Example #1
0
        public Task <QueryResult <FileMetadata> > GetFiles(FileQuery query, SyncTarget target, CancellationToken cancellationToken)
        {
            var account = GetSyncAccounts()
                          .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var result = new QueryResult <FileMetadata>();

            if (!string.IsNullOrWhiteSpace(query.Id))
            {
                var file = _fileSystem.GetFileSystemInfo(query.Id);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFile).ToArray();
                }

                return(Task.FromResult(result));
            }

            if (query.FullPath != null && query.FullPath.Length > 0)
            {
                var fullPath = GetFullPath(query.FullPath, target);
                var file     = _fileSystem.GetFileSystemInfo(fullPath);

                if (file.Exists)
                {
                    result.TotalRecordCount = 1;
                    result.Items            = new[] { file }.Select(GetFile).ToArray();
                }

                return(Task.FromResult(result));
            }

            FileMetadata[] files;

            try
            {
                files = _fileSystem.GetFiles(account.Path, true)
                        .Select(GetFile)
                        .ToArray();
            }
            catch (DirectoryNotFoundException)
            {
                files = new FileMetadata[] { };
            }

            result.Items            = files;
            result.TotalRecordCount = files.Length;

            return(Task.FromResult(result));
        }
        public virtual async Task <MetadataResult <T> > GetMetadata(E info, CancellationToken cancellationToken)
        {
            _logger.LogDebug("GetMetadata: {Path}", info.Path);
            MetadataResult <T> result = new();
            var id = GetYTID(info.Path);

            if (string.IsNullOrWhiteSpace(id))
            {
                _logger.LogInformation("Youtube ID not found in filename of title: {info.Name}", info.Name);
                result.HasMetadata = false;
                return(result);
            }
            var ytPath   = GetVideoInfoPath(this._config.ApplicationPaths, id);
            var fileInfo = _fileSystem.GetFileSystemInfo(ytPath);

            if (!IsFresh(fileInfo))
            {
                await this.GetAndCacheMetadata(id, this._config.ApplicationPaths, cancellationToken);
            }
            var video = ReadYTDLInfo(ytPath, cancellationToken);

            if (video != null)
            {
                result = this.GetMetadataImpl(video, id);
            }
            return(result);
        }
Example #3
0
        public List <LocalImageInfo> GetImages(BaseItem item, IDirectoryService directoryService)
        {
            _logger.LogInformation(item.Path);
            var list = new List <LocalImageInfo>();

            if (Plugin.Instance.Configuration.DisableLocalMetadata)
            {
                _logger.LogInformation("Local Metadata Disabled");
                return(list);
            }


            var filename = item.FileNameWithoutExtension + ".jpg";
            var fullpath = Path.Combine(item.ContainingFolderPath, filename);

            var localimg = new LocalImageInfo();
            var fileInfo = _fileSystem.GetFileSystemInfo(fullpath);

            if (File.Exists(fileInfo.FullName))
            {
                localimg.FileInfo = fileInfo;
                list.Add(localimg);
            }
            return(list);
        }
        public static FileSystemMetadata GetXmlFileInfo(ItemInfo info, IFileSystem fileSystem)
        {
            var path = info.Path;

            if (string.IsNullOrEmpty(path) || BaseItem.MediaSourceManager.GetPathProtocol(path.AsSpan()) != MediaBrowser.Model.MediaInfo.MediaProtocol.File)
            {
                return(null);
            }

            var fileInfo = fileSystem.GetFileSystemInfo(path);

            var directoryInfo = fileInfo.IsDirectory ? fileInfo : fileSystem.GetDirectoryInfo(fileSystem.GetDirectoryName(path));

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, fileSystem.GetFileNameWithoutExtension(path) + ".xml");

            var file = fileSystem.GetFileInfo(specificFile);

            // In a mixed folder, only {moviename}.xml is supported
            if (info.IsInMixedFolder)
            {
                return(file);
            }

            // If in it's own folder, prefer movie.xml, but allow the specific file as well
            var movieFile = fileSystem.GetFileInfo(Path.Combine(directoryPath, "movie.xml"));

            return(movieFile.Exists ? movieFile : file);
        }
Example #5
0
        internal async Task EnsureSeriesXml(string tvdbId, CancellationToken cancellationToken)
        {
            var xmlPath = GetFanartXmlPath(tvdbId);

            // Only allow one thread in here at a time since every season will be calling this method, possibly concurrently
            await _ensureSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                var fileInfo = _fileSystem.GetFileSystemInfo(xmlPath);

                if (fileInfo.Exists)
                {
                    if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 7)
                    {
                        return;
                    }
                }

                await DownloadSeriesXml(tvdbId, cancellationToken).ConfigureAwait(false);
            }
            finally
            {
                _ensureSemaphore.Release();
            }
        }
        /// <summary>
        /// Retrieves image for item.
        /// </summary>
        /// <param name="item"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            _logger.LogDebug("GetImages: {Name}", item.Name);
            var result = new List <RemoteImageInfo>();
            //var id = item.GetProviderId(Constants.PluginName);
            var name = item.Name;

            if (string.IsNullOrWhiteSpace(name))
            {
                _logger.LogInformation("Youtube ID not found in Item: {item.Name}", item.Name);
                return(result);
            }
            var ytPath   = Utils.GetVideoInfoPath(_config.ApplicationPaths, name);
            var fileInfo = _fileSystem.GetFileSystemInfo(ytPath);

            if (!(Utils.IsFresh(fileInfo)))
            {
                await Utils.YTDLMetadata(name, _config.ApplicationPaths, cancellationToken);
            }
            var path  = Utils.GetVideoInfoPath(_config.ApplicationPaths, name);
            var video = Utils.ReadYTDLInfo(path, cancellationToken);

            if (video != null)
            {
                result.Add(new RemoteImageInfo
                {
                    ProviderName = Name,
                    Url          = video.thumbnails[^ 1].url,
Example #7
0
        /// <summary>
        /// Refreshes the intro.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private async Task RefreshIntro(string path, CancellationToken cancellationToken)
        {
            var item = _libraryManager.ResolvePath(_fileSystem.GetFileSystemInfo(path));

            if (item == null)
            {
                _logger.Error("Intro resolver returned null for {0}", path);
                return;
            }

            var dbItem    = _libraryManager.RetrieveItem(item.Id);
            var isNewItem = false;

            if (dbItem != null)
            {
                dbItem.ResetResolveArgs(item.ResolveArgs);
                item = dbItem;
            }
            else
            {
                isNewItem = true;
            }

            // Force the save if it's a new item
            await item.RefreshMetadata(cancellationToken, isNewItem).ConfigureAwait(false);
        }
Example #8
0
        internal Task EnsureSeasonInfo(string tmdbId, int seasonNumber, string language, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(tmdbId))
            {
                throw new ArgumentNullException(nameof(tmdbId));
            }

            if (string.IsNullOrEmpty(language))
            {
                throw new ArgumentNullException(nameof(language));
            }

            var path = GetDataFilePath(tmdbId, seasonNumber, language);

            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            if (fileInfo.Exists)
            {
                // If it's recent or automatic updates are enabled, don't re-download
                if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
                {
                    return(Task.CompletedTask);
                }
            }

            return(DownloadSeasonInfo(tmdbId, seasonNumber, language, cancellationToken));
        }
Example #9
0
        private static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args)
        {
            // See if a different path came out of the resolver than what went in
            if (!fileSystem.AreEqual(args.Path, item.Path))
            {
                var childData = args.IsDirectory ? args.GetFileSystemEntryByPath(item.Path) : null;

                if (childData != null)
                {
                    SetDateCreated(item, childData);
                }
                else
                {
                    var fileData = fileSystem.GetFileSystemInfo(item.Path);

                    if (fileData.Exists)
                    {
                        SetDateCreated(item, fileData);
                    }
                }
            }
            else
            {
                SetDateCreated(item, args.FileInfo);
            }
        }
Example #10
0
        internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
        {
            var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);

            var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);

            if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
            {
                return;
            }

            var url = string.Format(
                CultureInfo.InvariantCulture,
                TmdbUtils.BaseTmdbApiUrl + @"3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids",
                TmdbUtils.ApiKey,
                id);

            using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
            foreach (var header in TmdbUtils.AcceptHeaders)
            {
                requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
            }

            using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);

            Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
            await using var fs = new FileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
            await response.Content.CopyToAsync(fs).ConfigureAwait(false);
        }
Example #11
0
        public static FileInfo GetXmlFileInfo(ItemInfo info, IFileSystem fileSystem)
        {
            var fileInfo = fileSystem.GetFileSystemInfo(info.Path);

            var directoryInfo = fileInfo as DirectoryInfo;

            if (directoryInfo == null)
            {
                directoryInfo = new DirectoryInfo(Path.GetDirectoryName(info.Path));
            }

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(info.Path) + ".xml");

            var file = new FileInfo(specificFile);

            // In a mixed folder, only {moviename}.xml is supported
            if (info.IsInMixedFolder)
            {
                return(file);
            }

            // If in it's own folder, prefer movie.xml, but allow the specific file as well
            var movieFile = new FileInfo(Path.Combine(directoryPath, "movie.xml"));

            return(movieFile.Exists ? movieFile : file);
        }
Example #12
0
        internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
        {
            var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);

            var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);

            if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
            {
                return;
            }

            var url = string.Format(@"http://api.themoviedb.org/3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids", MovieDbProvider.ApiKey, id);

            using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken,
                AcceptHeader = MovieDbProvider.AcceptHeader
            }).ConfigureAwait(false))
            {
                _fileSystem.CreateDirectory(Path.GetDirectoryName(dataFilePath));

                using (var fs = _fileSystem.GetFileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
                {
                    await json.CopyToAsync(fs).ConfigureAwait(false);
                }
            }
        }
Example #13
0
        internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
        {
            var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);

            var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);

            if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
            {
                return;
            }

            var url = string.Format(TmdbUtils.BaseTmdbApiUrl + @"3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids", TmdbUtils.ApiKey, id);

            using (var response = await TmdbMovieProvider.Current.GetMovieDbResponse(new HttpRequestOptions
            {
                Url = url,
                CancellationToken = cancellationToken,
                AcceptHeader = TmdbUtils.AcceptHeader
            }).ConfigureAwait(false))
            {
                using (var json = response.Content)
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));

                    using (var fs = new FileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true))
                    {
                        await json.CopyToAsync(fs).ConfigureAwait(false);
                    }
                }
            }
        }
Example #14
0
        public static FileSystemMetadata GetXmlFileInfo(ItemInfo info, IFileSystem fileSystem)
        {
            var fileInfo = fileSystem.GetFileSystemInfo(info.Path);

            var directoryInfo = fileInfo.IsDirectory ? fileInfo : fileSystem.GetDirectoryInfo(fileSystem.GetDirectoryName(info.Path));

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, fileSystem.GetFileNameWithoutExtension(info.Path) + ".xml");

            var file = fileSystem.GetFileInfo(specificFile);

            // In a mixed folder, only {moviename}.xml is supported
            if (info.IsInMixedFolder)
            {
                return(file);
            }

            // If in it's own folder, prefer movie.xml, but allow the specific file as well
            var movieFile = fileSystem.GetFileInfo(Path.Combine(directoryPath, "movie.xml"));

            return(movieFile.Exists ? movieFile : file);

            // var file = Path.Combine(directoryPath, fileSystem.GetFileNameWithoutExtension(info.Path) + ".xml")
            // return directoryService.GetFile(Path.ChangeExtension(info.Path, ".xml"));
        }
Example #15
0
        private FileInfo GetXmlFile(string path, bool isInMixedFolder)
        {
            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            var directoryInfo = fileInfo as DirectoryInfo;

            if (directoryInfo == null)
            {
                directoryInfo = new DirectoryInfo(Path.GetDirectoryName(path));
            }

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(path) + ".opf");

            var file = new FileInfo(specificFile);

            if (file.Exists)
            {
                return(file);
            }

            file = new FileInfo(Path.Combine(directoryPath, StandardOpfFile));

            return(file.Exists ? file : new FileInfo(Path.Combine(directoryPath, CalibreOpfFile)));
        }
Example #16
0
        FileSystemMetadata GetInfoJson(string path)
        {
            var fileInfo      = _fileSystem.GetFileSystemInfo(path);
            var directoryInfo = fileInfo.IsDirectory ? fileInfo : _fileSystem.GetDirectoryInfo(Path.GetDirectoryName(path));
            var directoryPath = directoryInfo.FullName;
            var specificFile  = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(path) + ".info.json");
            var file          = _fileSystem.GetFileInfo(specificFile);

            return(file);
        }
Example #17
0
        private FileSystemMetadata?GetComicBookFile(string path)
        {
            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            if (fileInfo.IsDirectory)
            {
                return(null);
            }

            // Only parse files that are known to have internal metadata
            return(fileInfo.Extension.Equals(".cbz", StringComparison.OrdinalIgnoreCase) ? fileInfo : null);
        }
        /// <summary>
        /// Ensures DateCreated and DateModified have values
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="item">The item.</param>
        /// <param name="args">The args.</param>
        /// <param name="includeCreationTime">if set to <c>true</c> [include creation time].</param>
        public static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args, bool includeCreationTime)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            // See if a different path came out of the resolver than what went in
            if (!string.Equals(args.Path, item.Path, StringComparison.OrdinalIgnoreCase))
            {
                var childData = args.IsDirectory ? args.GetFileSystemEntryByPath(item.Path) : null;

                if (childData != null)
                {
                    if (includeCreationTime)
                    {
                        SetDateCreated(item, fileSystem, childData);
                    }

                    item.DateModified = fileSystem.GetLastWriteTimeUtc(childData);
                }
                else
                {
                    var fileData = fileSystem.GetFileSystemInfo(item.Path);

                    if (fileData.Exists)
                    {
                        if (includeCreationTime)
                        {
                            SetDateCreated(item, fileSystem, fileData);
                        }
                        item.DateModified = fileSystem.GetLastWriteTimeUtc(fileData);
                    }
                }
            }
            else
            {
                if (includeCreationTime)
                {
                    SetDateCreated(item, fileSystem, args.FileInfo);
                }
                item.DateModified = fileSystem.GetLastWriteTimeUtc(args.FileInfo);
            }
        }
Example #19
0
        public Task<QueryResult<FileSystemMetadata>> GetFiles(string id, SyncTarget target, CancellationToken cancellationToken)
        {
            var account = GetSyncAccounts()
                .FirstOrDefault(i => string.Equals(i.Id, target.Id, StringComparison.OrdinalIgnoreCase));

            if (account == null)
            {
                throw new ArgumentException("Invalid SyncTarget supplied.");
            }

            var result = new QueryResult<FileSystemMetadata>();

            var file = _fileSystem.GetFileSystemInfo(id);

            if (file.Exists)
            {
                result.TotalRecordCount = 1;
                result.Items = new[] { file }.ToArray();
            }

            return Task.FromResult(result);
        }
        public ValueGroup CalculateBiggestMovie()
        {
            var movies = GetAllMovies();

            var    biggestMovie = new MediaBrowser.Controller.Entities.Movies.Movie();
            double maxSize      = 0;

            foreach (var movie in movies)
            {
                try
                {
                    var f = _fileSystem.GetFileSystemInfo(movie.Path);
                    if (maxSize >= f.Length)
                    {
                        continue;
                    }

                    maxSize      = f.Length;
                    biggestMovie = movie;
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            maxSize = maxSize / 1073741824; //Byte to Gb
            var valueLineOne = CheckMaxLength($"{maxSize:F1} Gb");
            var valueLineTwo = CheckMaxLength($"{biggestMovie.Name}");

            return(new ValueGroup
            {
                Title = Constants.BiggestMovie,
                ValueLineOne = valueLineOne,
                ValueLineTwo = valueLineTwo,
                Size = "half",
                Id = biggestMovie.Id.ToString()
            });
        }
Example #21
0
        private async Task <string> EnsureItemInfo(string imdbId, CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(imdbId))
            {
                throw new ArgumentNullException(nameof(imdbId));
            }

            var imdbParam = imdbId.StartsWith("tt", StringComparison.OrdinalIgnoreCase) ? imdbId : "tt" + imdbId;

            var path = GetDataFilePath(imdbParam);

            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            if (fileInfo.Exists)
            {
                // If it's recent or automatic updates are enabled, don't re-download
                if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 1)
                {
                    return(path);
                }
            }

            var url = GetOmdbUrl(
                string.Format(
                    CultureInfo.InvariantCulture,
                    "i={0}&plot=short&tomatoes=true&r=json",
                    imdbParam));

            var rootObject = await GetDeserializedOmdbResponse <RootObject>(_httpClientFactory.CreateClient(NamedClient.Default), url, cancellationToken).ConfigureAwait(false);

            var directory = Path.GetDirectoryName(path) ?? throw new ResourceNotFoundException($"Provided path ({path}) is not valid.");

            Directory.CreateDirectory(directory);
            await using FileStream jsonFileStream = File.OpenWrite(path);
            await JsonSerializer.SerializeAsync(jsonFileStream, rootObject, _jsonOptions, cancellationToken).ConfigureAwait(false);

            return(path);
        }
Example #22
0
        public Task <QueryResult <FileSystemMetadata> > GetFiles(string id, SyncTarget target, CancellationToken cancellationToken)
        {
            var result = new QueryResult <FileSystemMetadata>();

            var file = _fileSystem.GetFileSystemInfo(id);

            if (file.Exists)
            {
                result.TotalRecordCount = 1;
                result.Items            = new[] { file }.ToArray();
            }

            return(Task.FromResult(result));
        }
        private FileSystemMetadata GetXmlFile(string path, bool isInMixedFolder)
        {
            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            var directoryInfo = fileInfo.IsDirectory ? fileInfo : _fileSystem.GetDirectoryInfo(Path.GetDirectoryName(path));

            var directoryPath = directoryInfo.FullName;

            var specificFile = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(path) + ".xml");

            var file = _fileSystem.GetFileInfo(specificFile);

            return(file.Exists ? file : _fileSystem.GetFileInfo(Path.Combine(directoryPath, ComicRackMetaFile)));
        }
Example #24
0
        internal Task EnsureArtistInfo(string musicBrainzId, CancellationToken cancellationToken)
        {
            var xmlPath = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId);

            var fileInfo = _fileSystem.GetFileSystemInfo(xmlPath);

            if (fileInfo.Exists &&
                (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
            {
                return(Task.CompletedTask);
            }

            return(DownloadArtistInfo(musicBrainzId, cancellationToken));
        }
Example #25
0
        private async Task <MediaSourceInfo> GetEncodedMediaSource(string path, User user, bool isVideo)
        {
            var item = _libraryManager.ResolvePath(_fileSystem.GetFileSystemInfo(path));

            await item.RefreshMetadata(CancellationToken.None).ConfigureAwait(false);

            var hasMediaSources = item as IHasMediaSources;

            var mediaSources = _mediaSourceManager.GetStaticMediaSources(hasMediaSources, false).ToList();

            var preferredAudio = string.IsNullOrEmpty(user.Configuration.AudioLanguagePreference)
                ? new string[] { }
                : new[] { user.Configuration.AudioLanguagePreference };

            var preferredSubs = string.IsNullOrEmpty(user.Configuration.SubtitleLanguagePreference)
                ? new List <string> {
            }
                : new List <string> {
                user.Configuration.SubtitleLanguagePreference
            };

            foreach (var source in mediaSources)
            {
                if (isVideo)
                {
                    source.DefaultAudioStreamIndex =
                        MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.Configuration.PlayDefaultAudioTrack);

                    var defaultAudioIndex = source.DefaultAudioStreamIndex;
                    var audioLangage      = defaultAudioIndex == null
                        ? null
                        : source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select(i => i.Language).FirstOrDefault();

                    source.DefaultAudioStreamIndex =
                        MediaStreamSelector.GetDefaultSubtitleStreamIndex(source.MediaStreams, preferredSubs, user.Configuration.SubtitleMode, audioLangage);
                }
                else
                {
                    var audio = source.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);

                    if (audio != null)
                    {
                        source.DefaultAudioStreamIndex = audio.Index;
                    }
                }
            }

            return(mediaSources.FirstOrDefault());
        }
Example #26
0
        /// <summary>
        /// Checks and returns data in local cache, downloads and returns if not present.
        /// </summary>
        /// <param name="youtubeID"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        internal Task EnsureInfo(string youtubeID, CancellationToken cancellationToken)
        {
            var ytPath = GetVideoInfoPath(_config.ApplicationPaths, youtubeID);

            var fileInfo = _fileSystem.GetFileSystemInfo(ytPath);

            if (fileInfo.Exists)
            {
                if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 10)
                {
                    return(Task.CompletedTask);
                }
            }
            return(DownloadInfo(youtubeID, cancellationToken));
        }
Example #27
0
        /// <summary>
        /// Try and determine if a file is locked
        /// This is not perfect, and is subject to race conditions, so I'd rather not make this a re-usable library method.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns><c>true</c> if [is file locked] [the specified path]; otherwise, <c>false</c>.</returns>
        private bool IsFileLocked(string path)
        {
            try
            {
                var data = _fileSystem.GetFileSystemInfo(path);

                if (!data.Exists ||
                    data.Attributes.HasFlag(FileAttributes.Directory) ||
                    data.Attributes.HasFlag(FileAttributes.ReadOnly))
                {
                    return(false);
                }
            }
            catch (IOException)
            {
                return(false);
            }

            try
            {
                using (_fileSystem.GetFileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    //file is not locked
                    return(false);
                }
            }
            catch (DirectoryNotFoundException)
            {
                return(false);
            }
            catch (FileNotFoundException)
            {
                return(false);
            }
            catch (IOException)
            {
                //the file is unavailable because it is:
                //still being written to
                //or being processed by another thread
                //or does not exist (has already been processed)
                Logger.Debug("{0} is locked.", path);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        internal Task EnsureMovieXml(string tmdbId, CancellationToken cancellationToken)
        {
            var path = GetFanartXmlPath(tmdbId);

            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            if (fileInfo.Exists)
            {
                if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
                {
                    return(_cachedTask);
                }
            }

            return(DownloadMovieXml(tmdbId, cancellationToken));
        }
Example #29
0
        private FileSystemMetadata?GetEpubFile(string path)
        {
            var fileInfo = _fileSystem.GetFileSystemInfo(path);

            if (fileInfo.IsDirectory)
            {
                return(null);
            }

            if (!string.Equals(Path.GetExtension(fileInfo.FullName), ".epub", StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            return(fileInfo);
        }
        internal Task EnsureInfo(string musicBrainzReleaseGroupId, CancellationToken cancellationToken)
        {
            var xmlPath = GetAlbumInfoPath(_config.ApplicationPaths, musicBrainzReleaseGroupId);

            var fileInfo = _fileSystem.GetFileSystemInfo(xmlPath);

            if (fileInfo.Exists)
            {
                if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 7)
                {
                    return(_cachedTask);
                }
            }

            return(DownloadInfo(musicBrainzReleaseGroupId, cancellationToken));
        }
Example #31
0
        /// <summary>
        /// Ensures DateCreated and DateModified have values
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="item">The item.</param>
        /// <param name="args">The args.</param>
        /// <param name="includeCreationTime">if set to <c>true</c> [include creation time].</param>
        private static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args, bool includeCreationTime)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            // See if a different path came out of the resolver than what went in
            if (!string.Equals(args.Path, item.Path, StringComparison.OrdinalIgnoreCase))
            {
                var childData = args.IsDirectory ? args.GetFileSystemEntryByPath(item.Path) : null;

                if (childData != null)
                {
                    if (includeCreationTime)
                    {
                        SetDateCreated(item, fileSystem, childData);
                    }

                    item.DateModified = fileSystem.GetLastWriteTimeUtc(childData);
                }
                else
                {
                    var fileData = fileSystem.GetFileSystemInfo(item.Path);

                    if (fileData.Exists)
                    {
                        if (includeCreationTime)
                        {
                            SetDateCreated(item, fileSystem, fileData);
                        }
                        item.DateModified = fileSystem.GetLastWriteTimeUtc(fileData);
                    }
                }
            }
            else
            {
                if (includeCreationTime)
                {
                    SetDateCreated(item, fileSystem, args.FileInfo);
                }
                item.DateModified = fileSystem.GetLastWriteTimeUtc(args.FileInfo);
            }
        }
        /// <summary>
        /// Ensures DateCreated and DateModified have values
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="item">The item.</param>
        /// <param name="args">The args.</param>
        /// <param name="includeCreationTime">if set to <c>true</c> [include creation time].</param>
        public static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args, bool includeCreationTime)
        {
            if (!Path.IsPathRooted(item.Path))
            {
                return;
            }

            // See if a different path came out of the resolver than what went in
            if (!string.Equals(args.Path, item.Path, StringComparison.OrdinalIgnoreCase))
            {
                var childData = args.IsDirectory ? args.GetFileSystemEntryByPath(item.Path) : null;

                if (childData != null)
                {
                    if (includeCreationTime)
                    {
                        item.DateCreated = fileSystem.GetCreationTimeUtc(childData);
                    }

                    item.DateModified = fileSystem.GetLastWriteTimeUtc(childData);
                }
                else
                {
                    var fileData = fileSystem.GetFileSystemInfo(item.Path);

                    if (fileData.Exists)
                    {
                        if (includeCreationTime)
                        {
                            item.DateCreated = fileSystem.GetCreationTimeUtc(fileData);
                        }
                        item.DateModified = fileSystem.GetLastWriteTimeUtc(fileData);
                    }
                }
            }
            else
            {
                if (includeCreationTime)
                {
                    item.DateCreated = fileSystem.GetCreationTimeUtc(args.FileInfo);
                }
                item.DateModified = fileSystem.GetLastWriteTimeUtc(args.FileInfo);
            }
        }