Exemple #1
0
        public IEnumerable <RecentlyAddedMovieModel> GetRecentlyAddedMovies(DateTime from, DateTime to)
        {
            var plexMovies = _plex.GetAll().Where(x => x.Type == PlexMediaTypeEntity.Movie && x.AddedAt > from && x.AddedAt < to);
            var embyMovies = _emby.GetAll().Where(x => x.Type == EmbyMediaType.Movie && x.AddedAt > from && x.AddedAt < to);

            return(GetRecentlyAddedMovies(plexMovies, embyMovies).Take(30));
        }
Exemple #2
0
        private async Task StartPlexWithKnownContent(IEnumerable <int> contentids)
        {
            var everything = _plexRepo.GetAll().Where(x => contentids.Contains(x.Id));
            var allMovies  = everything.Where(x => x.Type == PlexMediaTypeEntity.Movie);

            await StartPlexMovies(allMovies);

            // Now Tv
            var allTv = everything.Where(x => x.Type == PlexMediaTypeEntity.Show);

            await StartPlexTv(allTv);
        }
Exemple #3
0
        private async Task StartPlex()
        {
            // Ensure we check that we have not linked this item to a request
            var allMovies = await _plexRepo.GetAll().Where(x =>
                                                           x.Type == PlexMediaTypeEntity.Movie && x.RequestId == null && (x.TheMovieDbId == null || x.ImdbId == null)).ToListAsync();

            await StartPlexMovies(allMovies);

            // Now Tv
            var allTv = await _plexRepo.GetAll().Where(x =>
                                                       x.Type == PlexMediaTypeEntity.Show && x.RequestId == null && (x.TheMovieDbId == null || x.ImdbId == null || x.TvDbId == null)).ToListAsync();

            await StartPlexTv(allTv);
        }
Exemple #4
0
        private async Task StartPlex()
        {
            // Ensure we check that we have not linked this item to a request
            var allMovies = _plexRepo.GetAll().Where(x =>
                                                     x.Type == PlexMediaTypeEntity.Movie && !x.RequestId.HasValue && (!x.TheMovieDbId.HasValue() || !x.ImdbId.HasValue()));

            await StartPlexMovies(allMovies);

            // Now Tv
            var allTv = _plexRepo.GetAll().Where(x =>
                                                 x.Type == PlexMediaTypeEntity.Show && !x.RequestId.HasValue && (!x.TheMovieDbId.HasValue() || !x.ImdbId.HasValue() || !x.TvDbId.HasValue()));

            await StartPlexTv(allTv);
        }
Exemple #5
0
        private async Task StartPlex(PlexSettings settings)
        {
            // Ensure we check that we have not linked this item to a request
            var allMovies = await _plexRepo.GetAll().Where(x =>
                                                           x.Type == MediaType.Movie && x.RequestId == null && ((x.TheMovieDbId == null || x.TheMovieDbId == string.Empty) || (x.ImdbId == null || x.ImdbId == string.Empty))).ToListAsync();

            await StartPlexMovies(allMovies, settings);

            // Now Tv
            var allTv = await _plexRepo.GetAll().Where(x =>
                                                       x.Type == MediaType.Series && x.RequestId == null && (x.TheMovieDbId == null || x.ImdbId == null || x.TvDbId == null)).ToListAsync();

            await StartPlexTv(allTv);
        }
Exemple #6
0
        public async Task ProcessEpsiodes(Metadata[] episodes, IQueryable <PlexEpisode> currentEpisodes)
        {
            var ep = new HashSet <PlexEpisode>();

            try
            {
                foreach (var episode in episodes)
                {
                    // I don't think we need to get the metadata, we only need to get the metadata if we need the provider id (TheTvDbid). Why do we need it for episodes?
                    // We have the parent and grandparent rating keys to link up to the season and series
                    //var metadata = _api.GetEpisodeMetaData(server.PlexAuthToken, server.FullUri, episode.ratingKey);

                    // This does seem to work, it looks like we can somehow get different rating, grandparent and parent keys with episodes. Not sure how.
                    var epExists = currentEpisodes.Any(x => episode.ratingKey == x.Key &&
                                                       episode.grandparentRatingKey == x.GrandparentKey);
                    if (epExists)
                    {
                        continue;
                    }

                    // Let's check if we have the parent
                    var seriesExists = await _repo.GetByKey(episode.grandparentRatingKey);

                    if (seriesExists == null)
                    {
                        // Ok let's try and match it to a title. TODO (This is experimental)
                        seriesExists = await _repo.GetAll().FirstOrDefaultAsync(x =>
                                                                                x.Title.Equals(episode.grandparentTitle, StringComparison.CurrentCultureIgnoreCase));

                        if (seriesExists == null)
                        {
                            _log.LogWarning(
                                "The episode title {0} we cannot find the parent series. The episode grandparentKey = {1}, grandparentTitle = {2}",
                                episode.title, episode.grandparentRatingKey, episode.grandparentTitle);
                            continue;
                        }

                        // Set the rating key to the correct one
                        episode.grandparentRatingKey = seriesExists.Key;
                    }

                    ep.Add(new PlexEpisode
                    {
                        EpisodeNumber  = episode.index,
                        SeasonNumber   = episode.parentIndex,
                        GrandparentKey = episode.grandparentRatingKey,
                        ParentKey      = episode.parentRatingKey,
                        Key            = episode.ratingKey,
                        Title          = episode.title
                    });
                }

                await _repo.AddRange(ep);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        /// <summary>
        /// We check if the request exists, if it does then we don't want to re-request it.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <returns></returns>
        public async Task <RuleResult> Execute(BaseRequest obj)
        {
            if (obj.RequestType == RequestType.TvShow)
            {
                var tvRequest = (ChildRequests)obj;

                var tvContent = _plexContent.GetAll().Include(x => x.Episodes).Where(x => x.Type == PlexMediaTypeEntity.Show);
                // We need to do a check on the TVDBId
                var anyMovieDbMatches = await tvContent.FirstOrDefaultAsync(x => x.TheMovieDbId.Length > 0 && x.TheMovieDbId == tvRequest.Id.ToString());

                if (anyMovieDbMatches == null)
                {
                    // So we do not have a TVDB Id, that really sucks.
                    // Let's try and match on the title and year of the show
                    var titleAndYearMatch = await tvContent.FirstOrDefaultAsync(x =>
                                                                                x.Title == tvRequest.Title &&
                                                                                x.ReleaseYear == tvRequest.ReleaseYear.Year.ToString());

                    if (titleAndYearMatch != null)
                    {
                        // We have a match! Surprise M**********r
                        return(CheckExistingContent(tvRequest, titleAndYearMatch));
                    }

                    // We do not have this
                    return(Success());
                }
                // looks like we have a match on the TVDbID
                return(CheckExistingContent(tvRequest, anyMovieDbMatches));
            }
            return(Success());
        }
Exemple #8
0
        private async Task StartPlexTv()
        {
            var allTv = _plexRepo.GetAll().Where(x =>
                                                 x.Type == PlexMediaTypeEntity.Show && (!x.TheMovieDbId.HasValue() || !x.ImdbId.HasValue() || !x.TvDbId.HasValue()));
            var tvCount = 0;

            foreach (var show in allTv)
            {
                var hasImdb       = show.ImdbId.HasValue();
                var hasTheMovieDb = show.TheMovieDbId.HasValue();
                var hasTvDbId     = show.TvDbId.HasValue();

                if (!hasTheMovieDb)
                {
                    var id = await GetTheMovieDbId(hasTvDbId, hasImdb, show.TvDbId, show.ImdbId, show.Title);

                    show.TheMovieDbId = id;
                }

                if (!hasImdb)
                {
                    var id = await GetImdbId(hasTheMovieDb, hasTvDbId, show.Title, show.TheMovieDbId, show.TvDbId);

                    show.ImdbId = id;
                    _plexRepo.UpdateWithoutSave(show);
                }

                if (!hasTvDbId)
                {
                    var id = await GetTvDbId(hasTheMovieDb, hasImdb, show.TheMovieDbId, show.ImdbId, show.Title);

                    show.TvDbId = id;
                    _plexRepo.UpdateWithoutSave(show);
                }
                tvCount++;
                if (tvCount >= 20)
                {
                    await _plexRepo.SaveChangesAsync();

                    tvCount = 0;
                }
            }
            await _plexRepo.SaveChangesAsync();
        }
Exemple #9
0
        public async Task Start(NewsletterSettings settings, bool test)
        {
            if (!settings.Enabled)
            {
                return;
            }
            var template = await _templateRepo.GetTemplate(NotificationAgent.Email, NotificationType.Newsletter);

            if (!template.Enabled)
            {
                return;
            }

            var emailSettings = await _emailSettings.GetSettingsAsync();

            if (!ValidateConfiguration(emailSettings))
            {
                return;
            }

            var customization = await _customizationSettings.GetSettingsAsync();

            // Get the Content
            var plexContent = _plex.GetAll().Include(x => x.Episodes).AsNoTracking();
            var embyContent = _emby.GetAll().Include(x => x.Episodes).AsNoTracking();

            var addedLog              = _recentlyAddedLog.GetAll();
            var addedPlexMovieLogIds  = addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Parent).Select(x => x.ContentId);
            var addedEmbyMoviesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Parent).Select(x => x.ContentId);

            var addedPlexEpisodesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Episode).Select(x => x.ContentId);
            var addedEmbyEpisodesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Episode).Select(x => x.ContentId);

            // Filter out the ones that we haven't sent yet
            var plexContentMoviesToSend = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie && !addedPlexMovieLogIds.Contains(x.Id));
            var embyContentMoviesToSend = embyContent.Where(x => x.Type == EmbyMediaType.Movie && !addedEmbyMoviesLogIds.Contains(x.Id));

            var plexEpisodesToSend = _plex.GetAllEpisodes().Include(x => x.Series).Where(x => !addedPlexEpisodesLogIds.Contains(x.Id)).AsNoTracking();
            var embyEpisodesToSend = _emby.GetAllEpisodes().Include(x => x.Series).Where(x => !addedEmbyEpisodesLogIds.Contains(x.Id)).AsNoTracking();

            var body = string.Empty;

            if (test)
            {
                var plexm = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                var embym = embyContent.Where(x => x.Type == EmbyMediaType.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                var plext = _plex.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.Series.AddedAt).Take(10);
                var embyt = _emby.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.AddedAt).Take(10);
                body = await BuildHtml(plexm, embym, plext, embyt);
            }
            else
            {
                body = await BuildHtml(plexContentMoviesToSend, embyContentMoviesToSend, plexEpisodesToSend, embyEpisodesToSend);

                if (body.IsNullOrEmpty())
                {
                    return;
                }
            }

            if (!test)
            {
                // Get the users to send it to
                var users = await _userManager.GetUsersInRoleAsync(OmbiRoles.RecievesNewsletter);

                if (!users.Any())
                {
                    return;
                }
                var emailTasks = new List <Task>();
                foreach (var user in users)
                {
                    if (user.Email.IsNullOrEmpty())
                    {
                        continue;
                    }

                    var messageContent = ParseTemplate(template, customization, user);
                    var email          = new NewsletterTemplate();

                    var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                    emailTasks.Add(_email.Send(
                                       new NotificationMessage {
                        Message = html, Subject = messageContent.Subject, To = user.Email
                    },
                                       emailSettings));
                }

                // Now add all of this to the Recently Added log
                var recentlyAddedLog = new HashSet <RecentlyAddedLog>();
                foreach (var p in plexContentMoviesToSend)
                {
                    recentlyAddedLog.Add(new RecentlyAddedLog
                    {
                        AddedAt     = DateTime.Now,
                        Type        = RecentlyAddedType.Plex,
                        ContentType = ContentType.Parent,
                        ContentId   = p.Id
                    });
                }

                foreach (var p in plexEpisodesToSend)
                {
                    recentlyAddedLog.Add(new RecentlyAddedLog
                    {
                        AddedAt     = DateTime.Now,
                        Type        = RecentlyAddedType.Plex,
                        ContentType = ContentType.Episode,
                        ContentId   = p.Id
                    });
                }

                foreach (var e in embyContentMoviesToSend)
                {
                    if (e.Type == EmbyMediaType.Movie)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt     = DateTime.Now,
                            Type        = RecentlyAddedType.Emby,
                            ContentType = ContentType.Parent,
                            ContentId   = e.Id
                        });
                    }
                }

                foreach (var p in embyEpisodesToSend)
                {
                    recentlyAddedLog.Add(new RecentlyAddedLog
                    {
                        AddedAt     = DateTime.Now,
                        Type        = RecentlyAddedType.Emby,
                        ContentType = ContentType.Episode,
                        ContentId   = p.Id
                    });
                }
                await _recentlyAddedLog.AddRange(recentlyAddedLog);

                await Task.WhenAll(emailTasks.ToArray());
            }
            else
            {
                var admins = await _userManager.GetUsersInRoleAsync(OmbiRoles.Admin);

                foreach (var a in admins)
                {
                    if (a.Email.IsNullOrEmpty())
                    {
                        continue;
                    }
                    var messageContent = ParseTemplate(template, customization, a);

                    var email = new NewsletterTemplate();

                    var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                    await _email.Send(
                        new NotificationMessage { Message = html, Subject = messageContent.Subject, To = a.Email },
                        emailSettings);
                }
            }
        }
Exemple #10
0
        public async Task Start(NewsletterSettings settings, bool test)
        {
            if (!settings.Enabled)
            {
                return;
            }
            var template = await _templateRepo.GetTemplate(NotificationAgent.Email, NotificationType.Newsletter);

            if (!template.Enabled)
            {
                return;
            }

            var emailSettings = await _emailSettings.GetSettingsAsync();

            if (!ValidateConfiguration(emailSettings))
            {
                return;
            }

            try
            {
                var customization = await _customizationSettings.GetSettingsAsync();

                // Get the Content
                var plexContent   = _plex.GetAll().Include(x => x.Episodes).AsNoTracking();
                var embyContent   = _emby.GetAll().Include(x => x.Episodes).AsNoTracking();
                var lidarrContent = _lidarrAlbumRepository.GetAll().Where(x => x.FullyAvailable).AsNoTracking();

                var addedLog              = _recentlyAddedLog.GetAll();
                var addedPlexMovieLogIds  = addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Parent).Select(x => x.ContentId).ToHashSet();
                var addedEmbyMoviesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Parent).Select(x => x.ContentId).ToHashSet();
                var addedAlbumLogIds      = addedLog.Where(x => x.Type == RecentlyAddedType.Lidarr && x.ContentType == ContentType.Album).Select(x => x.AlbumId).ToHashSet();

                var addedPlexEpisodesLogIds =
                    addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Episode);
                var addedEmbyEpisodesLogIds =
                    addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Episode);


                // Filter out the ones that we haven't sent yet
                var plexContentMoviesToSend   = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie && x.HasTheMovieDb && !addedPlexMovieLogIds.Contains(StringHelper.IntParseLinq(x.TheMovieDbId)));
                var embyContentMoviesToSend   = embyContent.Where(x => x.Type == EmbyMediaType.Movie && x.HasTheMovieDb && !addedEmbyMoviesLogIds.Contains(StringHelper.IntParseLinq(x.TheMovieDbId)));
                var lidarrContentAlbumsToSend = lidarrContent.Where(x => !addedAlbumLogIds.Contains(x.ForeignAlbumId)).ToHashSet();
                _log.LogInformation("Plex Movies to send: {0}", plexContentMoviesToSend.Count());
                _log.LogInformation("Emby Movies to send: {0}", embyContentMoviesToSend.Count());
                _log.LogInformation("Albums to send: {0}", lidarrContentAlbumsToSend.Count());

                var plexEpisodesToSend =
                    FilterPlexEpisodes(_plex.GetAllEpisodes().Include(x => x.Series).Where(x => x.Series.HasTvDb).AsNoTracking(), addedPlexEpisodesLogIds);
                var embyEpisodesToSend = FilterEmbyEpisodes(_emby.GetAllEpisodes().Include(x => x.Series).Where(x => x.Series.HasTvDb).AsNoTracking(),
                                                            addedEmbyEpisodesLogIds);

                _log.LogInformation("Plex Episodes to send: {0}", plexEpisodesToSend.Count());
                _log.LogInformation("Emby Episodes to send: {0}", embyEpisodesToSend.Count());
                var plexSettings = await _plexSettings.GetSettingsAsync();

                var embySettings = await _embySettings.GetSettingsAsync();

                var body = string.Empty;
                if (test)
                {
                    var plexm  = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                    var embym  = embyContent.Where(x => x.Type == EmbyMediaType.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                    var plext  = _plex.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.Series.AddedAt).Take(10).ToHashSet();
                    var embyt  = _emby.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.AddedAt).Take(10).ToHashSet();
                    var lidarr = lidarrContent.OrderByDescending(x => x.AddedAt).Take(10).ToHashSet();
                    body = await BuildHtml(plexm, embym, plext, embyt, lidarr, settings, embySettings, plexSettings);
                }
                else
                {
                    body = await BuildHtml(plexContentMoviesToSend, embyContentMoviesToSend, plexEpisodesToSend, embyEpisodesToSend, lidarrContentAlbumsToSend, settings, embySettings, plexSettings);

                    if (body.IsNullOrEmpty())
                    {
                        return;
                    }
                }

                if (!test)
                {
                    // Get the users to send it to
                    var users = await _userManager.GetUsersInRoleAsync(OmbiRoles.ReceivesNewsletter);

                    if (!users.Any())
                    {
                        return;
                    }

                    foreach (var emails in settings.ExternalEmails)
                    {
                        users.Add(new OmbiUser
                        {
                            UserName = emails,
                            Email    = emails
                        });
                    }

                    var messageContent = ParseTemplate(template, customization);
                    var email          = new NewsletterTemplate();

                    var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                    var bodyBuilder = new BodyBuilder
                    {
                        HtmlBody = html,
                    };

                    var message = new MimeMessage
                    {
                        Body    = bodyBuilder.ToMessageBody(),
                        Subject = messageContent.Subject
                    };

                    foreach (var user in users)
                    {
                        // Get the users to send it to
                        if (user.Email.IsNullOrEmpty())
                        {
                            continue;
                        }
                        // BCC the messages
                        message.Bcc.Add(new MailboxAddress(user.Email, user.Email));
                    }

                    // Send the email
                    await _email.Send(message, emailSettings);

                    // Now add all of this to the Recently Added log
                    var recentlyAddedLog = new HashSet <RecentlyAddedLog>();
                    foreach (var p in plexContentMoviesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt     = DateTime.Now,
                            Type        = RecentlyAddedType.Plex,
                            ContentType = ContentType.Parent,
                            ContentId   = StringHelper.IntParseLinq(p.TheMovieDbId),
                        });
                    }

                    foreach (var p in plexEpisodesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt       = DateTime.Now,
                            Type          = RecentlyAddedType.Plex,
                            ContentType   = ContentType.Episode,
                            ContentId     = StringHelper.IntParseLinq(p.Series.TvDbId),
                            EpisodeNumber = p.EpisodeNumber,
                            SeasonNumber  = p.SeasonNumber
                        });
                    }
                    foreach (var e in embyContentMoviesToSend)
                    {
                        if (e.Type == EmbyMediaType.Movie)
                        {
                            recentlyAddedLog.Add(new RecentlyAddedLog
                            {
                                AddedAt     = DateTime.Now,
                                Type        = RecentlyAddedType.Emby,
                                ContentType = ContentType.Parent,
                                ContentId   = StringHelper.IntParseLinq(e.TheMovieDbId),
                            });
                        }
                    }

                    foreach (var p in embyEpisodesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt       = DateTime.Now,
                            Type          = RecentlyAddedType.Emby,
                            ContentType   = ContentType.Episode,
                            ContentId     = StringHelper.IntParseLinq(p.Series.TvDbId),
                            EpisodeNumber = p.EpisodeNumber,
                            SeasonNumber  = p.SeasonNumber
                        });
                    }
                    await _recentlyAddedLog.AddRange(recentlyAddedLog);
                }
                else
                {
                    var admins = await _userManager.GetUsersInRoleAsync(OmbiRoles.Admin);

                    foreach (var a in admins)
                    {
                        if (a.Email.IsNullOrEmpty())
                        {
                            continue;
                        }
                        var messageContent = ParseTemplate(template, customization);

                        var email = new NewsletterTemplate();

                        var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                        await _email.Send(
                            new NotificationMessage { Message = html, Subject = messageContent.Subject, To = a.Email },
                            emailSettings);
                    }
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Error when attempting to create newsletter");
                throw;
            }
        }