Пример #1
0
        public void GetTmdbPoster(CancellationToken cancellationToken, MyRecordingInfo recording)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var pluginPath         = Plugin.Instance.ConfigurationFilePath.Remove(Plugin.Instance.ConfigurationFilePath.Length - 4);
            var localPoster        = Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + ".jpg");
            var localPosterMissing = Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + " [missing].jpg");

            if (!Directory.Exists(Path.Combine(pluginPath, "recordingposters")))
            {
                Directory.CreateDirectory(Path.Combine(pluginPath, "recordingposters"));
            }

            if (recording.IsMovie && !(File.Exists(localPoster) || File.Exists(localPosterMissing)))
            {
                try
                {
                    using (var tmdbMovieSearch = _httpClient.Get(new HttpRequestOptions()
                    {
                        Url = $"https://api.themoviedb.org/3/search/movie?api_key=9dbbec013a2d32baf38ccc58006cd991&query={recording.Name}" + $"&language={_serverConfigurationManager.Configuration.PreferredMetadataLanguage}",
                        CancellationToken = cancellationToken,
                        BufferContent = false,
                        EnableDefaultUserAgent = true,
                        AcceptHeader = "application/json",
                        EnableHttpCompression = true,
                        DecompressionMethod = CompressionMethod.Gzip
                    }).Result)
                    {
                        var movie = _json.DeserializeFromStream <TmdbMovieSearch>(tmdbMovieSearch);

                        if (movie.total_results > 0)
                        {
                            TmdbMovieResult tmdbMovieResult = movie.results.Find(x => x.title.Equals(recording.Name) || x.original_title.Contains(recording.EpisodeTitle)) ?? movie.results.First();

                            if (recording.Year.HasValue)
                            {
                                tmdbMovieResult = movie.results.Find(x => x.release_date.StartsWith(recording.Year.Value.ToString())) ?? movie.results.First();
                            }

                            var moviePoster = tmdbMovieResult.poster_path;

                            if (!String.IsNullOrEmpty(moviePoster))
                            {
                                using (WebClient client = new WebClient())
                                {
                                    client.DownloadFile(new Uri($"https://image.tmdb.org/t/p/w500{moviePoster}"), localPoster);
                                }
                            }
                            else
                            {
                                File.Create(localPosterMissing);
                            }
                        }
                        else
                        {
                            File.Create(localPosterMissing);
                        }
                    }
                }
                catch (WebException)
                {
                    Plugin.Logger.Info("Could not download poster for Movie Recording: {0}", recording.Name);
                }
            }

            if (recording.SeasonNumber.HasValue && recording.EpisodeNumber.HasValue && !(File.Exists(localPoster) || File.Exists(localPosterMissing)))
            {
                try
                {
                    using (var tmdbTvSearch = _httpClient.Get(new HttpRequestOptions()
                    {
                        Url = $"https://api.themoviedb.org/3/search/tv?api_key=9dbbec013a2d32baf38ccc58006cd991&query={recording.Name}" + $"&language={_serverConfigurationManager.Configuration.PreferredMetadataLanguage}",
                        CancellationToken = cancellationToken,
                        BufferContent = false,
                        EnableDefaultUserAgent = true,
                        AcceptHeader = "application/json",
                        EnableHttpCompression = true,
                        DecompressionMethod = CompressionMethod.Gzip
                    }).Result)
                    {
                        //var posterUrl = string.Empty;

                        //for (int i = 0; i < tvshow.results.Count; i++)
                        //{
                        //    TmdbTvResult tmdbTvResult = tvshow.results.ElementAt(i);
                        //
                        //    using (var tmdbEpisode = await _httpClient.Get(new HttpRequestOptions()
                        //    {
                        //        Url = $"https://api.themoviedb.org/3/tv/{tmdbTvResult.id}/season/{recording.SeasonNumber}/episode/{recording.EpisodeNumber}?api_key=9dbbec013a2d32baf38ccc58006cd991" + $"&language={_serverConfigurationManager.Configuration.UICulture}",
                        //        CancellationToken = cancellationToken,
                        //        BufferContent = false,
                        //        EnableDefaultUserAgent = true,
                        //        AcceptHeader = "application/json",
                        //        EnableHttpCompression = true,
                        //        DecompressionMethod = CompressionMethod.Gzip
                        //    }).ConfigureAwait(true))
                        //    {
                        //        var episode = _json.DeserializeFromStream<TmdbEpisodeResult>(tmdbEpisode);
                        //
                        //        if (episode.name == recording.EpisodeTitle)
                        //        {
                        //            posterUrl = $"https://image.tmdb.org/t/p/original{tmdbTvResult.poster_path}";
                        //            break;
                        //        }
                        //    }
                        //
                        //    Thread.Sleep(400);
                        //}

                        var tvshow = _json.DeserializeFromStream <TmdbTvSearch>(tmdbTvSearch);

                        if (tvshow.total_results > 0)
                        {
                            TmdbTvResult tmdbTvResult = tvshow.results.Find(x => x.name.Equals(recording.Name)) ?? tvshow.results.First();
                            var          tvPoster     = tmdbTvResult.poster_path;

                            if (!String.IsNullOrEmpty(tvPoster))
                            {
                                using (WebClient client = new WebClient())
                                {
                                    client.DownloadFile(new Uri($"https://image.tmdb.org/t/p/w500{tvPoster}"), localPoster);
                                }
                            }
                            else
                            {
                                File.Create(localPosterMissing);
                            }
                        }
                        else
                        {
                            File.Create(localPosterMissing);
                        }
                    }
                }
                catch (WebException)
                {
                    Plugin.Logger.Info("Could not download poster for TV Show Recording: {0}", recording.Name);
                }
            }
        }
Пример #2
0
        private MyRecordingInfo GetRecordingInfo(Recording i)
        {
            var genreMapper = new GenreMapper(Plugin.Instance.Configuration);
            var info        = new MyRecordingInfo();

            try
            {
                info.Id = i.id.ToString(_usCulture);
                if (i.recurring)
                {
                    info.SeriesTimerId = i.recurringParent.ToString(_usCulture);
                }

                if (i.file != null)
                {
                    if (Plugin.Instance.Configuration.RecordingTransport == 2)
                    {
                        info.Url = i.file;
                    }
                    else
                    {
                        info.Url = String.Format("{0}/live?recording={1}", _baseUrl, i.id);
                    }
                }

                info.Status    = ParseStatus(i.status);
                info.StartDate = DateTimeOffset.FromUnixTimeSeconds(i.startTime).DateTime;
                info.EndDate   = DateTimeOffset.FromUnixTimeSeconds(i.startTime + i.duration).DateTime;

                info.ProgramId    = i.epgEventId.ToString(_usCulture);
                info.EpisodeTitle = i.subtitle;
                info.Name         = i.name;
                info.Overview     = i.desc;
                info.Genres       = i.genres;
                info.IsRepeat     = !i.firstrun;
                info.ChannelId    = i.channelId.ToString(_usCulture);
                info.ChannelType  = ChannelType.TV;
                info.ImageUrl     = _baseUrl + "/service?method=channel.show.artwork&prefer=landscape&name=" + Uri.EscapeDataString(i.name);
                info.HasImage     = true;
                if (i.season.HasValue)
                {
                    info.SeasonNumber  = i.season;
                    info.EpisodeNumber = i.episode;
                    info.IsSeries      = true; //!string.IsNullOrEmpty(epg.Subtitle); http://emby.media/community/index.php?/topic/21264-series-record-ability-missing-in-emby-epg/#entry239633
                }
                if (i.original != null)
                {
                    info.OriginalAirDate = i.original;
                }
                info.ProductionYear = i.year;
                //info.CommunityRating = ListingsResponse.ParseCommunityRating(epg.StarRating);
                //info.IsHD = true;
                //info.Audio = ProgramAudio.Stereo;

                info.OfficialRating = i.rating;

                if (info.Genres != null)
                {
                    info.Genres = i.genres;
                    genreMapper.PopulateRecordingGenres(info);
                }
                else
                {
                    info.Genres = new List <string>();
                }
                return(info);
            }
            catch (Exception err)
            {
                throw (err);
            }
        }
Пример #3
0
        private MyRecordingInfo GetRecordingInfo(EpgEventJSONObject i)
        {
            var info = new MyRecordingInfo();

            var recurr = i.recurr;

            if (recurr != null)
            {
                if (recurr.OID != 0)
                {
                    info.SeriesTimerId = recurr.OID.ToString(_usCulture);
                }
            }

            var schd = i.schd;

            if (schd != null)
            {
                info.ChannelId = schd.ChannelOid.ToString(_usCulture);
                info.Id        = schd.OID.ToString(_usCulture);
                if (_fileSystem.FileExists(schd.RecordingFileName))
                {
                    info.Path = schd.RecordingFileName;
                }
                else
                {
                    info.Url = _baseUrl + "/live?recording=" + schd.OID;
                }

                info.Status    = ParseStatus(schd.Status);
                info.StartDate = DateTime.Parse(schd.StartTime).ToUniversalTime();
                info.EndDate   = DateTime.Parse(schd.EndTime).ToUniversalTime();

                info.IsHD     = string.Equals(schd.Quality, "hdtv", StringComparison.OrdinalIgnoreCase);
                info.ImageUrl = string.IsNullOrEmpty(schd.FanArt) ? null : (_baseUrl + "/" + schd.FanArt);
                info.HasImage = !string.IsNullOrEmpty(schd.FanArt);
            }

            var epg = i.epgEvent;

            if (epg != null)
            {
                info.Audio           = ListingsResponse.ParseAudio(epg.Audio);
                info.ProgramId       = epg.OID.ToString(_usCulture);
                info.OfficialRating  = epg.Rating;
                info.EpisodeTitle    = epg.Subtitle;
                info.Name            = epg.Title;
                info.Overview        = epg.Desc;
                info.Genres          = epg.Genres.Where(g => !string.IsNullOrWhiteSpace(g)).ToList();
                info.IsRepeat        = !epg.FirstRun;
                info.IsSeries        = true; //!string.IsNullOrEmpty(epg.Subtitle); http://emby.media/community/index.php?/topic/21264-series-record-ability-missing-in-emby-epg/#entry239633
                info.CommunityRating = ListingsResponse.ParseCommunityRating(epg.StarRating);
                info.IsHD            = string.Equals(epg.Quality, "hdtv", StringComparison.OrdinalIgnoreCase);
                info.IsNews          = epg.Genres.Contains("news", StringComparer.OrdinalIgnoreCase);
                info.IsMovie         = epg.Genres.Contains("movie", StringComparer.OrdinalIgnoreCase);
                info.IsKids          = epg.Genres.Contains("kids", StringComparer.OrdinalIgnoreCase);

                info.IsSports = epg.Genres.Contains("sports", StringComparer.OrdinalIgnoreCase) ||
                                epg.Genres.Contains("Sports non-event", StringComparer.OrdinalIgnoreCase) ||
                                epg.Genres.Contains("Sports event", StringComparer.OrdinalIgnoreCase) ||
                                epg.Genres.Contains("Sports talk", StringComparer.OrdinalIgnoreCase) ||
                                epg.Genres.Contains("Sports news", StringComparer.OrdinalIgnoreCase);
            }

            return(info);
        }
Пример #4
0
        public IEnumerable <MyRecordingInfo> GetRecordings(CancellationToken cancellationToken)
        {
            var pluginPath  = Plugin.Instance.ConfigurationFilePath.Remove(Plugin.Instance.ConfigurationFilePath.Length - 4);
            var localPath   = String.Format("{0}", Configuration.LocalFilePath);
            var remotePath  = String.Format("{0}", Configuration.RemoteFilePath);
            var genreMapper = new GenreMapper(Plugin.Instance.Configuration);
            var lastName    = string.Empty;

            var schedules = GetFromService <Timers>(cancellationToken, typeof(Timers), "api/timerlist.html?utf8=2");
            var response  = GetFromService <Recordings>(cancellationToken, typeof(Recordings), "api/recordings.html?utf8=1&images=1");

            Plugin.Logger.Info("Found overall Recordings: {0} ", response.Recording.Count());
            return(response.Recording.Select(r =>
            {
                var recording = new MyRecordingInfo()
                {
                    Id = r.Id,
                    Name = r.Name,
                    EpisodeTitle = r.EpisodeTitle,
                    EpisodeNumber = r.EpisodeNumber,
                    SeasonNumber = r.SeasonNumber,
                    Year = r.Year,
                    Overview = r.Overview,
                    EitContent = r.EitContent,
                    SeriesTimerId = r.Series,
                    ChannelId = r.ChannelId,
                    ChannelName = r.ChannelName,
                    ChannelType = ChannelType.TV,
                    StartDate = DateTime.ParseExact(r.Start, "yyyyMMddHHmmss", CultureInfo.InvariantCulture).ToUniversalTime(),
                    EndDate = DateTime.ParseExact(r.Start, "yyyyMMddHHmmss", CultureInfo.InvariantCulture).Add(TimeSpan.ParseExact(r.Duration, "hhmmss", CultureInfo.InvariantCulture)).ToUniversalTime(),
                    Path = r.File,
                };

                if (!String.IsNullOrEmpty(r.EitContent) || !String.IsNullOrEmpty(r.Overview))
                {
                    genreMapper.PopulateRecordingGenres(recording);
                }

                if (recording.IsMovie)
                {
                    recording.Name = r.MovieName;
                }

                if ((recording.StartDate <= DateTime.Now.ToUniversalTime()) && (recording.EndDate >= DateTime.Now.ToUniversalTime()))
                {
                    var timers = schedules.Timer.Where(t => GeneralExtensions.GetScheduleTime(t.Date, t.Start).AddMinutes(t.PreEPG) == recording.StartDate && t.Recording == "-1").FirstOrDefault();

                    if (timers != null)
                    {
                        recording.Status = RecordingStatus.InProgress;
                    }
                }
                else
                {
                    recording.Status = RecordingStatus.Completed;

                    if (!String.IsNullOrEmpty(r.Image))
                    {
                        recording.ImageUrl = _wssProxy.GetRecordingImage(r.Image);
                    }
                }

                if (Configuration.RequiresPathSubstitution)
                {
                    recording.Path = r.File.Replace(localPath, remotePath);
                }

                if (Configuration.EnableTmdbLookup)
                {
                    if (recording.Name != lastName)
                    {
                        _tmdbLookup.GetTmdbPoster(cancellationToken, recording);
                    }
                    lastName = recording.Name;
                }

                if (File.Exists(Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + ".jpg")))
                {
                    recording.TmdbPoster = Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + ".jpg");
                }

                Plugin.Logger.Info("Found Recording: {0} - {1}, Series: {2}, Id: {3}, status: {4}", r.Name, r.EpisodeTitle, r.Series, r.Id, recording.Status);
                return recording;
            }));
        }
        public Task <IEnumerable <MyRecordingInfo> > buildDvrInfos(CancellationToken cancellationToken)
        {
            return(Task.Factory.StartNew <IEnumerable <MyRecordingInfo> >(() =>
            {
                lock (_data)
                {
                    List <MyRecordingInfo> result = new List <MyRecordingInfo>();
                    foreach (KeyValuePair <string, HTSMessage> entry in _data)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            _logger.LogInformation("[TVHclient] DvrDataHelper.buildDvrInfos, call canceled - returning part list.");
                            return result;
                        }

                        HTSMessage m = entry.Value;
                        MyRecordingInfo ri = new MyRecordingInfo();

                        try
                        {
                            if (m.containsField("error"))
                            {
                                // When TVHeadend recordings are removed, their info can
                                // still be kept around with a status of "completed".
                                // The only way to identify them is from the error string
                                // which is set to "File missing". Use that to not show
                                // non-existing deleted recordings.
                                if (m.getString("error").Contains("missing"))
                                {
                                    continue;
                                }
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("id"))
                            {
                                ri.Id = "" + m.getInt("id");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("path"))
                            {
                                ri.Path = "" + m.getString("path");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("url"))
                            {
                                ri.Url = "" + m.getString("url");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("channel"))
                            {
                                ri.ChannelId = "" + m.getInt("channel");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("start"))
                            {
                                long unixUtc = m.getLong("start");
                                ri.StartDate = _initialDateTimeUTC.AddSeconds(unixUtc).ToUniversalTime();
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("stop"))
                            {
                                long unixUtc = m.getLong("stop");
                                ri.EndDate = _initialDateTimeUTC.AddSeconds(unixUtc).ToUniversalTime();
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("title"))
                            {
                                ri.Name = m.getString("title");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("description"))
                            {
                                ri.Overview = m.getString("description");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("summary"))
                            {
                                ri.EpisodeTitle = m.getString("summary");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        ri.HasImage = false;
                        // public string ImagePath { get; set; }
                        // public string ImageUrl { get; set; }

                        try
                        {
                            if (m.containsField("state"))
                            {
                                string state = m.getString("state");
                                switch (state)
                                {
                                case "completed":
                                    ri.Status = RecordingStatus.Completed;
                                    break;

                                case "scheduled":
                                    ri.Status = RecordingStatus.New;
                                    continue;

                                //break;
                                case "missed":
                                    ri.Status = RecordingStatus.Error;
                                    break;

                                case "recording":
                                    ri.Status = RecordingStatus.InProgress;
                                    break;

                                default:
                                    _logger.LogCritical("[TVHclient] DvrDataHelper.buildDvrInfos: state '{state}' not handled!", state);
                                    continue;
                                    //break;
                                }
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        // Path must not be set to force emby use of the LiveTvService methods!!!!
                        //if (m.containsField("path"))
                        //{
                        //    ri.Path = m.getString("path");
                        //}

                        try
                        {
                            if (m.containsField("autorecId"))
                            {
                                ri.SeriesTimerId = m.getString("autorecId");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        try
                        {
                            if (m.containsField("eventId"))
                            {
                                ri.ProgramId = "" + m.getInt("eventId");
                            }
                        }
                        catch (InvalidCastException)
                        {
                        }

                        /*
                         *      public ProgramAudio? Audio { get; set; }
                         *      public ChannelType ChannelType { get; set; }
                         *      public float? CommunityRating { get; set; }
                         *      public List<string> Genres { get; set; }
                         *      public bool? IsHD { get; set; }
                         *      public bool IsKids { get; set; }
                         *      public bool IsLive { get; set; }
                         *      public bool IsMovie { get; set; }
                         *      public bool IsNews { get; set; }
                         *      public bool IsPremiere { get; set; }
                         *      public bool IsRepeat { get; set; }
                         *      public bool IsSeries { get; set; }
                         *      public bool IsSports { get; set; }
                         *      public string OfficialRating { get; set; }
                         *      public DateTime? OriginalAirDate { get; set; }
                         *      public string Url { get; set; }
                         */

                        result.Add(ri);
                    }
                    return result;
                }
            }));
        }
Пример #6
0
        /// <summary>
        /// Populates the recording genres.
        /// </summary>
        /// <param name="recording">The recording.</param>
        public void PopulateRecordingGenres(MyRecordingInfo recording)
        {
            if (recording != null && recording.EitContent != null && _configuration.EitContent)
            {
                recording.IsMovie  = _eitMovieContent.Any(c => recording.EitContent.Contains(c));
                recording.IsSports = _eitSportContent.Any(c => recording.EitContent.Contains(c));
                recording.IsNews   = _eitNewsContent.Any(c => recording.EitContent.Contains(c));
                recording.IsKids   = _eitKidsContent.Any(c => recording.EitContent.Contains(c));
                recording.IsLive   = _eitLiveContent.Any(c => recording.EitContent.Contains(c));
                recording.IsSeries = _eitSeriesContent.Any(c => recording.EitContent.Contains(c));

                if (recording.EpisodeNumber.HasValue)
                {
                    if (!recording.IsMovie && !recording.IsSports && !recording.IsNews && !recording.IsKids && !recording.IsLive)
                    {
                        recording.IsSeries = true;
                    }
                }
            }

            // Check there is a recording and genres to map
            if (recording != null && recording.Overview != null && !_configuration.EitContent)
            {
                recording.Genres = new List <String>();

                if (_movieGenres.All(g => !string.IsNullOrWhiteSpace(g)) && recording.SeasonNumber == null && recording.EpisodeNumber == null)
                {
                    var genre = _movieGenres.FirstOrDefault(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);

                    if (!String.IsNullOrWhiteSpace(genre))
                    {
                        genre = Regex.Replace(genre, @"^\w+\W\s?|\s\(\w+\)$", String.Empty, RegexOptions.IgnoreCase);
                        recording.Genres.Add(genre);
                    }

                    recording.IsMovie = _movieGenres.Any(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);
                }

                if (_sportGenres.All(g => !string.IsNullOrWhiteSpace(g)))
                {
                    var genre = _sportGenres.FirstOrDefault(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);

                    if (!String.IsNullOrWhiteSpace(genre))
                    {
                        genre = Regex.Replace(genre, @"^\w+\W\s?|\s\(\w+\)$", String.Empty, RegexOptions.IgnoreCase);
                        recording.Genres.Add(genre);
                    }

                    recording.IsSports = _sportGenres.Any(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);
                }

                if (_newsGenres.All(g => !string.IsNullOrWhiteSpace(g)))
                {
                    var genre = _newsGenres.FirstOrDefault(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);

                    if (!String.IsNullOrWhiteSpace(genre))
                    {
                        genre = Regex.Replace(genre, @"^\w+\W\s?|\s\(\w+\)$", String.Empty, RegexOptions.IgnoreCase);
                        recording.Genres.Add(genre);
                    }

                    recording.IsNews = _newsGenres.Any(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);
                }

                if (_kidsGenres.All(g => !string.IsNullOrWhiteSpace(g)))
                {
                    var genre = _kidsGenres.FirstOrDefault(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);

                    if (!String.IsNullOrWhiteSpace(genre))
                    {
                        genre = Regex.Replace(genre, @"^\w+\W\s?|\s\(\w+\)$", String.Empty, RegexOptions.IgnoreCase);
                        recording.Genres.Add(genre);
                    }

                    recording.IsKids = _kidsGenres.Any(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);
                }

                if (_liveGenres.All(g => !string.IsNullOrWhiteSpace(g)))
                {
                    var genre = _liveGenres.FirstOrDefault(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);

                    if (!String.IsNullOrWhiteSpace(genre))
                    {
                        genre = Regex.Replace(genre, @"^\w+\W\s?|\s\(\w+\)$", String.Empty, RegexOptions.IgnoreCase);
                        recording.Genres.Add(genre);
                    }

                    recording.IsLive = _liveGenres.Any(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);
                }

                if (_seriesGenres.All(g => !string.IsNullOrWhiteSpace(g)))
                {
                    var genre = _seriesGenres.FirstOrDefault(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);

                    if (!String.IsNullOrWhiteSpace(genre))
                    {
                        genre = Regex.Replace(genre, @"^\w+\W\s?|\s\(\w+\)$", String.Empty, RegexOptions.IgnoreCase);
                        recording.Genres.Add(genre);
                    }

                    recording.IsSeries = _seriesGenres.Any(g => recording.Overview.IndexOf(g, StringComparison.InvariantCulture) != -1);
                }

                if (_seriesGenres.All(g => string.IsNullOrWhiteSpace(g)) && recording.EpisodeNumber.HasValue)
                {
                    if (!recording.IsMovie && !recording.IsSports && !recording.IsNews && !recording.IsKids && !recording.IsLive)
                    {
                        recording.IsSeries = true;
                    }
                }
            }
        }
Пример #7
0
        public void GetTmdbImage(CancellationToken cancellationToken, MyRecordingInfo recording)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var config            = Plugin.Instance.Configuration;
            var pluginPath        = Plugin.Instance.ConfigurationFilePath.Remove(Plugin.Instance.ConfigurationFilePath.Length - 4);
            var localImage        = Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + ".jpg");
            var localImageMissing = Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + " [missing].jpg");

            if (!Directory.Exists(Path.Combine(pluginPath, "recordingposters")))
            {
                Directory.CreateDirectory(Path.Combine(pluginPath, "recordingposters"));
            }

            if ((recording.IsMovie || (!recording.EpisodeNumber.HasValue && (recording.EndDate - recording.StartDate) > TimeSpan.FromMinutes(70))) && !(File.Exists(localImage) || File.Exists(localImageMissing)))
            {
                try
                {
                    using (var tmdbMovieSearch = _httpClient.Get(new HttpRequestOptions()
                    {
                        Url = $"https://api.themoviedb.org/3/search/movie?api_key=9dbbec013a2d32baf38ccc58006cd991&query={recording.MovieName}" + $"&language={_serverConfigurationManager.Configuration.PreferredMetadataLanguage}",
                        CancellationToken = cancellationToken,
                        BufferContent = false,
                        EnableDefaultUserAgent = true,
                        AcceptHeader = "application/json",
                        EnableHttpCompression = true,
                        DecompressionMethod = CompressionMethod.Gzip
                    }).Result)
                    {
                        var movie = _json.DeserializeFromStream <TmdbMovieSearch>(tmdbMovieSearch);

                        if (movie.total_results > 0)
                        {
                            TmdbMovieResult tmdbMovieResult = movie.results.Find(x => x.title.Equals(recording.MovieName) || x.original_title.Contains(recording.EpisodeTitle)) ?? movie.results.First();

                            if (recording.MovieYear.HasValue)
                            {
                                tmdbMovieResult = movie.results.Find(x => x.release_date.StartsWith(recording.MovieYear.Value.ToString())) ?? movie.results.First();
                            }

                            var moviePoster   = tmdbMovieResult.poster_path;
                            var movieBackdrop = tmdbMovieResult.backdrop_path;

                            if (config.RecGenreMapping)
                            {
                                if (!String.IsNullOrEmpty(moviePoster))
                                {
                                    using (WebClient client = new WebClient())
                                    {
                                        client.DownloadFile(new Uri($"https://image.tmdb.org/t/p/w500{moviePoster}"), localImage);
                                    }
                                }
                                else
                                {
                                    File.Create(localImageMissing);
                                }
                            }

                            if (!config.RecGenreMapping)
                            {
                                if (!String.IsNullOrEmpty(movieBackdrop))
                                {
                                    using (WebClient client = new WebClient())
                                    {
                                        client.DownloadFile(new Uri($"https://image.tmdb.org/t/p/w500{movieBackdrop}"), localImage);
                                    }
                                }
                                else
                                {
                                    File.Create(localImageMissing);
                                }
                            }
                        }
                        else
                        {
                            File.Create(localImageMissing);
                        }
                    }
                }
                catch (WebException)
                {
                    Plugin.Logger.Info("Could not download poster for Movie Recording: {0}", recording.Name);
                }
            }

            if ((recording.IsSeries || recording.EpisodeNumber.HasValue) && !(File.Exists(localImage) || File.Exists(localImageMissing)))
            {
                try
                {
                    using (var tmdbTvSearch = _httpClient.Get(new HttpRequestOptions()
                    {
                        Url = $"https://api.themoviedb.org/3/search/tv?api_key=9dbbec013a2d32baf38ccc58006cd991&query={recording.Name}" + $"&language={_serverConfigurationManager.Configuration.PreferredMetadataLanguage}",
                        CancellationToken = cancellationToken,
                        BufferContent = false,
                        EnableDefaultUserAgent = true,
                        AcceptHeader = "application/json",
                        EnableHttpCompression = true,
                        DecompressionMethod = CompressionMethod.Gzip
                    }).Result)
                    {
                        var tvshow = _json.DeserializeFromStream <TmdbTvSearch>(tmdbTvSearch);

                        if (tvshow.total_results > 0)
                        {
                            TmdbTvResult tmdbTvResult = tvshow.results.Find(x => x.name.Equals(recording.Name)) ?? tvshow.results.First();

                            var tvPoster   = tmdbTvResult.poster_path;
                            var tvBackdrop = tmdbTvResult.backdrop_path;

                            if (config.RecGenreMapping)
                            {
                                if (!String.IsNullOrEmpty(tvPoster))
                                {
                                    using (WebClient client = new WebClient())
                                    {
                                        client.DownloadFile(new Uri($"https://image.tmdb.org/t/p/w500{tvPoster}"), localImage);
                                    }
                                }
                                else
                                {
                                    File.Create(localImageMissing);
                                }
                            }

                            if (!config.RecGenreMapping)
                            {
                                if (!String.IsNullOrEmpty(tvBackdrop))
                                {
                                    using (WebClient client = new WebClient())
                                    {
                                        client.DownloadFile(new Uri($"https://image.tmdb.org/t/p/w500{tvBackdrop}"), localImage);
                                    }
                                }
                                else
                                {
                                    File.Create(localImageMissing);
                                }
                            }
                        }
                        else
                        {
                            File.Create(localImageMissing);
                        }
                    }
                }
                catch (WebException)
                {
                    Plugin.Logger.Info("Could not download poster for TV Show Recording: {0}", recording.Name);
                }
            }
        }
Пример #8
0
    private MyRecordingInfo GetRecordingInfo(Recording i)
    {
        var genreMapper = new GenreMapper(Plugin.Instance.Configuration);
        var info        = new MyRecordingInfo();

        info.Id = i.Id.ToString(CultureInfo.InvariantCulture);
        if (i.Recurring)
        {
            info.SeriesTimerId = i.RecurringParent.ToString(CultureInfo.InvariantCulture);
        }

        if (i.File != null)
        {
            if (Plugin.Instance.Configuration.RecordingTransport == 2)
            {
                info.Url = i.File;
            }
            else
            {
                info.Url = $"{_baseUrl}/live?recording={i.Id}";
            }
        }

        info.Status    = ParseStatus(i.Status);
        info.StartDate = DateTimeOffset.FromUnixTimeSeconds(i.StartTime).DateTime;
        info.EndDate   = DateTimeOffset.FromUnixTimeSeconds(i.StartTime + i.Duration).DateTime;

        info.ProgramId    = i.EpgEventId.ToString(CultureInfo.InvariantCulture);
        info.EpisodeTitle = i.Subtitle;
        info.Name         = i.Name;
        info.Overview     = i.Desc;
        info.Genres       = i.Genres;
        info.IsRepeat     = !i.Firstrun;
        info.ChannelId    = i.ChannelId.ToString(CultureInfo.InvariantCulture);
        info.ChannelType  = ChannelType.TV;
        info.ImageUrl     = _baseUrl + "/service?method=channel.show.artwork&prefer=landscape&name=" + Uri.EscapeDataString(i.Name);
        info.HasImage     = true;
        if (i.Season.HasValue)
        {
            info.SeasonNumber  = i.Season;
            info.EpisodeNumber = i.Episode;
            info.IsSeries      = true;
        }

        if (i.Original != null)
        {
            info.OriginalAirDate = i.Original;
        }

        info.ProductionYear = i.Year;
        info.OfficialRating = i.Rating;

        if (info.Genres != null)
        {
            info.Genres = i.Genres;
            genreMapper.PopulateRecordingGenres(info);
        }
        else
        {
            info.Genres = new List <string>();
        }

        return(info);
    }
Пример #9
0
        public IEnumerable <MyRecordingInfo> GetRecordings(CancellationToken cancellationToken)
        {
            var pluginPath  = Plugin.Instance.ConfigurationFilePath.Remove(Plugin.Instance.ConfigurationFilePath.Length - 4);
            var localPath   = String.Format("{0}", Configuration.LocalFilePath);
            var remotePath  = String.Format("{0}", Configuration.RemoteFilePath);
            var genreMapper = new GenreMapper(Plugin.Instance.Configuration);
            var lastName    = string.Empty;

            var recordings = GetFromService <List <Recording> >(cancellationToken, "GetRecordings").Select(r =>
            {
                var recording = new MyRecordingInfo()
                {
                    Id            = r.Id,
                    Name          = r.Title,
                    EpisodeTitle  = r.EpisodeName,
                    EpisodeNumber = r.EpisodeNumber,
                    SeasonNumber  = r.SeasonNumber,
                    Overview      = r.Description,
                    Year          = r.Year,
                    Genres        = new List <String>(),
                    TimerId       = r.ScheduleId.ToString(CultureInfo.InvariantCulture),
                    ChannelId     = r.ChannelId.ToString(CultureInfo.InvariantCulture),
                    ChannelName   = r.ChannelName,
                    ChannelType   = ChannelType.TV,
                    StartDate     = r.StartTime,
                    EndDate       = r.EndTime,
                    Status        = (r.IsRecording) ? RecordingStatus.InProgress : RecordingStatus.Completed,
                    Path          = r.FileName,
                };

                //recording.IsSeries = true; //is set by genreMapper
                if (!String.IsNullOrEmpty(r.Genre))
                {
                    recording.Genres.Add(r.Genre);
                    genreMapper.PopulateRecordingGenres(recording);
                }

                if (recording.IsMovie)
                {
                    recording.Name = r.MovieName;
                }

                if (r.IsRecording)
                {
                    var schedule      = GetSchedule(cancellationToken, r.ScheduleId.ToString());
                    recording.EndDate = schedule.EndTime + TimeSpan.FromMinutes(schedule.PostRecordInterval);
                }

                if (!r.IsRecording)
                {
                    recording.ImageUrl = _wssProxy.GetRecordingImage(r.Id);
                }

                if (Configuration.RequiresPathSubstitution)
                {
                    recording.Path = r.FileName.Replace(localPath, remotePath);
                }

                if (Configuration.EnableTmdbLookup)
                {
                    if (recording.Name != lastName)
                    {
                        _tmdbLookup.GetTmdbPoster(cancellationToken, recording);
                    }
                    lastName = recording.Name;
                }

                if (File.Exists(Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + ".jpg")))
                {
                    recording.TmdbPoster = Path.Combine(pluginPath, "recordingposters", String.Join("", recording.Name.Split(Path.GetInvalidFileNameChars())) + ".jpg");
                }

                return(recording);
            }).ToList();

            Plugin.Logger.Info("Found recordings: {0} ", recordings.Count());
            return(recordings);
        }