Example #1
0
        public List <LocalImageInfo> GetImages(IHasImages item, IDirectoryService directoryService)
        {
            var parentPath = Path.GetDirectoryName(item.Path);

            var parentPathFiles = directoryService.GetFileSystemEntries(parentPath)
                                  .ToList();

            var nameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(item.Path);

            var files = GetFilesFromParentFolder(nameWithoutExtension, parentPathFiles);

            if (files.Count > 0)
            {
                return(files);
            }

            var metadataPath = Path.Combine(parentPath, "metadata");

            if (parentPathFiles.Any(i => string.Equals(i.FullName, metadataPath, StringComparison.OrdinalIgnoreCase)))
            {
                return(GetFilesFromParentFolder(nameWithoutExtension, directoryService.GetFiles(metadataPath)));
            }

            return(new List <LocalImageInfo>());
        }
Example #2
0
        public static IEnumerable <FileSystemMetadata> GetSubtitleFiles(Video video, IDirectoryService directoryService, IFileSystem fileSystem, bool clearCache)
        {
            var containingPath = video.ContainingFolderPath;

            if (string.IsNullOrEmpty(containingPath))
            {
                throw new ArgumentException(string.Format("Cannot search for items that don't have a path: {0} {1}", video.Name, video.Id));
            }

            var files = directoryService.GetFiles(containingPath, clearCache);

            var videoFileNameWithoutExtension = fileSystem.GetFileNameWithoutExtension(video.Path);

            return(files.Where(i =>
            {
                if (!i.IsDirectory &&
                    SubtitleExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
                {
                    var fileNameWithoutExtension = fileSystem.GetFileNameWithoutExtension(i);

                    if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                    if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }

                return false;
            }));
        }
        public void FileSystem_GetFileNameWithExtension()
        {
            var tempFileNameWithOutExtension = FileExtensions.GetRandomFileName("Test_", "");

            _fileSystem.GetFileNameWithoutExtension($"{tempFileNameWithOutExtension}.log").Should()
            .Be(tempFileNameWithOutExtension);
        }
Example #4
0
        public bool GenerateTypesSourceCodeFiles(string projectName, IModelData modelData)
        {
            // Verify if model has types
            if (string.IsNullOrEmpty(modelData.Types))
            {
                return(true);
            }

            // Verify types extension
            if (_fileSystem.GetExtension(modelData.Types) != Constants.FileExtension.ModelTypes)
            {
                AppioLogger.Warn(string.Format(LoggingText.NodesetCompilerExecutableFailsInvalidFile, modelData.Types));
                _outputMessage = string.Format(OutputText.GenerateInformationModelFailureInvalidFile, projectName, modelData.Name, modelData.Types);
                return(false);
            }

            // Verify if types file exists
            var typesPath = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.Models, modelData.Types);

            if (!_fileSystem.FileExists(typesPath))
            {
                AppioLogger.Warn(string.Format(LoggingText.NodesetCompilerExecutableFailsMissingFile, typesPath));
                _outputMessage = string.Format(OutputText.GenerateInformationModelFailureMissingFile, projectName, modelData.Name, typesPath);
                return(false);
            }

            // Create a directory for generated C code
            var srcDirectory = _fileSystem.CombinePaths(projectName, Constants.DirectoryName.SourceCode, Constants.DirectoryName.ServerApp);

            CreateDirectoryForGeneratedModelsSourceCode(srcDirectory);

            // Build types source file and target files directories
            var modelName = _fileSystem.GetFileNameWithoutExtension(modelData.Name);
            var typesSourceRelativePath = @"../../" + _fileSystem.CombinePaths(Constants.DirectoryName.Models, modelData.Types);
            var typesTargetRelativePath = _fileSystem.CombinePaths(Constants.DirectoryName.InformationModels, modelName.ToLower());

            // Build types generation script arguments
            var generatedTypesArgs = Constants.ExecutableName.GenerateDatatypesScriptPath +
                                     string.Format(Constants.ExecutableName.GenerateDatatypesTypeBsd, typesSourceRelativePath) +
                                     " " +
                                     typesTargetRelativePath +
                                     Constants.InformationModelsName.Types;

            // Execute types generation script call
            var generatedTypesResult = _fileSystem.CallExecutable(Constants.ExecutableName.PythonScript, srcDirectory, generatedTypesArgs);

            if (!generatedTypesResult)
            {
                AppioLogger.Warn(LoggingText.GeneratedTypesExecutableFails);
                _outputMessage = string.Format(OutputText.GenerateInformationModelGenerateTypesFailure, projectName, modelData.Name, modelData.Types);
                return(false);
            }

            // Add generated types header file to server's meson build
            AdjustServerMesonBuildCFile(srcDirectory, modelName.ToLower() + Constants.InformationModelsName.TypesGenerated);

            return(true);
        }
Example #5
0
        public List <LocalImageInfo> GetImages(IHasMetadata item, IDirectoryService directoryService)
        {
            var parentPath = _fileSystem.GetDirectoryName(item.Path);

            var parentPathFiles = directoryService.GetFiles(parentPath);

            var nameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(item.Path);

            return(GetFilesFromParentFolder(nameWithoutExtension, parentPathFiles));
        }
Example #6
0
        /// <summary>
        /// Resolves the specified args.
        /// </summary>
        /// <param name="args">The args.</param>
        /// <returns>Trailer.</returns>
        protected override Trailer Resolve(ItemResolveArgs args)
        {
            // Trailers are not Children, therefore this can never happen
            if (args.Parent != null)
            {
                return(null);
            }

            // If the file is within a trailers folder, see if the VideoResolver returns something
            if (!args.IsDirectory)
            {
                if (string.Equals(Path.GetFileName(Path.GetDirectoryName(args.Path)), BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
                {
                    return(base.Resolve(args));
                }

                // Support xbmc local trailer convention, but only when looking for local trailers (hence the parent == null check)
                if (args.Parent == null)
                {
                    var nameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(args.Path);
                    var suffix = BaseItem.ExtraSuffixes.First(i => i.Value == ExtraType.Trailer);

                    if (nameWithoutExtension.EndsWith(suffix.Key, StringComparison.OrdinalIgnoreCase))
                    {
                        return(base.Resolve(args));
                    }
                }
            }

            return(null);
        }
Example #7
0
        private List <LocalImageInfo> GetFilesFromParentFolder(string filenameWithoutExtension, List <FileSystemMetadata> parentPathFiles)
        {
            var thumbName = filenameWithoutExtension + "-thumb";

            var list = new List <LocalImageInfo>(1);

            foreach (var i in parentPathFiles)
            {
                if (i.IsDirectory)
                {
                    continue;
                }

                if (BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
                {
                    var currentNameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(i);

                    if (string.Equals(filenameWithoutExtension, currentNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        list.Add(new LocalImageInfo {
                            FileInfo = i, Type = ImageType.Primary
                        });
                    }
                    else if (string.Equals(thumbName, currentNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        list.Add(new LocalImageInfo {
                            FileInfo = i, Type = ImageType.Primary
                        });
                    }
                }
            }

            return(list);
        }
        /// <summary>
        /// Determine if the supplied list contains what we should consider music
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="allowSubfolders">if set to <c>true</c> [allow subfolders].</param>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="libraryManager">The library manager.</param>
        /// <returns><c>true</c> if the specified list contains music; otherwise, <c>false</c>.</returns>
        private static bool ContainsMusic(IEnumerable <FileSystemInfo> list,
                                          bool allowSubfolders,
                                          IDirectoryService directoryService,
                                          ILogger logger,
                                          IFileSystem fileSystem,
                                          ILibraryManager libraryManager)
        {
            var discSubfolderCount = 0;

            foreach (var fileSystemInfo in list)
            {
                if ((fileSystemInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    if (allowSubfolders && IsAlbumSubfolder(fileSystemInfo, directoryService, logger, fileSystem, libraryManager))
                    {
                        discSubfolderCount++;
                    }
                }

                var fullName = fileSystemInfo.FullName;

                if (libraryManager.IsAudioFile(fullName))
                {
                    // Don't resolve these into audio files
                    if (string.Equals(fileSystem.GetFileNameWithoutExtension(fullName), BaseItem.ThemeSongFilename))
                    {
                        continue;
                    }

                    return(true);
                }
            }

            return(discSubfolderCount > 0);
        }
        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 #10
0
        public async Task DownloadSubtitles(Video video,
                                            string subtitleId,
                                            CancellationToken cancellationToken)
        {
            var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false);

            using (var stream = response.Stream)
            {
                var savePath = Path.Combine(Path.GetDirectoryName(video.Path),
                                            _fileSystem.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLower());

                if (response.IsForced)
                {
                    savePath += ".forced";
                }

                savePath += "." + response.Format.ToLower();

                _logger.Info("Saving subtitles to {0}", savePath);

                _monitor.ReportFileSystemChangeBeginning(savePath);

                try
                {
                    using (var fs = _fileSystem.GetFileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
                    {
                        await stream.CopyToAsync(fs).ConfigureAwait(false);
                    }
                }
                finally
                {
                    _monitor.ReportFileSystemChangeComplete(savePath, false);
                }
            }
        }
        private T GetMovieWithMultipleSources <T>(IEnumerable <T> movies)
            where T : Video, new()
        {
            var sortedMovies = movies.OrderBy(i => i.Path).ToList();

            // Cap this at five to help avoid incorrect matching
            if (sortedMovies.Count > 5)
            {
                return(null);
            }

            var firstMovie = sortedMovies[0];

            var filenamePrefix = Path.GetFileName(Path.GetDirectoryName(firstMovie.Path));

            if (!string.IsNullOrWhiteSpace(filenamePrefix))
            {
                if (sortedMovies.All(i => _fileSystem.GetFileNameWithoutExtension(i.Path).StartsWith(filenamePrefix + " - ", StringComparison.OrdinalIgnoreCase)))
                {
                    firstMovie.HasLocalAlternateVersions = true;

                    _logger.Debug("Multi-version video found: " + firstMovie.Path);

                    return(firstMovie);
                }
            }

            return(null);
        }
Example #12
0
        /// <summary>
        /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="path">The path.</param>
        /// <param name="appPaths">The app paths.</param>
        public static void AddMediaPath(IFileSystem fileSystem, string virtualFolderName, string path, IServerApplicationPaths appPaths)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }

            if (!fileSystem.DirectoryExists(path))
            {
                throw new DirectoryNotFoundException("The path does not exist.");
            }

            var rootFolderPath    = appPaths.DefaultUserViewsPath;
            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);

            var shortcutFilename = fileSystem.GetFileNameWithoutExtension(path);

            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);

            while (fileSystem.FileExists(lnk))
            {
                shortcutFilename += "1";
                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
            }

            fileSystem.CreateShortcut(lnk, path);
        }
Example #13
0
        private void AssertLogFileEntry(IPureLoggerSettings loggerSettings, LogLevel logLevel, string logFileName,
                                        Action <string, LogLevel> testAction)
        {
            string        partialName = _fileSystem.GetFileNameWithoutExtension(logFileName);
            DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(loggerSettings.TestLogFolderPath);

            FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");

            foreach (FileInfo foundFile in filesInDir)
            {
                if (foundFile.Name.StartsWith(partialName))
                {
                    if (!_fileSystem.FileExists(foundFile.FullName))
                    {
                        continue;
                    }

                    using (var sr = new StreamReader(foundFile.FullName))
                    {
                        var logContents = sr.ReadToEnd();

                        testAction(logContents, logLevel);
                    }
                }
            }
        }
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
        /// <summary>
        /// Prepares HelixWorkItem that can run on a device (currently Android or iOS) using XHarness
        /// </summary>
        /// <param name="appPackage">Path to application package</param>
        /// <returns>An ITaskItem instance representing the prepared HelixWorkItem.</returns>
        private async Task <ITaskItem> PrepareWorkItem(IZipArchiveManager zipArchiveManager, IFileSystem fileSystem, ITaskItem appPackage)
        {
            string workItemName = fileSystem.GetFileNameWithoutExtension(appPackage.ItemSpec);

            var(testTimeout, workItemTimeout, expectedExitCode, customCommands) = ParseMetadata(appPackage);

            string command = ValidateMetadataAndGetXHarnessAndroidCommand(appPackage, testTimeout, expectedExitCode);

            if (!fileSystem.GetExtension(appPackage.ItemSpec).Equals(".apk", StringComparison.OrdinalIgnoreCase))
            {
                Log.LogError($"Unsupported app package type: {fileSystem.GetFileName(appPackage.ItemSpec)}");
                return(null);
            }

            Log.LogMessage($"Creating work item with properties Identity: {workItemName}, Payload: {appPackage.ItemSpec}, Command: {command}");

            string workItemZip = await CreateZipArchiveOfPackageAsync(zipArchiveManager, fileSystem, appPackage.ItemSpec);

            return(new Build.Utilities.TaskItem(workItemName, new Dictionary <string, string>()
            {
                { "Identity", workItemName },
                { "PayloadArchive", workItemZip },
                { "Command", command },
                { "Timeout", workItemTimeout.ToString() },
            }));
        }
Example #16
0
        private List <ImageByNameInfo> GetImageList(string path, bool supportsThemes)
        {
            try
            {
                return(_fileSystem.GetFiles(path, BaseItem.SupportedImageExtensions, false, true)
                       .Select(i => new ImageByNameInfo
                {
                    Name = _fileSystem.GetFileNameWithoutExtension(i),
                    FileLength = i.Length,

                    // For themeable images, use the Theme property
                    // For general images, the same object structure is fine,
                    // but it's not owned by a theme, so call it Context
                    Theme = supportsThemes ? GetThemeName(i.FullName, path) : null,
                    Context = supportsThemes ? null : GetThemeName(i.FullName, path),

                    Format = i.Extension.ToLower().TrimStart('.')
                })
                       .OrderBy(i => i.Name)
                       .ToList());
            }
            catch (IOException)
            {
                return(new List <ImageByNameInfo>());
            }
        }
Example #17
0
        /// <summary>
        /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="virtualFolderName">Name of the virtual folder.</param>
        /// <param name="path">The path.</param>
        /// <param name="appPaths">The app paths.</param>
        public static void AddMediaPath(IFileSystem fileSystem, string virtualFolderName, string path, IServerApplicationPaths appPaths)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }

			if (!fileSystem.DirectoryExists(path))
            {
                throw new DirectoryNotFoundException("The path does not exist.");
            }

            var rootFolderPath = appPaths.DefaultUserViewsPath;
            var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName);

            var shortcutFilename = fileSystem.GetFileNameWithoutExtension(path);

            var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);

			while (fileSystem.FileExists(lnk))
            {
                shortcutFilename += "1";
                lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension);
            }

            fileSystem.CreateShortcut(lnk, path);
        }
Example #18
0
        /// <summary>
        /// Loads the ratings.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>Dictionary{System.StringParentalRating}.</returns>
        private void LoadRatings(string file)
        {
            var dict = _fileSystem.ReadAllLines(file).Select(i =>
            {
                if (!string.IsNullOrWhiteSpace(i))
                {
                    var parts = i.Split(',');

                    if (parts.Length == 2)
                    {
                        int value;

                        if (int.TryParse(parts[1], NumberStyles.Integer, UsCulture, out value))
                        {
                            return(new ParentalRating {
                                Name = parts[0], Value = value
                            });
                        }
                    }
                }

                return(null);
            })
                       .Where(i => i != null)
                       .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);

            var countryCode = _fileSystem.GetFileNameWithoutExtension(file)
                              .Split('-')
                              .Last();

            _allParentalRatings.TryAdd(countryCode, dict);
        }
        private List <ImageByNameInfo> GetImageList(string path, bool supportsThemes)
        {
            try
            {
                return(new DirectoryInfo(path)
                       .GetFiles("*", SearchOption.AllDirectories)
                       .Where(i => BaseItem.SupportedImageExtensions.Contains(i.Extension, StringComparer.Ordinal))
                       .Select(i => new ImageByNameInfo
                {
                    Name = _fileSystem.GetFileNameWithoutExtension(i),
                    FileLength = i.Length,

                    // For themeable images, use the Theme property
                    // For general images, the same object structure is fine,
                    // but it's not owned by a theme, so call it Context
                    Theme = supportsThemes ? GetThemeName(i.FullName, path) : null,
                    Context = supportsThemes ? null : GetThemeName(i.FullName, path),

                    Format = i.Extension.ToLower().TrimStart('.')
                })
                       .OrderBy(i => i.Name)
                       .ToList());
            }
            catch (DirectoryNotFoundException)
            {
                return(new List <ImageByNameInfo>());
            }
        }
Example #20
0
        private IEnumerable <InternalProfileInfo> GetProfileInfos(string path, DeviceProfileType type)
        {
            try
            {
                return(new DirectoryInfo(path)
                       .EnumerateFiles("*", SearchOption.TopDirectoryOnly)
                       .Where(i => string.Equals(i.Extension, ".xml", StringComparison.OrdinalIgnoreCase))
                       .Select(i => new InternalProfileInfo
                {
                    Path = i.FullName,

                    Info = new DeviceProfileInfo
                    {
                        Id = i.FullName.ToLower().GetMD5().ToString("N"),
                        Name = _fileSystem.GetFileNameWithoutExtension(i),
                        Type = type
                    }
                })
                       .ToList());
            }
            catch (DirectoryNotFoundException)
            {
                return(new List <InternalProfileInfo>());
            }
        }
Example #21
0
        private string FindBestCandidate(string name, IEnumerable <FileSystemMetadata> subtitleFiles)
        {
            if (!subtitleFiles.Any())
            {
                return("");
            }

            var fileNameParts = BreakNameInParts(name);
            var candidates    = new List <Tuple <string, int> >();

            foreach (var file in subtitleFiles)
            {
                var subtitleParts = BreakNameInParts(_fileSystem.GetFileNameWithoutExtension(file.Name));
                var exceptions    = fileNameParts.Except(subtitleParts);
                candidates.Add(new Tuple <string, int>(file.FullName, exceptions.Count()));
            }
            var sorted = candidates.OrderBy(t => t.Item2);

            _logger.Info($"Media file: {name}");
            foreach (var compareResult in sorted)
            {
                _logger.Info($"File: {compareResult.Item1} has {compareResult.Item2} difference(s)");
            }
            return(sorted.First().Item1);
        }
Example #22
0
        public async Task DownloadSubtitles(Video video,
                                            LibraryOptions libraryOptions,
                                            string subtitleId,
                                            CancellationToken cancellationToken)
        {
            var parts    = subtitleId.Split(new[] { '_' }, 2);
            var provider = GetProvider(parts.First());

            var saveInMediaFolder = libraryOptions.SaveSubtitlesWithMedia;

            try
            {
                var response = await GetRemoteSubtitles(subtitleId, cancellationToken).ConfigureAwait(false);

                using (var stream = response.Stream)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        await stream.CopyToAsync(memoryStream).ConfigureAwait(false);

                        memoryStream.Position = 0;

                        var savePaths    = new List <string>();
                        var saveFileName = _fileSystem.GetFileNameWithoutExtension(video.Path) + "." + response.Language.ToLower();

                        if (response.IsForced)
                        {
                            saveFileName += ".forced";
                        }

                        saveFileName += "." + response.Format.ToLower();

                        if (saveInMediaFolder)
                        {
                            savePaths.Add(Path.Combine(video.ContainingFolderPath, saveFileName));
                        }

                        savePaths.Add(Path.Combine(video.GetInternalMetadataPath(), saveFileName));

                        await TrySaveToFiles(memoryStream, savePaths).ConfigureAwait(false);
                    }
                }
            }
            catch (RateLimitExceededException)
            {
                throw;
            }
            catch (Exception ex)
            {
                EventHelper.FireEventIfNotNull(SubtitleDownloadFailure, this, new SubtitleDownloadFailureEventArgs
                {
                    Item      = video,
                    Exception = ex,
                    Provider  = provider.Name
                }, _logger);

                throw;
            }
        }
Example #23
0
        private List <string> GetOtherDuplicatePaths(string targetPath,
                                                     Series series,
                                                     int?seasonNumber,
                                                     int?episodeNumber,
                                                     int?endingEpisodeNumber)
        {
            // TODO: Support date-naming?
            if (!seasonNumber.HasValue || !episodeNumber.HasValue)
            {
                return(new List <string>());
            }

            var episodePaths = series.GetRecursiveChildren(i => i is Episode)
                               .OfType <Episode>()
                               .Where(i =>
            {
                var locationType = i.LocationType;

                // Must be file system based and match exactly
                if (locationType != LocationType.Remote &&
                    locationType != LocationType.Virtual &&
                    i.ParentIndexNumber.HasValue &&
                    i.ParentIndexNumber.Value == seasonNumber &&
                    i.IndexNumber.HasValue &&
                    i.IndexNumber.Value == episodeNumber)
                {
                    if (endingEpisodeNumber.HasValue || i.IndexNumberEnd.HasValue)
                    {
                        return(endingEpisodeNumber.HasValue && i.IndexNumberEnd.HasValue &&
                               endingEpisodeNumber.Value == i.IndexNumberEnd.Value);
                    }

                    return(true);
                }

                return(false);
            })
                               .Select(i => i.Path)
                               .ToList();

            var folder = _fileSystem.GetDirectoryName(targetPath);
            var targetFileNameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(targetPath);

            try
            {
                var filesOfOtherExtensions = _fileSystem.GetFilePaths(folder)
                                             .Where(i => _libraryManager.IsVideoFile(i) && string.Equals(_fileSystem.GetFileNameWithoutExtension(i), targetFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase));

                episodePaths.AddRange(filesOfOtherExtensions);
            }
            catch (IOException)
            {
                // No big deal. Maybe the season folder doesn't already exist.
            }

            return(episodePaths.Where(i => !string.Equals(i, targetPath, StringComparison.OrdinalIgnoreCase))
                   .Distinct(StringComparer.OrdinalIgnoreCase)
                   .ToList());
        }
        /// <summary>
        /// Determine if the supplied list contains what we should consider music
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="isMusicMediaFolder">if set to <c>true</c> [is music media folder].</param>
        /// <param name="allowSubfolders">if set to <c>true</c> [allow subfolders].</param>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="logger">The logger.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <returns><c>true</c> if the specified list contains music; otherwise, <c>false</c>.</returns>
        private static bool ContainsMusic(IEnumerable <FileSystemInfo> list,
                                          bool isMusicMediaFolder,
                                          bool allowSubfolders,
                                          IDirectoryService directoryService,
                                          ILogger logger,
                                          IFileSystem fileSystem)
        {
            // If list contains at least 2 audio files or at least one and no video files consider it to contain music
            var foundAudio = 0;

            var discSubfolderCount = 0;

            foreach (var fileSystemInfo in list)
            {
                if ((fileSystemInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    if (isMusicMediaFolder && allowSubfolders && IsAlbumSubfolder(fileSystemInfo, true, directoryService, logger, fileSystem))
                    {
                        discSubfolderCount++;
                    }
                    if (!IsAdditionalSubfolderAllowed(fileSystemInfo))
                    {
                        return(false);
                    }
                }

                var fullName = fileSystemInfo.FullName;

                if (EntityResolutionHelper.IsAudioFile(fullName))
                {
                    // Don't resolve these into audio files
                    if (string.Equals(fileSystem.GetFileNameWithoutExtension(fullName), BaseItem.ThemeSongFilename))
                    {
                        continue;
                    }

                    foundAudio++;
                }
                else if (EntityResolutionHelper.IsVideoFile(fullName))
                {
                    return(false);
                }
                else if (EntityResolutionHelper.IsVideoPlaceHolder(fullName))
                {
                    return(false);
                }

                if (foundAudio >= 2)
                {
                    return(true);
                }
            }

            //  or a single audio file and no video files
            return(foundAudio > 0 || discSubfolderCount > 0);
        }
Example #25
0
        public List <LocalImageInfo> GetImages(IHasMetadata item, IDirectoryService directoryService)
        {
            var parentPath = _fileSystem.GetDirectoryName(item.Path);

            var parentPathFiles = directoryService.GetFileSystemEntries(parentPath)
                                  .ToList();

            var nameWithoutExtension = _fileSystem.GetFileNameWithoutExtension(item.Path);

            var metadataPath = Path.Combine(parentPath, "metadata");

            if (parentPathFiles.Any(i => string.Equals(i.FullName, metadataPath, StringComparison.OrdinalIgnoreCase)))
            {
                var filesInMetadataFolder = _fileSystem.GetFiles(metadataPath, BaseItem.SupportedImageExtensions, false, false);
                return(GetFilesFromParentFolder(nameWithoutExtension, filesInMetadataFolder));
            }

            return(new List <LocalImageInfo>());
        }
Example #26
0
        public static string GetMovieSavePath(ItemInfo item, IFileSystem fileSystem)
        {
            if (Directory.Exists(item.Path))
            {
                var path = item.Path;

                return(Path.Combine(path, fileSystem.GetFileNameWithoutExtension(path) + ".nfo"));
            }

            return(Path.ChangeExtension(item.Path, ".nfo"));
        }
Example #27
0
        private void PopulateImages(IHasImages item, List <LocalImageInfo> images, List <FileSystemInfo> files, bool supportParentSeriesFiles, IDirectoryService directoryService)
        {
            var imagePrefix = string.Empty;

            var baseItem = item as BaseItem;

            if (baseItem != null && baseItem.IsInMixedFolder)
            {
                imagePrefix = _fileSystem.GetFileNameWithoutExtension(item.Path) + "-";
            }

            PopulatePrimaryImages(item, images, files, imagePrefix);
            PopulateBackdrops(item, images, files, imagePrefix, directoryService);
            PopulateScreenshots(images, files, imagePrefix);

            AddImage(files, images, imagePrefix + "logo", ImageType.Logo);
            AddImage(files, images, imagePrefix + "clearart", ImageType.Art);
            AddImage(files, images, imagePrefix + "disc", ImageType.Disc);
            AddImage(files, images, imagePrefix + "cdart", ImageType.Disc);
            AddImage(files, images, imagePrefix + "box", ImageType.Box);
            AddImage(files, images, imagePrefix + "back", ImageType.BoxRear);
            AddImage(files, images, imagePrefix + "boxrear", ImageType.BoxRear);
            AddImage(files, images, imagePrefix + "menu", ImageType.Menu);

            // Banner
            AddImage(files, images, imagePrefix + "banner", ImageType.Banner);

            // Thumb
            AddImage(files, images, imagePrefix + "thumb", ImageType.Thumb);
            AddImage(files, images, imagePrefix + "landscape", ImageType.Thumb);

            if (supportParentSeriesFiles)
            {
                var season = item as Season;

                if (season != null)
                {
                    PopulateSeasonImagesFromSeriesFolder(season, images, directoryService);
                }
            }
        }
        /// <summary>
        /// Prepares HelixWorkItem that can run on a device (currently Android or iOS) using XHarness
        /// </summary>
        /// <param name="appPackage">Path to application package</param>
        /// <returns>An ITaskItem instance representing the prepared HelixWorkItem.</returns>
        private async Task <ITaskItem> PrepareWorkItem(IZipArchiveManager zipArchiveManager, IFileSystem fileSystem, ITaskItem appPackage)
        {
            // The user can re-use the same .apk for 2 work items so the name of the work item will come from ItemSpec and path from metadata
            // This can be useful when we want to run the same app with different parameters or run the same app on different test targets, e.g. iOS 13 and 13.5
            string workItemName;
            string apkPath;

            if (appPackage.TryGetMetadata(MetadataNames.ApkPath, out string apkPathMetadata) && !string.IsNullOrEmpty(apkPathMetadata))
            {
                workItemName = appPackage.ItemSpec;
                apkPath      = apkPathMetadata;
            }
            else
            {
                workItemName = fileSystem.GetFileNameWithoutExtension(appPackage.ItemSpec);
                apkPath      = appPackage.ItemSpec;
            }

            if (!fileSystem.FileExists(apkPath))
            {
                Log.LogError($"App package not found in {apkPath}");
                return(null);
            }

            if (!fileSystem.GetExtension(apkPath).Equals(".apk", StringComparison.OrdinalIgnoreCase))
            {
                Log.LogError($"Unsupported app package type: {fileSystem.GetFileName(apkPath)}");
                return(null);
            }

            // Validation of any metadata specific to Android stuff goes here
            if (!appPackage.GetRequiredMetadata(Log, MetadataNames.AndroidPackageName, out string androidPackageName))
            {
                Log.LogError($"{MetadataNames.AndroidPackageName} metadata must be specified; this may match, but can vary from file name");
                return(null);
            }

            var(testTimeout, workItemTimeout, expectedExitCode, customCommands) = ParseMetadata(appPackage);

            if (customCommands == null)
            {
                // When no user commands are specified, we add the default `android test ...` command
                customCommands = GetDefaultCommand(appPackage, expectedExitCode);
            }

            string command = GetHelixCommand(appPackage, apkPath, androidPackageName, testTimeout, expectedExitCode);

            Log.LogMessage($"Creating work item with properties Identity: {workItemName}, Payload: {apkPath}, Command: {command}");

            string workItemZip = await CreateZipArchiveOfPackageAsync(zipArchiveManager, fileSystem, workItemName, apkPath, customCommands);

            return(CreateTaskItem(workItemName, workItemZip, command, workItemTimeout));
        }
Example #29
0
 public void ProcessDirectoryFiles(EnumerationState state)
 {
     foreach (var file in fs.GetFiles(state.DirectoryName, "*.py", SearchOption.TopDirectoryOnly))
     {
         var xlator = new Translator(
             state.Namespace,
             fs.GetFileNameWithoutExtension(file),
             new FileSystem(),
             new ConsoleLogger());
         xlator.TranslateFile(file, file + ".cs");
     }
 }
Example #30
0
        public static string GetMovieSavePath(IHasMetadata item, IFileSystem fileSystem)
        {
            var video = (Video)item;

            if (video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay || video.VideoType == VideoType.HdDvd)
            {
                var path = item.ContainingFolderPath;

                return Path.Combine(path, fileSystem.GetFileNameWithoutExtension(path) + ".nfo");
            }

            return Path.ChangeExtension(item.Path, ".nfo");
        }
Example #31
0
        public static string GetMovieSavePath(IHasMetadata item, IFileSystem fileSystem)
        {
            var video = (Video)item;

            if (video.VideoType == VideoType.Dvd || video.VideoType == VideoType.BluRay || video.VideoType == VideoType.HdDvd)
            {
                var path = item.ContainingFolderPath;

                return(Path.Combine(path, fileSystem.GetFileNameWithoutExtension(path) + ".nfo"));
            }

            return(Path.ChangeExtension(item.Path, ".nfo"));
        }
Example #32
0
        private InternalProfileInfo GetInternalProfileInfo(FileSystemMetadata file, DeviceProfileType type)
        {
            return(new InternalProfileInfo
            {
                Path = file.FullName,

                Info = new DeviceProfileInfo
                {
                    Id = file.FullName.ToLower().GetMD5().ToString("N"),
                    Name = _fileSystem.GetFileNameWithoutExtension(file),
                    Type = type
                }
            });
        }
Example #33
0
        /// <summary>
        /// Determines whether [is season folder] [the specified path].
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="directoryService">The directory service.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <returns><c>true</c> if [is season folder] [the specified path]; otherwise, <c>false</c>.</returns>
        private static bool IsSeasonFolder(string path, IDirectoryService directoryService, IFileSystem fileSystem)
        {
            var seasonNumber = GetSeasonNumberFromPath(path);
            var hasSeasonNumber = seasonNumber != null;

            if (!hasSeasonNumber)
            {
                return false;
            }

            // It's a season folder if it's named as such and does not contain any audio files, apart from theme.mp3
            foreach (var fileSystemInfo in directoryService.GetFileSystemEntries(path))
            {
                var attributes = fileSystemInfo.Attributes;

                if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                {
                    continue;
                }

                // Can't enforce this because files saved by Bitcasa are always marked System
                //if ((attributes & FileAttributes.System) == FileAttributes.System)
                //{
                //    continue;
                //}

                if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    //if (IsBadFolder(fileSystemInfo.Name))
                    //{
                    //    return false;
                    //}
                }
                else
                {
                    if (EntityResolutionHelper.IsAudioFile(fileSystemInfo.FullName) &&
                        !string.Equals(fileSystem.GetFileNameWithoutExtension(fileSystemInfo), BaseItem.ThemeSongFilename))
                    {
                        return false;
                    }
                }
            }

            return true;
        }
Example #34
0
 /// <summary>
 /// Determines whether [is season folder] [the specified path].
 /// </summary>
 /// <param name="path">The path.</param>
 /// <param name="directoryService">The directory service.</param>
 /// <param name="fileSystem">The file system.</param>
 /// <returns><c>true</c> if [is season folder] [the specified path]; otherwise, <c>false</c>.</returns>
 private static bool IsSeasonFolder(string path, IDirectoryService directoryService, IFileSystem fileSystem)
 {
     // It's a season folder if it's named as such and does not contain any audio files, apart from theme.mp3
     return GetSeasonNumberFromPath(path) != null && 
         !directoryService.GetFiles(path)
         .Any(i => EntityResolutionHelper.IsAudioFile(i.FullName) && !string.Equals(fileSystem.GetFileNameWithoutExtension(i), BaseItem.ThemeSongFilename));
 }
Example #35
0
        public static IEnumerable<FileSystemMetadata> GetSubtitleFiles(Video video, IDirectoryService directoryService, IFileSystem fileSystem, bool clearCache)
        {
            var containingPath = video.ContainingFolderPath;

            if (string.IsNullOrEmpty(containingPath))
            {
                throw new ArgumentException(string.Format("Cannot search for items that don't have a path: {0} {1}", video.Name, video.Id));
            }

            var files = directoryService.GetFiles(containingPath, clearCache);

            var videoFileNameWithoutExtension = fileSystem.GetFileNameWithoutExtension(video.Path);

            return files.Where(i =>
            {
                if (!i.Attributes.HasFlag(FileAttributes.Directory) &&
                    SubtitleExtensions.Contains(i.Extension, StringComparer.OrdinalIgnoreCase))
                {
                    var fileNameWithoutExtension = fileSystem.GetFileNameWithoutExtension(i);

                    if (string.Equals(videoFileNameWithoutExtension, fileNameWithoutExtension, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                    if (fileNameWithoutExtension.StartsWith(videoFileNameWithoutExtension + ".", StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }

                return false;
            });
        }