Exemplo n.º 1
0
        private async Task <InternalMediaInfoResult> GetMediaInfo(BaseItem item, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var idString  = item.Id.ToString("N");
            var cachePath = Path.Combine(_appPaths.CachePath,
                                         "ffprobe-audio",
                                         idString.Substring(0, 2), idString, "v" + SchemaVersion + _mediaEncoder.Version + item.DateModified.Ticks.ToString(_usCulture) + ".json");

            try
            {
                return(_json.DeserializeFromFile <InternalMediaInfoResult>(cachePath));
            }
            catch (FileNotFoundException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }

            var inputPath = new[] { item.Path };

            var result = await _mediaEncoder.GetMediaInfo(inputPath, MediaProtocol.File, false, cancellationToken).ConfigureAwait(false);

            Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
            _json.SerializeToFile(result, cachePath);

            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Fetches the images.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="language">The language.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MovieImages}.</returns>
        private async Task <MovieDbSeriesProvider.Images> FetchImages(BaseItem item, string language, IJsonSerializer jsonSerializer,
                                                                      CancellationToken cancellationToken)
        {
            var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);

            if (string.IsNullOrEmpty(tmdbId))
            {
                return(null);
            }

            await MovieDbSeriesProvider.Current.EnsureSeriesInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);

            var path = MovieDbSeriesProvider.Current.GetDataFilePath(tmdbId, language);

            if (!string.IsNullOrEmpty(path))
            {
                var fileInfo = new FileInfo(path);

                if (fileInfo.Exists)
                {
                    return(jsonSerializer.DeserializeFromFile <MovieDbSeriesProvider.RootObject>(path).images);
                }
            }

            return(null);
        }
Exemplo n.º 3
0
        private async Task <InternalMediaInfoResult> GetMediaInfo(Video item,
                                                                  IIsoMount isoMount,
                                                                  CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var idString  = item.Id.ToString("N");
            var cachePath = Path.Combine(_appPaths.CachePath,
                                         "ffprobe-video",
                                         idString.Substring(0, 2), idString, "v" + SchemaVersion + _mediaEncoder.Version + item.DateModified.Ticks.ToString(_usCulture) + ".json");

            try
            {
                return(_json.DeserializeFromFile <InternalMediaInfoResult>(cachePath));
            }
            catch (FileNotFoundException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }

            var protocol = item.LocationType == LocationType.Remote
                ? MediaProtocol.Http
                : MediaProtocol.File;

            var inputPath = MediaEncoderHelpers.GetInputArgument(item.Path, protocol, isoMount, item.PlayableStreamFileNames);

            var result = await _mediaEncoder.GetMediaInfo(inputPath, protocol, false, cancellationToken).ConfigureAwait(false);

            Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
            _json.SerializeToFile(result, cachePath);

            return(result);
        }
Exemplo n.º 4
0
        /// <inheritdoc />
        public async Task <MetadataResult <MusicAlbum> > GetMetadata(AlbumInfo info, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <MusicAlbum>();

            // TODO maybe remove when artist metadata can be disabled
            if (!Plugin.Instance.Configuration.Enable)
            {
                return(result);
            }

            var id = info.GetReleaseGroupId();

            if (!string.IsNullOrWhiteSpace(id))
            {
                await EnsureInfo(id, cancellationToken).ConfigureAwait(false);

                var path = GetAlbumInfoPath(_config.ApplicationPaths, id);

                var obj = _json.DeserializeFromFile <RootObject>(path);

                if (obj != null && obj.album != null && obj.album.Count > 0)
                {
                    result.Item        = new MusicAlbum();
                    result.HasMetadata = true;
                    ProcessResult(result.Item, obj.album[0], info.MetadataLanguage);
                }
            }

            return(result);
        }
Exemplo n.º 5
0
        public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder)
        {
            _logger         = logger;
            _fileSystem     = fileSystem;
            _jsonSerializer = jsonSerializer;
            _mediaEncoder   = mediaEncoder;
            _appPaths       = appPaths;

            _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);

            Dictionary <Guid, ImageSize> sizeDictionary;

            try
            {
                sizeDictionary = jsonSerializer.DeserializeFromFile <Dictionary <Guid, ImageSize> >(ImageSizeFile) ??
                                 new Dictionary <Guid, ImageSize>();
            }
            catch (FileNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error parsing image size cache file", ex);

                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }

            _cachedImagedSizes = new ConcurrentDictionary <Guid, ImageSize>(sizeDictionary);

            LogWebPVersion();
        }
Exemplo n.º 6
0
        public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
        {
            _logger = logger;
            _fileSystem = fileSystem;
            _jsonSerializer = jsonSerializer;
            _appPaths = appPaths;

            _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);

            Dictionary<Guid, ImageSize> sizeDictionary;

            try
            {
                sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ?? 
                    new Dictionary<Guid, ImageSize>();
            }
            catch (FileNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error parsing image size cache file", ex);

                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }

            _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Fetches the season data.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="seriesDataPath">The series data path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{Season}.</returns>
        private MetadataResult <Season> FetchSeasonData(SeasonInfo info, string seriesDataPath, CancellationToken cancellationToken)
        {
            var seasonFileName = TvMazeSeriesProvider.Current.GetSeasonPath(seriesDataPath, info.IndexNumber.Value);

            var mazeSeason = _jsonSerializer.DeserializeFromFile <MazeSeason>(seasonFileName);
            var season     = TvMazeAdapter.Convert(mazeSeason);

            if (string.IsNullOrEmpty(season.Name))
            {
                season.Name = info.Name;
            }

            if (!season.IndexNumber.HasValue)
            {
                season.IndexNumber = info.IndexNumber.Value;
            }

            var result = new MetadataResult <Season>()
            {
                Item        = season,
                HasMetadata = true
            };

            return(result);
        }
Exemplo n.º 8
0
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
        {
            var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);

            var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);

            var tmdbImageUrl = tmdbSettings.images.base_url + "original";

            if (!string.IsNullOrEmpty(tmdbId))
            {
                await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);

                var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
                var info         = _jsonSerializer.DeserializeFromFile <PersonResult>(dataFilePath);

                var images = (info.images ?? new Images()).profiles ?? new List <Profile>();

                var result = new RemoteSearchResult
                {
                    Name = info.name,

                    SearchProviderName = Name,

                    ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].file_path)
                };

                result.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
                result.SetProviderId(MetadataProviders.Imdb, info.imdb_id.ToString(_usCulture));

                return(new[] { result });
            }

            var url = string.Format(@"http://api.themoviedb.org/3/search/person?api_key={1}&query={0}", WebUtility.UrlEncode(searchInfo.Name), MovieDbProvider.ApiKey);

            using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken,
                AcceptHeader = MovieDbProvider.AcceptHeader
            }).ConfigureAwait(false))
            {
                var result = _jsonSerializer.DeserializeFromStream <PersonSearchResults>(json) ??
                             new PersonSearchResults();

                return(result.Results.Select(i => GetSearchResult(i, tmdbImageUrl)));
            }
        }
Exemplo n.º 9
0
        private ChutzpahTestSettingsFile FindSettingsFile(string directory, ChutzpahSettingsFileEnvironment environment)
        {
            if (string.IsNullOrEmpty(directory))
            {
                return(ChutzpahTestSettingsFile.Default);
            }

            directory = directory.TrimEnd('/', '\\');

            ChutzpahTestSettingsFile settings;

            if (!ChutzpahSettingsFileCache.TryGetValue(directory, out settings))
            {
                var testSettingsFilePath = fileProbe.FindTestSettingsFile(directory);
                if (string.IsNullOrEmpty(testSettingsFilePath))
                {
                    ChutzpahTracer.TraceInformation("Chutzpah.json file not found given starting directoy {0}", directory);
                    settings = ChutzpahTestSettingsFile.Default;
                }
                else if (!ChutzpahSettingsFileCache.TryGetValue(Path.GetDirectoryName(testSettingsFilePath), out settings))
                {
                    ChutzpahTracer.TraceInformation("Chutzpah.json file found at {0} given starting directoy {1}", testSettingsFilePath, directory);
                    settings = serializer.DeserializeFromFile <ChutzpahTestSettingsFile>(testSettingsFilePath);

                    if (settings == null)
                    {
                        settings = ChutzpahTestSettingsFile.Default;
                    }
                    else
                    {
                        settings.IsDefaultSettings = false;
                    }

                    settings.SettingsFileDirectory = Path.GetDirectoryName(testSettingsFilePath);

                    var chutzpahVariables = BuildChutzpahReplacementVariables(testSettingsFilePath, environment, settings);

                    ResolveTestHarnessDirectory(settings, chutzpahVariables);

                    ResolveAMDBaseUrl(settings, chutzpahVariables);

                    ResolveBatchCompileConfiguration(settings, chutzpahVariables);

                    ProcessPathSettings(settings, chutzpahVariables);

                    ProcessInheritance(environment, settings, chutzpahVariables);

                    // Add a mapping in the cache for the directory that contains the test settings file
                    ChutzpahSettingsFileCache.TryAdd(settings.SettingsFileDirectory, settings);
                }

                // Add mapping in the cache for the original directory tried to skip needing to traverse the tree again
                ChutzpahSettingsFileCache.TryAdd(directory, settings);
            }



            return(settings);
        }
Exemplo n.º 10
0
        private IEnumerable <DeviceInfo> LoadDevices()
        {
            var path = GetDevicesPath();

            try
            {
                return(new DirectoryInfo(path)
                       .EnumerateFiles("*", SearchOption.AllDirectories)
                       .Where(i => string.Equals(i.Name, "device.json", StringComparison.OrdinalIgnoreCase))
                       .Select(i => _json.DeserializeFromFile <DeviceInfo>(i.FullName))
                       .ToList());
            }
            catch (IOException)
            {
                return(new List <DeviceInfo>());
            }
        }
Exemplo n.º 11
0
        private async Task <SeasonResult> GetSeasonInfo(string seriesTmdbId, int season, string preferredMetadataLanguage,
                                                        CancellationToken cancellationToken)
        {
            await EnsureSeasonInfo(seriesTmdbId, season, preferredMetadataLanguage, cancellationToken)
            .ConfigureAwait(false);

            var dataFilePath = GetDataFilePath(seriesTmdbId, season, preferredMetadataLanguage);

            return(_jsonSerializer.DeserializeFromFile <SeasonResult>(dataFilePath));
        }
Exemplo n.º 12
0
        protected async Task <EpisodeResult> GetEpisodeInfo(string seriesTmdbId, int season, int episodeNumber, string preferredMetadataLanguage,
                                                            CancellationToken cancellationToken)
        {
            await EnsureEpisodeInfo(seriesTmdbId, season, episodeNumber, preferredMetadataLanguage, cancellationToken)
            .ConfigureAwait(false);

            var dataFilePath = GetDataFilePath(seriesTmdbId, season, episodeNumber, preferredMetadataLanguage);

            return(_jsonSerializer.DeserializeFromFile <EpisodeResult>(dataFilePath));
        }
Exemplo n.º 13
0
 private Dictionary <string, DateTime> GetHistory(string path)
 {
     try
     {
         return(_json.DeserializeFromFile <Dictionary <string, DateTime> >(path));
     }
     catch
     {
         return(new Dictionary <string, DateTime>());
     }
 }
Exemplo n.º 14
0
 public Notification <T> DeserializeFromFile <T>(string path)
 {
     try
     {
         var obj = _jsonSerializer.DeserializeFromFile <T>(path);
         return(obj);
     }
     catch (Exception e)
     {
         return(Notification.ErrorFor(DeserializationErrorMessageText, path, Environment.NewLine, e.Message).ToNotification <T>());
     }
 }
Exemplo n.º 15
0
        public ClientCapabilities GetCapabilities(string id)
        {
            lock (_capabilitiesSyncLock)
            {
                if (_capabilitiesCache.TryGetValue(id, out var result))
                {
                    return(result);
                }

                var path = Path.Combine(GetDevicePath(id), "capabilities.json");
                try
                {
                    return(_json.DeserializeFromFile <ClientCapabilities>(path) ?? new ClientCapabilities());
                }
                catch
                {
                }
            }

            return(new ClientCapabilities());
        }
Exemplo n.º 16
0
        private List <T> GetItemsFromFile(string path)
        {
            var jsonFile = path + ".json";

            try
            {
                return(_jsonSerializer.DeserializeFromFile <List <T> >(jsonFile));
            }
            catch (FileNotFoundException)
            {
            }
            catch (DirectoryNotFoundException ex)
            {
            }
            catch (IOException ex)
            {
                Logger.ErrorException("Error deserializing {0}", ex, jsonFile);
                throw;
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error deserializing {0}", ex, jsonFile);
                return(new List <T>());
            }

            var xmlFile = path + ".xml";

            try
            {
                var xml   = ModifyInputXml(File.ReadAllText(xmlFile));
                var bytes = Encoding.UTF8.GetBytes(xml);

                return((List <T>)_serializer.DeserializeFromBytes(typeof(List <T>), bytes));
            }
            catch (FileNotFoundException)
            {
                return(new List <T>());
            }
            catch (DirectoryNotFoundException ex)
            {
                return(new List <T>());
            }
            catch (IOException ex)
            {
                Logger.ErrorException("Error deserializing {0}", ex, xmlFile);
                throw;
            }
            catch (Exception ex)
            {
                Logger.ErrorException("Error deserializing {0}", ex, xmlFile);
                return(new List <T>());
            }
        }
Exemplo n.º 17
0
        private List <MediaSourceInfo> GetSavedMediaSources(BaseItem item)
        {
            var path = Path.Combine(item.GetInternalMetadataPath(), "channelmediasourceinfos.json");

            try
            {
                return(_jsonSerializer.DeserializeFromFile <List <MediaSourceInfo> >(path) ?? new List <MediaSourceInfo>());
            }
            catch
            {
                return(new List <MediaSourceInfo>());
            }
        }
Exemplo n.º 18
0
        private List <T> GetItemsFromFile(string path)
        {
            try
            {
                return(_jsonSerializer.DeserializeFromFile <List <T> >(path));
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "Error deserializing {Path}", path);
            }

            return(new List <T>());
        }
Exemplo n.º 19
0
 private List <ProgramInfo> GetEpgDataForChannel(string channelId)
 {
     try
     {
         lock (_epgLock)
         {
             return(_jsonSerializer.DeserializeFromFile <List <ProgramInfo> >(GetChannelEpgCachePath(channelId)));
         }
     }
     catch
     {
         return(new List <ProgramInfo>());
     }
 }
Exemplo n.º 20
0
        public async Task <IEnumerable <RemoteSearchResult> > GetMovieSearchResults(ItemLookupInfo searchInfo, CancellationToken cancellationToken)
        {
            var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);

            if (!string.IsNullOrEmpty(tmdbId))
            {
                cancellationToken.ThrowIfCancellationRequested();

                await EnsureMovieInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                var dataFilePath = GetDataFilePath(tmdbId, searchInfo.MetadataLanguage);

                var obj = _jsonSerializer.DeserializeFromFile <CompleteMovieData>(dataFilePath);

                var tmdbSettings = await GetTmdbSettings(cancellationToken).ConfigureAwait(false);

                var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");

                var remoteResult = new RemoteSearchResult
                {
                    Name = obj.GetTitle(),
                    SearchProviderName = Name,
                    ImageUrl           = string.IsNullOrWhiteSpace(obj.poster_path) ? null : tmdbImageUrl + obj.poster_path
                };

                if (!string.IsNullOrWhiteSpace(obj.release_date))
                {
                    DateTime r;

                    // These dates are always in this exact format
                    if (DateTime.TryParse(obj.release_date, _usCulture, DateTimeStyles.None, out r))
                    {
                        remoteResult.PremiereDate   = r.ToUniversalTime();
                        remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
                    }
                }

                remoteResult.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_usCulture));

                if (!string.IsNullOrWhiteSpace(obj.imdb_id))
                {
                    remoteResult.SetProviderId(MetadataProviders.Imdb, obj.imdb_id);
                }

                return(new[] { remoteResult });
            }

            return(await new MovieDbSearch(_logger, _jsonSerializer, _libraryManager).GetMovieSearchResults(searchInfo, cancellationToken).ConfigureAwait(false));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Fetches the episode data.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <param name="seriesDataPath">The series data path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{Episode}.</returns>
        private MetadataResult <Episode> FetchEpisodeData(EpisodeInfo id, string seriesDataPath, CancellationToken cancellationToken)
        {
            var episodeFileName = TvMazeSeriesProvider.Current.GetEpisodePath(seriesDataPath, id.ParentIndexNumber.Value, id.IndexNumber.Value);

            var mazeEpisode = _jsonSerializer.DeserializeFromFile <MazeEpisode>(episodeFileName);
            var episode     = TvMazeAdapter.Convert(mazeEpisode);

            var result = new MetadataResult <Episode>()
            {
                Item        = episode,
                HasMetadata = true
            };

            return(result);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Adds the images.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="path">The path.</param>
        /// <param name="releaseId">The release identifier.</param>
        /// <param name="releaseGroupId">The release group identifier.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        private void AddImages(List <RemoteImageInfo> list, string path, string releaseId, string releaseGroupId, CancellationToken cancellationToken)
        {
            var obj = _jsonSerializer.DeserializeFromFile <FanartArtistProvider.FanartArtistResponse>(path);

            if (obj.albums != null)
            {
                var album = obj.albums.FirstOrDefault(i => string.Equals(i.release_group_id, releaseGroupId, StringComparison.OrdinalIgnoreCase));

                if (album != null)
                {
                    PopulateImages(list, album.albumcover, ImageType.Primary, 1000, 1000);
                    PopulateImages(list, album.cdart, ImageType.Disc, 1000, 1000);
                }
            }
        }
Exemplo n.º 23
0
        private async Task <List <Poster> > FetchImages(Season item, string tmdbId, string language, CancellationToken cancellationToken)
        {
            await TmdbSeasonProvider.Current.EnsureSeasonInfo(tmdbId, item.IndexNumber.GetValueOrDefault(), language, cancellationToken).ConfigureAwait(false);

            var path = TmdbSeriesProvider.Current.GetDataFilePath(tmdbId, language);

            if (!string.IsNullOrEmpty(path))
            {
                if (File.Exists(path))
                {
                    return(_jsonSerializer.DeserializeFromFile <Models.TV.SeasonResult>(path).Images.Posters);
                }
            }

            return(null);
        }
Exemplo n.º 24
0
        private int ExtractEpisodes(string jsonFile)
        {
            TVDBjson temp  = _jsonserializer.DeserializeFromFile <TVDBjson>(jsonFile);
            var      count = 0;

            foreach (var e in temp.episodes)
            {
                _logger.Debug(e.name);
                if ((e.aired != null) && (DateTime.Now.Date >= StringToDateTime(e.aired) && e.seasonNumber != 0))
                {
                    count++;
                }
            }

            return(count);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Fetches the images.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <returns>Task{MovieImages}.</returns>
        private MovieDbProvider.Images FetchImages(BaseItem item, IJsonSerializer jsonSerializer)
        {
            var path = MovieDbProvider.Current.GetImagesDataFilePath(item);

            if (!string.IsNullOrEmpty(path))
            {
                var fileInfo = new FileInfo(path);

                if (fileInfo.Exists)
                {
                    return(jsonSerializer.DeserializeFromFile <MovieDbProvider.CompleteMovieData>(path).images);
                }
            }

            return(null);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Gets the critic reviews.
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <returns>Task{IEnumerable{ItemReview}}.</returns>
        public IEnumerable <ItemReview> GetCriticReviews(Guid itemId)
        {
            try
            {
                var path = Path.Combine(_criticReviewsPath, itemId + ".json");

                return(_jsonSerializer.DeserializeFromFile <List <ItemReview> >(path));
            }
            catch (DirectoryNotFoundException)
            {
                return(new List <ItemReview>());
            }
            catch (FileNotFoundException)
            {
                return(new List <ItemReview>());
            }
        }
Exemplo n.º 27
0
        /// <inheritdoc />
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var id = YoutubeMetadataProvider.Current.GetYTID(item.FileNameWithoutExtension);

            if (!string.IsNullOrWhiteSpace(id))
            {
                await YoutubeMetadataProvider.Current.EnsureInfo(id, cancellationToken).ConfigureAwait(false);

                var path = YoutubeMetadataProvider.GetVideoInfoPath(_config.ApplicationPaths, id);

                var obj = _json.DeserializeFromFile <Google.Apis.YouTube.v3.Data.Video>(path);

                if (obj != null)
                {
                    var tnurls = new List <string>();
                    if (obj.Snippet.Thumbnails.Maxres != null)
                    {
                        tnurls.Add(obj.Snippet.Thumbnails.Maxres.Url);
                    }
                    if (obj.Snippet.Thumbnails.Standard != null)
                    {
                        tnurls.Add(obj.Snippet.Thumbnails.Standard.Url);
                    }
                    if (obj.Snippet.Thumbnails.High != null)
                    {
                        tnurls.Add(obj.Snippet.Thumbnails.High.Url);
                    }
                    if (obj.Snippet.Thumbnails.Medium != null)
                    {
                        tnurls.Add(obj.Snippet.Thumbnails.Medium.Url);
                    }
                    if (obj.Snippet.Thumbnails.Default__.Url != null)
                    {
                        tnurls.Add(obj.Snippet.Thumbnails.Default__.Url);
                    }

                    return(GetImages(tnurls));
                }
                else
                {
                    _logger.LogInformation("Object is null!");
                }
            }

            return(new List <RemoteImageInfo>());
        }
Exemplo n.º 28
0
        private async Task <IEnumerable <ChannelItemInfo> > GetLatestItems(ISupportsLatestMedia indexable, IChannel channel, string userId, CancellationToken cancellationToken)
        {
            var cacheLength = TimeSpan.FromHours(12);
            var cachePath   = GetChannelDataCachePath(channel, userId, "channelmanager-latest", null, false);

            try
            {
                if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
                {
                    return(_jsonSerializer.DeserializeFromFile <List <ChannelItemInfo> >(cachePath));
                }
            }
            catch (FileNotFoundException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }

            await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                try
                {
                    if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
                    {
                        return(_jsonSerializer.DeserializeFromFile <List <ChannelItemInfo> >(cachePath));
                    }
                }
                catch (FileNotFoundException)
                {
                }
                catch (DirectoryNotFoundException)
                {
                }

                var result = await indexable.GetLatestMedia(new ChannelLatestMediaSearch
                {
                    UserId = userId
                }, cancellationToken).ConfigureAwait(false);

                var resultItems = result.ToList();

                CacheResponse(resultItems, cachePath);

                return(resultItems);
            }
            finally
            {
                _resourcePool.Release();
            }
        }
Exemplo n.º 29
0
        public ImageProcessor(ILogger logger,
                              IServerApplicationPaths appPaths,
                              IFileSystem fileSystem,
                              IJsonSerializer jsonSerializer,
                              IImageEncoder imageEncoder,
                              Func <ILibraryManager> libraryManager, ITimerFactory timerFactory, Func <IMediaEncoder> mediaEncoder)
        {
            _logger         = logger;
            _fileSystem     = fileSystem;
            _jsonSerializer = jsonSerializer;
            _imageEncoder   = imageEncoder;
            _libraryManager = libraryManager;
            _mediaEncoder   = mediaEncoder;
            _appPaths       = appPaths;

            ImageEnhancers             = new IImageEnhancer[] { };
            _saveImageSizeTimer        = timerFactory.Create(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);
            ImageHelper.ImageProcessor = this;

            Dictionary <Guid, ImageSize> sizeDictionary;

            try
            {
                sizeDictionary = jsonSerializer.DeserializeFromFile <Dictionary <Guid, ImageSize> >(ImageSizeFile) ??
                                 new Dictionary <Guid, ImageSize>();
            }
            catch (FileNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }
            catch (IOException)
            {
                // No biggie
                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error parsing image size cache file", ex);

                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }

            _cachedImagedSizes = new ConcurrentDictionary <Guid, ImageSize>(sizeDictionary);
        }
Exemplo n.º 30
0
        public ImageProcessor(ILogger logger,
                              IServerApplicationPaths appPaths,
                              IFileSystem fileSystem,
                              IJsonSerializer jsonSerializer,
                              IImageEncoder imageEncoder,
                              int maxConcurrentImageProcesses, Func <ILibraryManager> libraryManager)
        {
            _logger         = logger;
            _fileSystem     = fileSystem;
            _jsonSerializer = jsonSerializer;
            _imageEncoder   = imageEncoder;
            _libraryManager = libraryManager;
            _appPaths       = appPaths;

            ImageEnhancers      = new List <IImageEnhancer>();
            _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);

            Dictionary <Guid, ImageSize> sizeDictionary;

            try
            {
                sizeDictionary = jsonSerializer.DeserializeFromFile <Dictionary <Guid, ImageSize> >(ImageSizeFile) ??
                                 new Dictionary <Guid, ImageSize>();
            }
            catch (FileNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }
            catch (DirectoryNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error parsing image size cache file", ex);

                sizeDictionary = new Dictionary <Guid, ImageSize>();
            }

            _cachedImagedSizes = new ConcurrentDictionary <Guid, ImageSize>(sizeDictionary);
            _logger.Info("ImageProcessor started with {0} max concurrent image processes", maxConcurrentImageProcesses);
            _imageProcessingSemaphore = new SemaphoreSlim(maxConcurrentImageProcesses, maxConcurrentImageProcesses);
        }
Exemplo n.º 31
0
        public ImageProcessor(ILogger logger,
            IServerApplicationPaths appPaths,
            IFileSystem fileSystem,
            IJsonSerializer jsonSerializer,
            IImageEncoder imageEncoder,
            int maxConcurrentImageProcesses, Func<ILibraryManager> libraryManager)
        {
            _logger = logger;
            _fileSystem = fileSystem;
            _jsonSerializer = jsonSerializer;
            _imageEncoder = imageEncoder;
            _libraryManager = libraryManager;
            _appPaths = appPaths;

            ImageEnhancers = new List<IImageEnhancer>();
            _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite);

            Dictionary<Guid, ImageSize> sizeDictionary;

            try
            {
                sizeDictionary = jsonSerializer.DeserializeFromFile<Dictionary<Guid, ImageSize>>(ImageSizeFile) ??
                    new Dictionary<Guid, ImageSize>();
            }
            catch (FileNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }
            catch (DirectoryNotFoundException)
            {
                // No biggie
                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }
            catch (Exception ex)
            {
                logger.ErrorException("Error parsing image size cache file", ex);

                sizeDictionary = new Dictionary<Guid, ImageSize>();
            }

            _cachedImagedSizes = new ConcurrentDictionary<Guid, ImageSize>(sizeDictionary);
            _logger.Info("ImageProcessor started with {0} max concurrent image processes", maxConcurrentImageProcesses);
            _imageProcessingSemaphore = new SemaphoreSlim(maxConcurrentImageProcesses, maxConcurrentImageProcesses);
        }
Exemplo n.º 32
0
        private async Task <Model.MediaInfo.MediaInfo> GetMediaInfo(Video item,
                                                                    IIsoMount isoMount,
                                                                    CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var idString  = item.Id.ToString("N");
            var cachePath = Path.Combine(_appPaths.CachePath,
                                         "ffprobe-video",
                                         idString.Substring(0, 2), idString, "v" + SchemaVersion + _mediaEncoder.Version + item.DateModified.Ticks.ToString(_usCulture) + ".json");

            try
            {
                return(_json.DeserializeFromFile <Model.MediaInfo.MediaInfo>(cachePath));
            }
            catch (FileNotFoundException)
            {
            }
            catch (DirectoryNotFoundException)
            {
            }

            var protocol = item.LocationType == LocationType.Remote
                ? MediaProtocol.Http
                : MediaProtocol.File;

            var result = await _mediaEncoder.GetMediaInfo(new MediaInfoRequest
            {
                PlayableStreamFileNames = item.PlayableStreamFileNames,
                MountedIso              = isoMount,
                ExtractChapters         = true,
                VideoType               = item.VideoType,
                MediaType               = DlnaProfileType.Video,
                InputPath               = item.Path,
                Protocol                = protocol,
                ExtractKeyFrameInterval = true
            }, cancellationToken).ConfigureAwait(false);

            Directory.CreateDirectory(Path.GetDirectoryName(cachePath));
            _json.SerializeToFile(result, cachePath);

            return(result);
        }
        /// <summary>
        /// Fetches the images.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MovieImages}.</returns>
        private async Task<MovieDbProvider.Images> FetchImages(BaseItem item, IJsonSerializer jsonSerializer,
            CancellationToken cancellationToken)
        {
            await MovieDbProvider.Current.EnsureMovieInfo(item, cancellationToken).ConfigureAwait(false);

            var path = MovieDbProvider.Current.GetDataFilePath(item);

            if (!string.IsNullOrEmpty(path))
            {
                var fileInfo = new FileInfo(path);

                if (fileInfo.Exists)
                {
                    return jsonSerializer.DeserializeFromFile<MovieDbProvider.CompleteMovieData>(path).images;
                }
            }

            return null;
        }
Exemplo n.º 34
0
        /// <summary>
        /// Find and reads a chutzpah test settings file given a direcotry. If none is found a default settings object is created
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="fileProbe"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public static ChutzpahTestSettingsFile Read(string directory, IFileProbe fileProbe, IJsonSerializer serializer)
        {
            if (string.IsNullOrEmpty(directory)) return new ChutzpahTestSettingsFile();

            directory = directory.TrimEnd('/', '\\');

            ChutzpahTestSettingsFile settings;
            if (!ChutzpahSettingsFileCache.TryGetValue(directory, out settings))
            {
                var testSettingsFilePath = fileProbe.FindTestSettingsFile(directory);
                if(string.IsNullOrEmpty(testSettingsFilePath))
                {
                    settings = new ChutzpahTestSettingsFile();
                }
                else if (!ChutzpahSettingsFileCache.TryGetValue(testSettingsFilePath, out settings))
                {
                    settings = serializer.DeserializeFromFile<ChutzpahTestSettingsFile>(testSettingsFilePath);
                    settings.SettingsFileDirectory = Path.GetDirectoryName(testSettingsFilePath);

                    ValidateTestHarnessLocationMode(settings, fileProbe);

                    // Add a mapping in the cache for the directory that contains the test settings file
                    ChutzpahSettingsFileCache.TryAdd(settings.SettingsFileDirectory, settings);
                }

                // Add mapping in the cache for the original directory tried to skip needing to traverse the tree again
                ChutzpahSettingsFileCache.TryAdd(directory, settings);
            }

            return settings;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Fetches the images.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="language">The language.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MovieImages}.</returns>
        private async Task<MovieDbProvider.Images> FetchImages(BaseItem item, string language, IJsonSerializer jsonSerializer, CancellationToken cancellationToken)
        {
            var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);

            if (string.IsNullOrWhiteSpace(tmdbId))
            {
                var imdbId = item.GetProviderId(MetadataProviders.Imdb);
                if (!string.IsNullOrWhiteSpace(imdbId))
                {
                    var movieInfo = await MovieDbProvider.Current.FetchMainResult(imdbId, false, language, cancellationToken).ConfigureAwait(false);
                    if (movieInfo != null)
                    {
                        tmdbId = movieInfo.id.ToString(CultureInfo.InvariantCulture);
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(tmdbId))
            {
                return null;
            }

            await MovieDbProvider.Current.EnsureMovieInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);

            var path = MovieDbProvider.Current.GetDataFilePath(tmdbId, language);

            if (!string.IsNullOrEmpty(path))
            {
                var fileInfo = new FileInfo(path);

                if (fileInfo.Exists)
                {
                    return jsonSerializer.DeserializeFromFile<MovieDbProvider.CompleteMovieData>(path).images;
                }
            }

            return null;
        }
        /// <summary>
        /// Fetches the images.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <returns>Task{MovieImages}.</returns>
        private MovieDbProvider.Images FetchImages(BaseItem item, IJsonSerializer jsonSerializer)
        {
            var path = MovieDbProvider.Current.GetImagesDataFilePath(item);

            if (!string.IsNullOrEmpty(path))
            {
                var fileInfo = new FileInfo(path);

                if (fileInfo.Exists)
                {
                    return jsonSerializer.DeserializeFromFile<MovieDbProvider.CompleteMovieData>(path).images;
                }
            }

            return null;
        }
Exemplo n.º 37
0
        /// <summary>
        /// Fetches the images.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="language">The language.</param>
        /// <param name="jsonSerializer">The json serializer.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task{MovieImages}.</returns>
        private async Task<MovieDbSeriesProvider.Images> FetchImages(BaseItem item, string language, IJsonSerializer jsonSerializer,
            CancellationToken cancellationToken)
        {
            var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);

            if (string.IsNullOrEmpty(tmdbId))
            {
                return null;
            }

            await MovieDbSeriesProvider.Current.EnsureSeriesInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);

            var path = MovieDbSeriesProvider.Current.GetDataFilePath(tmdbId, language);

            if (!string.IsNullOrEmpty(path))
            {
                var fileInfo = new FileInfo(path);

                if (fileInfo.Exists)
                {
                    return jsonSerializer.DeserializeFromFile<MovieDbSeriesProvider.RootObject>(path).images;
                }
            }

            return null;
        }