Example #1
0
        public void DeleteFolder(string path)
        {
            logger.Info("Attempting to send '{0}' to recycling bin", path);
            var recyclingBin = _configService.RecycleBin;

            if (String.IsNullOrWhiteSpace(recyclingBin))
            {
                logger.Info("Recycling Bin has not been configured, deleting permanently.");
                _diskProvider.DeleteFolder(path, true);
                logger.Debug("Folder has been permanently deleted: {0}", path);
            }

            else
            {
                var destination = Path.Combine(recyclingBin, new DirectoryInfo(path).Name);

                logger.Debug("Moving '{0}' to '{1}'", path, destination);
                _diskProvider.MoveFolder(path, destination);

                logger.Debug("Setting last accessed: {0}", path);
                _diskProvider.FolderSetLastWriteTimeUtc(destination, DateTime.UtcNow);
                foreach (var file in _diskProvider.GetFiles(destination, SearchOption.AllDirectories))
                {
                    _diskProvider.FileSetLastWriteTimeUtc(file, DateTime.UtcNow);
                }

                logger.Debug("Folder has been moved to the recycling bin: {0}", destination);
            }
        }
Example #2
0
        public void Backup(BackupType backupType)
        {
            _logger.ProgressInfo("Starting Backup");

            _diskProvider.EnsureFolder(_backupTempFolder);
            _diskProvider.EnsureFolder(GetBackupFolder(backupType));

            var backupFilename = string.Format("radarr_backup_v{0}_{1:yyyy.MM.dd_HH.mm.ss}.zip", BuildInfo.Version, DateTime.Now);
            var backupPath     = Path.Combine(GetBackupFolder(backupType), backupFilename);

            Cleanup();

            if (backupType != BackupType.Manual)
            {
                CleanupOldBackups(backupType);
            }

            BackupConfigFile();
            BackupDatabase();
            CreateVersionInfo();

            _logger.ProgressDebug("Creating backup zip");

            // Delete journal file created during database backup
            _diskProvider.DeleteFile(Path.Combine(_backupTempFolder, "radarr.db-journal"));

            _archiveService.CreateZip(backupPath, _diskProvider.GetFiles(_backupTempFolder, SearchOption.TopDirectoryOnly));

            _logger.ProgressDebug("Backup zip created");
        }
Example #3
0
        public void DeleteFolder(string path)
        {
            _logger.Info("Attempting to send '{0}' to recycling bin", path);
            var recyclingBin = _configService.RecycleBin;

            if (string.IsNullOrWhiteSpace(recyclingBin))
            {
                _logger.Info("Recycling Bin has not been configured, deleting permanently. {0}", path);
                _diskProvider.DeleteFolder(path, true);
                _logger.Debug("Folder has been permanently deleted: {0}", path);
            }

            else
            {
                var destination = Path.Combine(recyclingBin, new DirectoryInfo(path).Name);

                _logger.Debug("Moving '{0}' to '{1}'", path, destination);
                _diskTransferService.TransferFolder(path, destination, TransferMode.Move);

                _logger.Debug("Setting last accessed: {0}", path);
                _diskProvider.FolderSetLastWriteTime(destination, DateTime.UtcNow);
                foreach (var file in _diskProvider.GetFiles(destination, SearchOption.AllDirectories))
                {
                    if (OsInfo.IsWindows)
                    {
                        //TODO: Better fix than this for non-Windows?
                        _diskProvider.FileSetLastWriteTime(file, DateTime.UtcNow);
                    }
                }

                _logger.Debug("Folder has been moved to the recycling bin: {0}", destination);
            }
        }
Example #4
0
        public string[] GetVideoFiles(string path, bool allDirectories = true)
        {
            _logger.Debug("Scanning '{0}' for video files", path);

            var searchOption = allDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            var filesOnDisk  = _diskProvider.GetFiles(path, searchOption);

            var mediaFileList = filesOnDisk.Where(file => MediaFileExtensions.Extensions.Contains(Path.GetExtension(file).ToLower()))
                                .ToList();

            _logger.Debug("{0} video files were found in {1}", mediaFileList.Count, path);
            return(mediaFileList.ToArray());
        }
        public OsVersionModel Read()
        {
            var version = "10.0";

            if (!_diskProvider.FolderExists(PLIST_DIR))
            {
                _logger.Debug("Directory {0} doesn't exist", PLIST_DIR);
                return(null);
            }

            var allFiles = _diskProvider.GetFiles(PLIST_DIR, SearchOption.TopDirectoryOnly);

            var versionFile = allFiles.SingleOrDefault(c =>
                                                       c.EndsWith("SystemVersion.plist") ||
                                                       c.EndsWith("ServerVersion.plist"));

            if (string.IsNullOrWhiteSpace(versionFile))
            {
                _logger.Debug("Couldn't find version plist file in {0}", PLIST_DIR);
                return(null);
            }

            var text  = _diskProvider.ReadAllText(versionFile);
            var match = DarwinVersionRegex.Match(text);

            if (match.Success)
            {
                version = match.Groups["version"].Value;
            }

            var name = versionFile.Contains("Server") ? "macOS Server" : "macOS";

            return(new OsVersionModel(name, version));
        }
        public bool ShouldDeleteFolder(DirectoryInfo directoryInfo, Series series)
        {
            var videoFiles = _diskScanService.GetVideoFiles(directoryInfo.FullName);
            var rarFiles   = _diskProvider.GetFiles(directoryInfo.FullName, SearchOption.AllDirectories).Where(f => Path.GetExtension(f) == ".rar");

            foreach (var videoFile in videoFiles)
            {
                var episodeParseResult = Parser.Parser.ParseTitle(Path.GetFileName(videoFile));

                if (episodeParseResult == null)
                {
                    _logger.Warn("Unable to parse file on import: [{0}]", videoFile);
                    return(false);
                }

                var size    = _diskProvider.GetFileSize(videoFile);
                var quality = QualityParser.ParseQuality(videoFile);

                if (!_detectSample.IsSample(series, quality, videoFile, size, episodeParseResult.IsPossibleSpecialEpisode))
                {
                    _logger.Warn("Non-sample file detected: [{0}]", videoFile);
                    return(false);
                }
            }

            if (rarFiles.Any(f => _diskProvider.GetFileSize(f) > 10.Megabytes()))
            {
                _logger.Warn("RAR file detected, will require manual cleanup");
                return(false);
            }

            return(true);
        }
Example #7
0
        public bool ShouldDeleteFolder(DirectoryInfo directoryInfo, Movie movie)
        {
            var videoFiles = _diskScanService.GetVideoFiles(directoryInfo.FullName);
            var rarFiles   = _diskProvider.GetFiles(directoryInfo.FullName, SearchOption.AllDirectories).Where(f => Path.GetExtension(f).Equals(".rar", StringComparison.OrdinalIgnoreCase));

            foreach (var videoFile in videoFiles)
            {
                var episodeParseResult =
                    Parser.Parser.ParseMovieTitle(Path.GetFileName(videoFile), _config.ParsingLeniency > 0);

                if (episodeParseResult == null)
                {
                    _logger.Warn("Unable to parse file on import: [{0}]", videoFile);
                    return(false);
                }

                var size = _diskProvider.GetFileSize(videoFile);

                if (!_detectSample.IsSample(movie, QualityParser.ParseQuality(Path.GetFileName(videoFile)), videoFile, size, false))
                {
                    _logger.Warn("Non-sample file detected: [{0}]", videoFile);
                    return(false);
                }
            }

            if (rarFiles.Any(f => _diskProvider.GetFileSize(f) > 10.Megabytes()))
            {
                _logger.Warn("RAR file detected, will require manual cleanup");
                return(false);
            }

            return(true);
        }
Example #8
0
        public OsVersionModel Read()
        {
            if (!_diskProvider.FolderExists("/etc/"))
            {
                return(null);
            }

            var issueFile = _diskProvider.GetFiles("/etc/", SearchOption.TopDirectoryOnly).SingleOrDefault(c => c.EndsWith("/issue"));

            if (issueFile == null)
            {
                return(null);
            }

            var fileContent = _diskProvider.ReadAllText(issueFile);

            // Ubuntu 14.04.5 LTS \n \l
            // Ubuntu 16.04.1 LTS \n \l

            // Fedora/Centos
            // Kernel \r on an \m (\l)

            // Arch Linux \r (\l)
            // Debian GNU/Linux 8 \n \l
            if (fileContent.Contains("Arch Linux"))
            {
                return(new OsVersionModel("Arch", "1.0", "Arch Linux"));
            }

            return(null);
        }
        public bool ShouldDeleteFolder(IDirectoryInfo directoryInfo, Author author)
        {
            var bookFiles = _diskScanService.GetBookFiles(directoryInfo.FullName);
            var rarFiles  = _diskProvider.GetFiles(directoryInfo.FullName, SearchOption.AllDirectories).Where(f => Path.GetExtension(f).Equals(".rar", StringComparison.OrdinalIgnoreCase));

            foreach (var bookFile in bookFiles)
            {
                var bookParseResult = Parser.Parser.ParseTitle(bookFile.Name);

                if (bookParseResult == null)
                {
                    _logger.Warn("Unable to parse file on import: [{0}]", bookFile);
                    return(false);
                }

                _logger.Warn("Book file detected: [{0}]", bookFile);
                return(false);
            }

            if (rarFiles.Any(f => _diskProvider.GetFileSize(f) > 10.Megabytes()))
            {
                _logger.Warn("RAR file detected, will require manual cleanup");
                return(false);
            }

            return(true);
        }
Example #10
0
        public bool ShouldDeleteFolder(IDirectoryInfo directoryInfo, Artist artist)
        {
            try
            {
                var audioFiles = _diskScanService.GetAudioFiles(directoryInfo.FullName);
                var rarFiles   = _diskProvider.GetFiles(directoryInfo.FullName, SearchOption.AllDirectories).Where(f => Path.GetExtension(f).Equals(".rar", StringComparison.OrdinalIgnoreCase));

                foreach (var audioFile in audioFiles)
                {
                    var albumParseResult = Parser.Parser.ParseMusicTitle(audioFile.Name);

                    if (albumParseResult == null)
                    {
                        _logger.Warn("Unable to parse file on import: [{0}]", audioFile);
                        return(false);
                    }

                    _logger.Warn("Audio file detected: [{0}]", audioFile);
                    return(false);
                }

                if (rarFiles.Any(f => _diskProvider.GetFileSize(f) > 10.Megabytes()))
                {
                    _logger.Warn("RAR file detected, will require manual cleanup");
                    return(false);
                }

                return(true);
            }
            catch (DirectoryNotFoundException e)
            {
                _logger.Debug(e, "Folder {0} has already been removed", directoryInfo.FullName);
                return(false);
            }
        }
Example #11
0
 private void CleanupSqLiteRollbackFiles()
 {
     _diskProvider.GetFiles(_appFolderInfo.AppDataFolder, SearchOption.TopDirectoryOnly)
     .Where(f => Path.GetFileName(f).StartsWith("nzbdrone.db"))
     .ToList()
     .ForEach(_diskProvider.DeleteFile);
 }
Example #12
0
        public OsVersionModel Read()
        {
            if (!_diskProvider.FolderExists("/etc/"))
            {
                return(null);
            }

            var releaseFiles = _diskProvider.GetFiles("/etc/", SearchOption.TopDirectoryOnly).Where(c => c.EndsWith("release")).ToList();

            var name     = "Linux";
            var fullName = "";
            var version  = "";

            bool success = false;

            foreach (var releaseFile in releaseFiles)
            {
                var fileContent = _diskProvider.ReadAllText(releaseFile);
                var lines       = Regex.Split(fileContent, "\r\n|\r|\n");

                foreach (var line in lines)
                {
                    var parts = line.Split('=');
                    if (parts.Length >= 2)
                    {
                        var key   = parts[0];
                        var value = parts[1];

                        if (!string.IsNullOrWhiteSpace(value))
                        {
                            switch (key)
                            {
                            case "ID":
                                success = true;
                                name    = value;
                                break;

                            case "PRETTY_NAME":
                                success  = true;
                                fullName = value;
                                break;

                            case "VERSION_ID":
                                success = true;
                                version = value;
                                break;
                            }
                        }
                    }
                }
            }

            if (!success)
            {
                return(null);
            }

            return(new OsVersionModel(name, version, fullName));
        }
        public void Execute(DeleteLogFilesCommand message)
        {
            var logFiles = _diskProvider.GetFiles(_appFolderInfo.GetLogFolder(), SearchOption.TopDirectoryOnly);

            foreach (var logFile in logFiles)
            {
                _diskProvider.DeleteFile(logFile);
            }
        }
Example #14
0
        private MovieFile TransferFile(MovieFile movieFile, Movie movie, string destinationFilePath, TransferMode mode)
        {
            Ensure.That(movieFile, () => movieFile).IsNotNull();
            Ensure.That(movie, () => movie).IsNotNull();
            Ensure.That(destinationFilePath, () => destinationFilePath).IsValidPath();

            var movieFilePath = movieFile.Path ?? Path.Combine(movie.Path, movieFile.RelativePath);

            if (!_diskProvider.FileExists(movieFilePath))
            {
                throw new FileNotFoundException("Movie file path does not exist", movieFilePath);
            }

            if (movieFilePath == destinationFilePath)
            {
                throw new SameFilenameException("File not moved, source and destination are the same", movieFilePath);
            }

            _diskTransferService.TransferFile(movieFilePath, destinationFilePath, mode);

            var oldMoviePath = movie.Path;

            var newMoviePath = new OsPath(destinationFilePath).Directory.FullPath.TrimEnd(Path.DirectorySeparatorChar);

            movie.Path = newMoviePath;
            if (oldMoviePath != newMoviePath)
            {
                _movieService.UpdateMovie(movie);
            }

            movieFile.RelativePath = movie.Path.GetRelativePath(destinationFilePath);

            _updateMovieFileService.ChangeFileDateForFile(movieFile, movie);

            try
            {
                _mediaFileAttributeService.SetFolderLastWriteTime(movie.Path, movieFile.DateAdded);
            }

            catch (Exception ex)
            {
                _logger.Warn(ex, "Unable to set last write time");
            }

            _mediaFileAttributeService.SetFilePermissions(destinationFilePath);

            if (oldMoviePath != newMoviePath)
            {
                if (_diskProvider.GetFiles(oldMoviePath, SearchOption.AllDirectories).Count() == 0)
                {
                    _recycleBinProvider.DeleteFolder(oldMoviePath);
                }
            }

            return(movieFile);
        }
        public OsVersionModel Read()
        {
            if (!_diskProvider.FolderExists("/etc.defaults/"))
            {
                return(null);
            }

            var versionFile = _diskProvider.GetFiles("/etc.defaults/", SearchOption.TopDirectoryOnly).SingleOrDefault(c => c.EndsWith("VERSION"));

            if (versionFile == null)
            {
                return(null);
            }

            var version = "";
            var major   = "";
            var minor   = "0";

            var fileContent = _diskProvider.ReadAllText(versionFile);
            var lines       = Regex.Split(fileContent, "\r\n|\r|\n");

            foreach (var line in lines)
            {
                var parts = line.Split('=');
                if (parts.Length >= 2)
                {
                    var key   = parts[0];
                    var value = parts[1].Trim('"');

                    if (!string.IsNullOrWhiteSpace(value))
                    {
                        switch (key)
                        {
                        case "productversion":
                            version = value;
                            break;

                        case "majorversion":
                            major = value;
                            break;

                        case "minorversion":
                            minor = value;
                            break;
                        }
                    }
                }
            }

            if (string.IsNullOrWhiteSpace(version) && !string.IsNullOrWhiteSpace(major))
            {
                version = $"{major}.{minor}";
            }

            return(new OsVersionModel(NAME, version, $"{FULL_NAME} {version}"));
        }
        public void Handle(SeriesScannedEvent message)
        {
            if (!_diskProvider.FolderExists(message.Series.Path))
            {
                return;
            }

            _logger.Debug("Looking for existing metadata in {0}", message.Series.Path);

            var filesOnDisk = _diskProvider.GetFiles(message.Series.Path, SearchOption.AllDirectories);

            var possibleMetadataFiles = filesOnDisk.Where(c => !MediaFileExtensions.Extensions.Contains(Path.GetExtension(c).ToLower()) &&
                                                          !c.StartsWith(Path.Combine(message.Series.Path, "EXTRAS"))).ToList();

            var filteredFiles = _metadataFileService.FilterExistingFiles(possibleMetadataFiles, message.Series);

            var metadataFiles = new List <MetadataFile>();

            foreach (var possibleMetadataFile in filteredFiles)
            {
                foreach (var consumer in _consumers)
                {
                    var metadata = consumer.FindMetadataFile(message.Series, possibleMetadataFile);

                    if (metadata == null)
                    {
                        continue;
                    }

                    if (metadata.Type == MetadataType.EpisodeImage ||
                        metadata.Type == MetadataType.EpisodeMetadata)
                    {
                        var localEpisode = _parsingService.GetLocalEpisode(possibleMetadataFile, message.Series, false);

                        if (localEpisode == null)
                        {
                            _logger.Debug("Cannot find related episodes for: {0}", possibleMetadataFile);
                            break;
                        }

                        if (localEpisode.Episodes.DistinctBy(e => e.EpisodeFileId).Count() > 1)
                        {
                            _logger.Debug("Metadata file: {0} does not match existing files.", possibleMetadataFile);
                            break;
                        }

                        metadata.EpisodeFileId = localEpisode.Episodes.First().EpisodeFileId;
                    }

                    metadataFiles.Add(metadata);
                }
            }

            _metadataFileService.Upsert(metadataFiles);
        }
Example #17
0
        protected override IEnumerable <string> GetLogFiles()
        {
            if (!_diskProvider.FolderExists(_appFolderInfo.GetUpdateLogFolder()))
            {
                return(Enumerable.Empty <string>());
            }

            return(_diskProvider.GetFiles(_appFolderInfo.GetUpdateLogFolder(), SearchOption.TopDirectoryOnly)
                   .Where(f => Regex.IsMatch(Path.GetFileName(f), LOGFILE_ROUTE.TrimStart('/'), RegexOptions.IgnoreCase))
                   .ToList());
        }
Example #18
0
        public void ImportExtraFiles(LocalEpisode localEpisode, EpisodeFile episodeFile, bool isReadOnly)
        {
            var series = localEpisode.Series;

            foreach (var extraFileManager in _extraFileManagers)
            {
                extraFileManager.CreateAfterEpisodeImport(series, episodeFile);
            }

            if (!_configService.ImportExtraFiles)
            {
                return;
            }

            var sourcePath     = localEpisode.Path;
            var sourceFolder   = _diskProvider.GetParentFolder(sourcePath);
            var sourceFileName = Path.GetFileNameWithoutExtension(sourcePath);
            var files          = _diskProvider.GetFiles(sourceFolder, SearchOption.TopDirectoryOnly);

            var wantedExtensions = _configService.ExtraFileExtensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                   .Select(e => e.Trim(' ', '.'))
                                   .ToList();

            var matchingFilenames = files.Where(f => Path.GetFileNameWithoutExtension(f).StartsWith(sourceFileName));

            foreach (var matchingFilename in matchingFilenames)
            {
                var matchingExtension = wantedExtensions.FirstOrDefault(e => matchingFilename.EndsWith(e));

                if (matchingExtension == null)
                {
                    continue;
                }

                try
                {
                    foreach (var extraFileManager in _extraFileManagers)
                    {
                        var extension = Path.GetExtension(matchingFilename);
                        var extraFile = extraFileManager.Import(series, episodeFile, matchingFilename, extension, isReadOnly);

                        if (extraFile != null)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Warn(ex, "Failed to import extra file: {0}", matchingFilename);
                }
            }
        }
Example #19
0
        public void Handle(BookFileDeletedEvent message)
        {
            if (message.Reason == DeleteMediaFileReason.Upgrade)
            {
                return;
            }

            if (_configService.DeleteEmptyFolders)
            {
                var author     = message.BookFile.Author.Value;
                var bookFolder = message.BookFile.Path.GetParentPath();

                if (_diskProvider.GetFiles(author.Path, SearchOption.AllDirectories).Empty())
                {
                    _diskProvider.DeleteFolder(author.Path, true);
                }
                else if (_diskProvider.GetFiles(bookFolder, SearchOption.AllDirectories).Empty())
                {
                    _diskProvider.RemoveEmptySubfolders(bookFolder);
                }
            }
        }
Example #20
0
        public void Backup(BackupType backupType)
        {
            _logger.ProgressInfo("Starting Backup");

            _diskProvider.EnsureFolder(_backupTempFolder);
            _diskProvider.EnsureFolder(GetBackupFolder(backupType));

            var backupFilename = String.Format("nzbdrone_backup_{0:yyyy.MM.dd_HH.mm.ss}.zip", DateTime.Now);
            var backupPath     = Path.Combine(GetBackupFolder(backupType), backupFilename);

            Cleanup();

            if (backupType != BackupType.Manual)
            {
                CleanupOldBackups(backupType);
            }

            BackupConfigFile();
            BackupDatabase();

            _logger.ProgressDebug("Creating backup zip");
            _archiveService.CreateZip(backupPath, _diskProvider.GetFiles(_backupTempFolder, SearchOption.TopDirectoryOnly));
            _logger.ProgressDebug("Backup zip created");
        }
Example #21
0
        public bool ShouldDeleteFolder(DirectoryInfo directoryInfo, Series series)
        {
            try
            {
                var videoFiles = _diskScanService.GetVideoFiles(directoryInfo.FullName);
                var rarFiles   = _diskProvider.GetFiles(directoryInfo.FullName, SearchOption.AllDirectories).Where(f =>
                                                                                                                   Path.GetExtension(f).Equals(".rar",
                                                                                                                                               StringComparison.OrdinalIgnoreCase));

                foreach (var videoFile in videoFiles)
                {
                    var episodeParseResult = Parser.Parser.ParseTitle(Path.GetFileName(videoFile));

                    if (episodeParseResult == null)
                    {
                        _logger.Warn("Unable to parse file on import: [{0}]", videoFile);
                        return(false);
                    }

                    if (_detectSample.IsSample(series, videoFile, episodeParseResult.IsPossibleSpecialEpisode) !=
                        DetectSampleResult.Sample)
                    {
                        _logger.Warn("Non-sample file detected: [{0}]", videoFile);
                        return(false);
                    }
                }

                if (rarFiles.Any(f => _diskProvider.GetFileSize(f) > 10.Megabytes()))
                {
                    _logger.Warn("RAR file detected, will require manual cleanup");
                    return(false);
                }

                return(true);
            }
            catch (DirectoryNotFoundException e)
            {
                _logger.Debug(e, "Folder {0} has already been removed", directoryInfo.FullName);
                return(false);
            }
            catch (Exception e)
            {
                _logger.Debug(e, "Unable to determine whether folder {0} should be removed", directoryInfo.FullName);
                return(false);
            }
        }
Example #22
0
        private void ImportExtraFiles(LocalEpisode localEpisode, EpisodeFile episodeFile, bool isReadOnly)
        {
            if (!_configService.ImportExtraFiles)
            {
                return;
            }

            var folderSearchOption = localEpisode.FolderEpisodeInfo == null
                ? SearchOption.TopDirectoryOnly
                : SearchOption.AllDirectories;

            var wantedExtensions = _configService.ExtraFileExtensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                   .Select(e => e.Trim(' ', '.')
                                           .Insert(0, "."))
                                   .ToList();

            var sourceFolder = _diskProvider.GetParentFolder(localEpisode.Path);
            var files        = _diskProvider.GetFiles(sourceFolder, folderSearchOption);
            var managedFiles = _extraFileManagers.Select((i) => new List <string>()).ToArray();

            foreach (var file in files)
            {
                var extension         = Path.GetExtension(file);
                var matchingExtension = wantedExtensions.FirstOrDefault(e => e.Equals(extension));

                if (matchingExtension == null)
                {
                    continue;
                }

                for (int i = 0; i < _extraFileManagers.Count; i++)
                {
                    if (_extraFileManagers[i].CanImportFile(localEpisode, episodeFile, file, extension, isReadOnly))
                    {
                        managedFiles[i].Add(file);
                        break;
                    }
                }
            }

            for (int i = 0; i < _extraFileManagers.Count; i++)
            {
                _extraFileManagers[i].ImportFiles(localEpisode, episodeFile, managedFiles[i], isReadOnly);
            }
        }
Example #23
0
        private List <LogFileResource> GetLogFiles()
        {
            var result = new List <LogFileResource>();

            var files = _diskProvider.GetFiles(_appFolderInfo.GetLogFolder(), SearchOption.TopDirectoryOnly);

            for (int i = 0; i < files.Length; i++)
            {
                var file = files[i];

                result.Add(new LogFileResource
                {
                    Id            = i + 1,
                    Filename      = Path.GetFileName(file),
                    LastWriteTime = _diskProvider.FileGetLastWriteUtc(file)
                });
            }

            return(result.OrderByDescending(l => l.LastWriteTime).ToList());
        }
Example #24
0
        public void RenameMoviePath(Movie movie, bool shouldRenameFiles = true)
        {
            var newFolder = _filenameBuilder.BuildMoviePath(movie);

            if (newFolder != movie.Path && movie.PathState == MoviePathState.Dynamic)
            {
                if (!_configService.AutoRenameFolders)
                {
                    _logger.Info("{0}'s movie should be {1} according to your naming config.", movie, newFolder);
                    return;
                }

                _logger.Info("{0}'s movie folder changed to: {1}", movie, newFolder);
                var oldFolder = movie.Path;
                movie.Path = newFolder;

                _diskProvider.MoveFolder(oldFolder, movie.Path);

                if (false)
                {
                    var movieFiles = _mediaFileService.GetFilesByMovie(movie.Id);
                    _logger.ProgressInfo("Renaming movie files for {0}", movie.Title);
                    RenameFiles(movieFiles, movie, oldFolder);
                    _logger.ProgressInfo("All movie files renamed for {0}", movie.Title);
                }

                _movieService.UpdateMovie(movie);

                if (_diskProvider.GetFiles(oldFolder, SearchOption.AllDirectories).Count() == 0)
                {
                    _recycleBinProvider.DeleteFolder(oldFolder);
                }
            }

            if (movie.PathState == MoviePathState.StaticOnce)
            {
                movie.PathState = MoviePathState.Dynamic;
                _movieService.UpdateMovie(movie);
            }
        }
Example #25
0
        private FileSystemResult GetResult(string path, bool includeFiles)
        {
            var result = new FileSystemResult();

            try
            {
                result.Parent      = _diskProvider.GetParent(path);
                result.Directories = _diskProvider.GetDirectories(path);

                if (includeFiles)
                {
                    result.Files = _diskProvider.GetFiles(path);
                }
            }
            catch (DirectoryNotFoundException)
            {
                return(new FileSystemResult {
                    Parent = _diskProvider.GetParent(path)
                });
            }
            catch (ArgumentException)
            {
                return(new FileSystemResult());
            }
            catch (IOException)
            {
                return(new FileSystemResult {
                    Parent = _diskProvider.GetParent(path)
                });
            }
            catch (UnauthorizedAccessException)
            {
                return(new FileSystemResult {
                    Parent = _diskProvider.GetParent(path)
                });
            }

            return(result);
        }
        public Decision IsSatisfiedBy(LocalMovie localMovie, DownloadClientItem downloadClientItem)
        {
            var regexReplace = MovieMultiPartRegex.First().Replace(localMovie.Path, "");

            if (MovieMultiPartRegex.Any(v => v.IsMatch(localMovie.Path)))
            {
                var parentPath       = localMovie.Path.GetParentPath();
                var filesInDirectory = _diskProvider.GetFiles(localMovie.Path.GetParentPath(), SearchOption.TopDirectoryOnly);

                foreach (var regex in MovieMultiPartRegex)
                {
                    if (filesInDirectory.Where(file => regex.Replace(file, "") == regex.Replace(localMovie.Path, "")).Count() > 1)
                    {
                        _logger.Debug("Rejected Multi-Part File: {0}", localMovie.Path);

                        return(Decision.Reject("File is suspected multi-part file, Radarr doesn't support"));
                    }
                }
            }

            return(Decision.Accept());
        }
        private MovieFile TransferFile(MovieFile movieFile, Movie movie, string destinationFilePath, TransferMode mode)
        {
            Ensure.That(movieFile, () => movieFile).IsNotNull();
            Ensure.That(movie, () => movie).IsNotNull();
            Ensure.That(destinationFilePath, () => destinationFilePath).IsValidPath();

            var movieFilePath = movieFile.Path ?? Path.Combine(movie.Path, movieFile.RelativePath);

            if (!_diskProvider.FileExists(movieFilePath))
            {
                throw new FileNotFoundException("Movie file path does not exist", movieFilePath);
            }

            if (movieFilePath == destinationFilePath)
            {
                throw new SameFilenameException("File not moved, source and destination are the same", movieFilePath);
            }

            _diskTransferService.TransferFile(movieFilePath, destinationFilePath, mode);

            var oldMoviePath = movie.Path;

            var newMoviePath = new OsPath(destinationFilePath).Directory.FullPath.TrimEnd(Path.DirectorySeparatorChar);

            movie.Path = newMoviePath; //We update it when everything went well!

            movieFile.RelativePath = movie.Path.GetRelativePath(destinationFilePath);

            _updateMovieFileService.ChangeFileDateForFile(movieFile, movie);

            try
            {
                _mediaFileAttributeService.SetFolderLastWriteTime(movie.Path, movieFile.DateAdded);
            }

            catch (Exception ex)
            {
                _logger.Warn(ex, "Unable to set last write time");
            }

            _mediaFileAttributeService.SetFilePermissions(destinationFilePath);

            if (oldMoviePath != newMoviePath && _diskProvider.FolderExists(oldMoviePath))
            {
                //Let's move the old files before deleting the old folder. We could just do move folder, but the main file (movie file) is already moved, so eh.
                var files = _diskProvider.GetFiles(oldMoviePath, SearchOption.AllDirectories);

                foreach (var file in files)
                {
                    try
                    {
                        var destFile = Path.Combine(newMoviePath, oldMoviePath.GetRelativePath(file));
                        _diskProvider.EnsureFolder(Path.GetDirectoryName(destFile));
                        _diskProvider.MoveFile(file, destFile);
                    }
                    catch (Exception e)
                    {
                        _logger.Warn(e, "Error while trying to move extra file {0} to new folder. Maybe it already exists? (Manual cleanup necessary!).", oldMoviePath.GetRelativePath(file));
                    }
                }

                if (_diskProvider.GetFiles(oldMoviePath, SearchOption.AllDirectories).Count() == 0)
                {
                    _recycleBinProvider.DeleteFolder(oldMoviePath);
                }
            }

            //Only update the movie path if we were successfull!
            if (oldMoviePath != newMoviePath)
            {
                _movieService.UpdateMovie(movie);
            }

            return(movieFile);
        }
Example #28
0
        private IEnumerable <WatchFolderItem> GetDownloadItems(string watchFolder, Dictionary <string, WatchFolderItem> lastWatchItems, TimeSpan waitPeriod)
        {
            // get a fresh naming config each time, in case the user has made changes
            foreach (var folder in _diskProvider.GetDirectories(watchFolder))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(folder));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(folder) + "_" + _diskProvider.FolderGetCreationTime(folder).Ticks,
                    Title      = title,

                    OutputPath = new OsPath(folder),

                    Status        = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    var files = _diskProvider.GetFiles(folder, SearchOption.AllDirectories);

                    newWatchItem.TotalSize = files.Select(_diskProvider.GetFileSize).Sum();
                    newWatchItem.Hash      = GetHash(folder, files);

                    if (files.Any(_diskProvider.IsFileLocked))
                    {
                        newWatchItem.Status        = DownloadItemStatus.Downloading;
                        newWatchItem.RemainingTime = null;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return(newWatchItem);
            }

            foreach (var videoFile in _diskScanService.GetVideoFiles(watchFolder, false))
            {
                var title = FileNameBuilder.CleanFileName(Path.GetFileName(videoFile));

                var newWatchItem = new WatchFolderItem
                {
                    DownloadId = Path.GetFileName(videoFile) + "_" + _diskProvider.FileGetLastWrite(videoFile).Ticks,
                    Title      = title,

                    OutputPath = new OsPath(videoFile),

                    Status        = DownloadItemStatus.Completed,
                    RemainingTime = TimeSpan.Zero
                };

                var oldWatchItem = lastWatchItems.GetValueOrDefault(newWatchItem.DownloadId);

                if (PreCheckWatchItemExpiry(newWatchItem, oldWatchItem))
                {
                    newWatchItem.TotalSize = _diskProvider.GetFileSize(videoFile);
                    newWatchItem.Hash      = GetHash(videoFile);

                    if (_diskProvider.IsFileLocked(videoFile))
                    {
                        newWatchItem.Status = DownloadItemStatus.Downloading;
                    }

                    UpdateWatchItemExpiry(newWatchItem, oldWatchItem, waitPeriod);
                }

                yield return(newWatchItem);
            }
        }
Example #29
0
        public void ImportExtraFiles(LocalBook localBook, BookFile bookFile, bool isReadOnly)
        {
            if (!_configService.ImportExtraFiles)
            {
                return;
            }

            var sourcePath     = localBook.Path;
            var sourceFolder   = _diskProvider.GetParentFolder(sourcePath);
            var sourceFileName = Path.GetFileNameWithoutExtension(sourcePath);
            var files          = _diskProvider.GetFiles(sourceFolder, SearchOption.TopDirectoryOnly);

            var wantedExtensions = _configService.ExtraFileExtensions.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                   .Select(e => e.Trim(' ', '.'))
                                   .ToList();

            var matchingFilenames = files.Where(f => Path.GetFileNameWithoutExtension(f).StartsWith(sourceFileName, StringComparison.InvariantCultureIgnoreCase)).ToList();
            var filteredFilenames = new List <string>();
            var hasNfo            = false;

            foreach (var matchingFilename in matchingFilenames)
            {
                // Filter out duplicate NFO files
                if (matchingFilename.EndsWith(".nfo", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (hasNfo)
                    {
                        continue;
                    }

                    hasNfo = true;
                }

                filteredFilenames.Add(matchingFilename);
            }

            foreach (var matchingFilename in filteredFilenames)
            {
                var matchingExtension = wantedExtensions.FirstOrDefault(e => matchingFilename.EndsWith(e));

                if (matchingExtension == null)
                {
                    continue;
                }

                try
                {
                    foreach (var extraFileManager in _extraFileManagers)
                    {
                        var extension = Path.GetExtension(matchingFilename);
                        var extraFile = extraFileManager.Import(localBook.Author, bookFile, matchingFilename, extension, isReadOnly);

                        if (extraFile != null)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Warn(ex, "Failed to import extra file: {0}", matchingFilename);
                }
            }
        }
Example #30
0
 protected override IEnumerable <string> GetLogFiles()
 {
     return(_diskProvider.GetFiles(_appFolderInfo.GetLogFolder(), SearchOption.TopDirectoryOnly));
 }