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"); }
public void DeleteFile(string path) { logger.Debug("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."); if (!OsInfo.IsMono) { logger.Debug(_diskProvider.GetFileAttributes(path)); } _diskProvider.DeleteFile(path); logger.Debug("File has been permanently deleted: {0}", path); } else { var destination = Path.Combine(recyclingBin, new FileInfo(path).Name); logger.Debug("Moving '{0}' to '{1}'", path, destination); _diskProvider.MoveFile(path, destination); _diskProvider.FileSetLastWriteTimeUtc(destination, DateTime.UtcNow); logger.Debug("File has been moved to the recycling bin: {0}", destination); } }
private void MoveSqliteDatabase(string source, string destination) { _logger.Info("Moving {0}* to {1}*", source, destination); var dbSuffixes = new[] { "", "-shm", "-wal", "-journal" }; foreach (var suffix in dbSuffixes) { var sourceFile = source + suffix; var destFile = destination + suffix; if (_diskProvider.FileExists(destFile)) { _diskProvider.DeleteFile(destFile); } if (_diskProvider.FileExists(sourceFile)) { _diskProvider.CopyFile(sourceFile, destFile); } } foreach (var suffix in dbSuffixes) { var sourceFile = source + suffix; if (_diskProvider.FileExists(sourceFile)) { _diskProvider.DeleteFile(sourceFile); } } }
public void DeleteFile(string path, string subfolder = "") { _logger.Debug("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); if (OsInfo.IsWindows) { _logger.Debug(_diskProvider.GetFileAttributes(path)); } _diskProvider.DeleteFile(path); _logger.Debug("File has been permanently deleted: {0}", path); } else { var fileInfo = new FileInfo(path); var destinationFolder = Path.Combine(recyclingBin, subfolder); var destination = Path.Combine(destinationFolder, fileInfo.Name); _diskProvider.CreateFolder(destinationFolder); var index = 1; while (_diskProvider.FileExists(destination)) { index++; if (fileInfo.Extension.IsNullOrWhiteSpace()) { destination = Path.Combine(destinationFolder, fileInfo.Name + "_" + index); } else { destination = Path.Combine(destinationFolder, Path.GetFileNameWithoutExtension(fileInfo.Name) + "_" + index + fileInfo.Extension); } } try { _logger.Debug("Moving '{0}' to '{1}'", path, destination); _diskTransferService.TransferFile(path, destination, TransferMode.Move); } catch (IOException e) { _logger.Error(e, "Unable to move '{0}' to the recycling bin: '{1}'", path, destination); throw; } //TODO: Better fix than this for non-Windows? if (OsInfo.IsWindows) { _diskProvider.FileSetLastWriteTime(destination, DateTime.UtcNow); } _logger.Debug("File has been moved to the recycling bin: {0}", destination); } }
public void Handle(ApplicationStartingEvent message) { // Check if we have to do an application update on startup try { var updateMarker = Path.Combine(_appFolderInfo.AppDataFolder, "update_required"); if (!_diskProvider.FileExists(updateMarker)) { return; } _logger.Debug("Post-install update check requested"); // Don't do a prestartup update check unless BuiltIn update is enabled if (!_configFileProvider.UpdateAutomatically || _configFileProvider.UpdateMechanism != UpdateMechanism.BuiltIn || _deploymentInfoProvider.IsExternalUpdateMechanism) { _logger.Debug("Built-in updater disabled, skipping post-install update check"); return; } var latestAvailable = _checkUpdateService.AvailableUpdate(); if (latestAvailable == null) { _logger.Debug("No post-install update available"); _diskProvider.DeleteFile(updateMarker); return; } _logger.Info("Installing post-install update from {0} to {1}", BuildInfo.Version, latestAvailable.Version); _diskProvider.DeleteFile(updateMarker); var installing = InstallUpdate(latestAvailable); if (installing) { _logger.Debug("Install in progress, giving installer 30 seconds."); var watch = Stopwatch.StartNew(); while (watch.Elapsed < TimeSpan.FromSeconds(30)) { Thread.Sleep(1000); } _logger.Error("Post-install update not completed within 30 seconds. Attempting to continue normal operation."); } else { _logger.Debug("Post-install update cancelled for unknown reason. Attempting to continue normal operation."); } } catch (Exception ex) { _logger.Error(ex, "Failed to perform the post-install update check. Attempting to continue normal operation."); } }
public void Restore() { var dbRestorePath = _appFolderInfo.GetDatabaseRestore(); if (!_diskProvider.FileExists(dbRestorePath)) { return; } try { Logger.Info("Restoring Database"); var dbPath = _appFolderInfo.GetDatabase(); _diskProvider.DeleteFile(dbPath + "-shm"); _diskProvider.DeleteFile(dbPath + "-wal"); _diskProvider.DeleteFile(dbPath + "-journal"); _diskProvider.DeleteFile(dbPath); _diskProvider.MoveFile(dbRestorePath, dbPath); } catch (Exception e) { Logger.Error(e, "Failed to restore database"); throw; } }
private void CreateLog(string connectionString, MigrationContext migrationContext) { try { _migrationController.Migrate(connectionString, migrationContext); } catch (SQLiteException e) { var fileName = _connectionStringFactory.GetDatabasePath(connectionString); Logger.Error(e, "Logging database is corrupt, attempting to recreate it automatically"); try { _diskProvider.DeleteFile(fileName + "-shm"); _diskProvider.DeleteFile(fileName + "-wal"); _diskProvider.DeleteFile(fileName + "-journal"); _diskProvider.DeleteFile(fileName); } catch (Exception) { Logger.Error("Unable to recreate logging database automatically. It will need to be removed manually."); } _migrationController.Migrate(connectionString, migrationContext); } catch (Exception e) { throw new ProwlarrStartupException(e, "Error creating log database"); } }
private void DeleteBackup(int id) { var backup = GetBackup(id); var path = GetBackupPath(backup); if (!_diskProvider.FileExists(path)) { throw new NotFoundException(); } _diskProvider.DeleteFile(path); }
public void DeleteFile(string path) { logger.Debug("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."); if (OsInfo.IsWindows) { logger.Debug(_diskProvider.GetFileAttributes(path)); } _diskProvider.DeleteFile(path); logger.Debug("File has been permanently deleted: {0}", path); } else { var fileInfo = new FileInfo(path); var destination = Path.Combine(recyclingBin, fileInfo.Name); var index = 1; while (_diskProvider.FileExists(destination)) { index++; if (fileInfo.Extension.IsNullOrWhiteSpace()) { destination = Path.Combine(recyclingBin, fileInfo.Name + "_" + index); } else { destination = Path.Combine(recyclingBin, Path.GetFileNameWithoutExtension(fileInfo.Name) + "_" + index + fileInfo.Extension); } } logger.Debug("Moving '{0}' to '{1}'", path, destination); _diskProvider.MoveFile(path, destination, true); //TODO: Better fix than this for non-Windows? if (OsInfo.IsWindows) { _diskProvider.FileSetLastWriteTimeUtc(destination, DateTime.UtcNow); } logger.Debug("File has been moved to the recycling bin: {0}", destination); } }
private void PerformTest(string folder) { var testPath = Path.Combine(folder, "drone_test.txt"); _diskProvider.WriteAllText(testPath, DateTime.Now.ToString()); _diskProvider.DeleteFile(testPath); }
private void RemovePidFile() { if (OsInfo.IsNotWindows) { _diskProvider.DeleteFile(Path.Combine(_appFolderInfo.AppDataFolder, "sonarr.pid")); } }
public void HandleAsync(EpisodeFileDeletedEvent message) { var episodeFile = message.EpisodeFile; var series = _seriesService.GetSeries(message.EpisodeFile.SeriesId); foreach (var extra in _repository.GetFilesByEpisodeFile(episodeFile.Id)) { var path = Path.Combine(series.Path, extra.RelativePath); if (_diskProvider.FileExists(path)) { if (PermanentlyDelete) { _diskProvider.DeleteFile(path); } else { // Send extra files to the recycling bin so they can be recovered if necessary _recycleBinProvider.DeleteFile(path); } } } _logger.Debug("Deleting Extra from database for episode file: {0}", episodeFile); _repository.DeleteForEpisodeFile(episodeFile.Id); }
private void RemoveCompleted(TrackedDownload trackedDownload, IDownloadClient downloadClient) { if (trackedDownload.State == TrackedDownloadState.Imported && !trackedDownload.DownloadItem.IsReadOnly) { try { _logger.Debug("[{0}] Removing completed download from history.", trackedDownload.DownloadItem.Title); downloadClient.RemoveItem(trackedDownload.DownloadItem.DownloadClientId); if (_diskProvider.FolderExists(trackedDownload.DownloadItem.OutputPath)) { _logger.Debug("Removing completed download directory: {0}", trackedDownload.DownloadItem.OutputPath); _diskProvider.DeleteFolder(trackedDownload.DownloadItem.OutputPath, true); } else if (_diskProvider.FileExists(trackedDownload.DownloadItem.OutputPath)) { _logger.Debug("Removing completed download file: {0}", trackedDownload.DownloadItem.OutputPath); _diskProvider.DeleteFile(trackedDownload.DownloadItem.OutputPath); } trackedDownload.State = TrackedDownloadState.Removed; } catch (NotSupportedException) { UpdateStatusMessage(trackedDownload, LogLevel.Debug, "Removing item not supported by your download client."); } } }
public override HealthCheck Check() { var droneFactoryFolder = _configService.DownloadedEpisodesFolder; if (droneFactoryFolder.IsNullOrWhiteSpace()) { return(new HealthCheck(GetType(), HealthCheckResult.Warning, "Drone factory folder is not configured")); } if (!_diskProvider.FolderExists(droneFactoryFolder)) { return(new HealthCheck(GetType(), HealthCheckResult.Error, "Drone factory folder does not exist")); } try { var testPath = Path.Combine(droneFactoryFolder, "drone_test.txt"); _diskProvider.WriteAllText(testPath, DateTime.Now.ToString()); _diskProvider.DeleteFile(testPath); } catch (Exception) { return(new HealthCheck(GetType(), HealthCheckResult.Error, "Unable to write to drone factory folder")); } //Todo: Unable to import one or more files/folders from return(new HealthCheck(GetType())); }
public void Resize(string source, string destination, int height) { try { if (!_diskProvider.CanUseGDIPlus()) { throw new Exception("Can't resize without libgdiplus."); } using (var sourceStream = _diskProvider.OpenReadStream(source)) { using (var outputStream = _diskProvider.OpenWriteStream(destination)) { var settings = new Instructions(); settings.Height = height; var job = new ImageJob(sourceStream, outputStream, settings); ImageBuilder.Current.Build(job); } } } catch { if (_diskProvider.FileExists(destination)) { _diskProvider.DeleteFile(destination); } throw; } }
public void Resize(string source, string destination, int height) { if (!_enabled) { return; } try { using (var image = Image.Load(source)) { image.Mutate(x => x.Resize(0, height)); image.Save(destination); } } catch { if (_diskProvider.FileExists(destination)) { _diskProvider.DeleteFile(destination); } throw; } }
public void Resize(string source, string destination, int height) { try { GdiPlusInterop.CheckGdiPlus(); using (var sourceStream = _diskProvider.OpenReadStream(source)) { using (var outputStream = _diskProvider.OpenWriteStream(destination)) { var settings = new Instructions(); settings.Height = height; var job = new ImageJob(sourceStream, outputStream, settings); ImageBuilder.Current.Build(job); } } } catch { if (_diskProvider.FileExists(destination)) { _diskProvider.DeleteFile(destination); } throw; } }
public override HealthCheck Check() { if (OsInfo.IsWindows) { try { var testPath = Path.Combine(_appFolderInfo.StartUpFolder, "drone_test.txt"); _diskProvider.WriteAllText(testPath, DateTime.Now.ToString()); _diskProvider.DeleteFile(testPath); } catch (Exception) { return(new HealthCheck(GetType(), HealthCheckResult.Error, "Unable to update, running from write-protected folder")); } } if (BuildInfo.BuildDateTime < DateTime.UtcNow.AddDays(-14)) { if (_checkUpdateService.AvailableUpdate() != null) { return(new HealthCheck(GetType(), HealthCheckResult.Warning, "New update is available")); } } return(new HealthCheck(GetType())); }
protected ValidationFailure TestFolder(String folder, String propertyName, Boolean mustBeWritable = true) { if (!_diskProvider.FolderExists(folder)) { return(new NzbDroneValidationFailure(propertyName, "Folder does not exist") { DetailedDescription = "The folder you specified does not exist or is inaccessible. Please verify the folder permissions for the user account that is used to execute NzbDrone." }); } if (mustBeWritable) { try { var testPath = Path.Combine(folder, "drone_test.txt"); _diskProvider.WriteAllText(testPath, DateTime.Now.ToString()); _diskProvider.DeleteFile(testPath); } catch (Exception ex) { _logger.ErrorException(ex.Message, ex); return(new NzbDroneValidationFailure(propertyName, "Unable to write to folder") { DetailedDescription = "The folder you specified is not writable. Please verify the folder permissions for the user account that is used to execute NzbDrone." }); } } return(null); }
public void Execute(DeleteLogFilesCommand message) { var logFiles = _diskProvider.GetFiles(_appFolderInfo.GetLogFolder(), SearchOption.TopDirectoryOnly); foreach (var logFile in logFiles) { _diskProvider.DeleteFile(logFile); } }
protected virtual void DeleteItemData(string downloadId) { if (downloadId.IsNullOrWhiteSpace()) { return; } var item = GetItems().FirstOrDefault(v => v.DownloadId == downloadId); if (item == null) { _logger.Trace("DownloadItem {0} in {1} history not found, skipping delete data.", downloadId, Name); return; } if (item.OutputPath.IsEmpty) { _logger.Trace("[{0}] Doesn't have an outputPath, skipping delete data.", item.Title); return; } try { if (_diskProvider.FolderExists(item.OutputPath.FullPath)) { _logger.Debug("[{0}] Deleting folder '{1}'.", item.Title, item.OutputPath); _diskProvider.DeleteFolder(item.OutputPath.FullPath, true); } else if (_diskProvider.FileExists(item.OutputPath.FullPath)) { _logger.Debug("[{0}] Deleting file '{1}'.", item.Title, item.OutputPath); _diskProvider.DeleteFile(item.OutputPath.FullPath); } else { _logger.Trace("[{0}] File or folder '{1}' doesn't exist, skipping cleanup.", item.Title, item.OutputPath); } } catch (Exception ex) { _logger.Warn(ex, string.Format("[{0}] Error occurred while trying to delete data from '{1}'.", item.Title, item.OutputPath)); } }
private void CleanupOldBackups(BackupType backupType) { _logger.Debug("Cleaning up old backup files"); var files = GetBackupFiles(GetBackupFolder(backupType)); foreach (var file in files) { var lastWriteTime = _diskProvider.FileGetLastWrite(file); if (lastWriteTime.AddDays(28) < DateTime.UtcNow) { _logger.Debug("Deleting old backup file: {0}", file); _diskProvider.DeleteFile(file); } } _logger.Debug("Finished cleaning up old backup files"); }
public void HandleAsync(EpisodeFileDeletedEvent message) { var episodeFile = message.EpisodeFile; var series = _seriesService.GetSeries(message.EpisodeFile.SeriesId); foreach (var metadata in _repository.GetFilesByEpisodeFile(episodeFile.Id)) { var path = Path.Combine(series.Path, metadata.RelativePath); if (_diskProvider.FileExists(path)) { _diskProvider.DeleteFile(path); } } _logger.Debug("Deleting Metadata from database for episode file: {0}", episodeFile); _repository.DeleteForEpisodeFile(episodeFile.Id); }
public bool AlreadyExists(string url, string path) { if (!_diskProvider.FileExists(path)) { return(false); } if (!_diskProvider.IsValidGDIPlusImage(path)) { _diskProvider.DeleteFile(path); return(false); } var headers = _httpClient.Head(new HttpRequest(url)).Headers; var fileSize = _diskProvider.GetFileSize(path); return(fileSize == headers.ContentLength); }
private MetadataFile GetMetadataFile(Series series, List <MetadataFile> existingMetadataFiles, Func <MetadataFile, bool> predicate) { var matchingMetadataFiles = existingMetadataFiles.Where(predicate).ToList(); if (matchingMetadataFiles.Empty()) { return(null); } //Remove duplicate metadata files from DB and disk foreach (var file in matchingMetadataFiles.Skip(1)) { var path = Path.Combine(series.Path, file.RelativePath); _logger.Debug("Removing duplicate Metadata file: {0}", path); _diskProvider.DeleteFile(path); _metadataFileService.Delete(file.Id); } return(matchingMetadataFiles.First()); }
public void Handle(EpisodeFileDeletedEvent message) { var episodeFile = message.EpisodeFile; if (message.Reason == DeleteMediaFileReason.NoLinkedEpisodes) { _logger.Debug("Removing episode file from DB as part of cleanup routine, not deleting extra files from disk."); } else { var series = _seriesService.GetSeries(message.EpisodeFile.SeriesId); foreach (var extra in _repository.GetFilesByEpisodeFile(episodeFile.Id)) { var path = Path.Combine(series.Path, extra.RelativePath); if (_diskProvider.FileExists(path)) { if (PermanentlyDelete) { _diskProvider.DeleteFile(path); } else { // Send extra files to the recycling bin so they can be recovered if necessary var subfolder = _diskProvider.GetParentFolder(series.Path).GetRelativePath(_diskProvider.GetParentFolder(path)); _recycleBinProvider.DeleteFile(path, subfolder); } } } } _logger.Debug("Deleting Extra from database for episode file: {0}", episodeFile); _repository.DeleteForEpisodeFile(episodeFile.Id); }
protected virtual void DeleteItemData(DownloadClientItem item) { if (item == null) { return; } if (item.OutputPath.IsEmpty) { _logger.Trace("[{0}] Doesn't have an outputPath, skipping delete data.", item.Title); return; } try { if (_diskProvider.FolderExists(item.OutputPath.FullPath)) { _logger.Debug("[{0}] Deleting folder '{1}'.", item.Title, item.OutputPath); _diskProvider.DeleteFolder(item.OutputPath.FullPath, true); } else if (_diskProvider.FileExists(item.OutputPath.FullPath)) { _logger.Debug("[{0}] Deleting file '{1}'.", item.Title, item.OutputPath); _diskProvider.DeleteFile(item.OutputPath.FullPath); } else { _logger.Trace("[{0}] File or folder '{1}' doesn't exist, skipping cleanup.", item.Title, item.OutputPath); } } catch (Exception ex) { _logger.Warn(ex, string.Format("[{0}] Error occurred while trying to delete data from '{1}'.", item.Title, item.OutputPath)); } }
public IDatabase Create(MigrationContext migrationContext) { string connectionString; switch (migrationContext.MigrationType) { case MigrationType.Main: { connectionString = _connectionStringFactory.MainDbConnectionString; break; } case MigrationType.Log: { connectionString = _connectionStringFactory.LogDbConnectionString; break; } default: { throw new ArgumentException("Invalid MigrationType"); } } try { _migrationController.Migrate(connectionString, migrationContext); } catch (SQLiteException ex) { var fileName = _connectionStringFactory.GetDatabasePath(connectionString); if (migrationContext.MigrationType == MigrationType.Log) { Logger.Error(ex, "Logging database is corrupt, attempting to recreate it automatically"); try { _diskProvider.DeleteFile(fileName + "-shm"); _diskProvider.DeleteFile(fileName + "-wal"); _diskProvider.DeleteFile(fileName + "-journal"); _diskProvider.DeleteFile(fileName); } catch (Exception) { Logger.Error("Unable to recreate logging database automatically. It will need to be removed manually."); } _migrationController.Migrate(connectionString, migrationContext); } else { if (OsInfo.IsOsx) { throw new CorruptDatabaseException("Database file: {0} is corrupt, restore from backup if available. See: https://github.com/Radarr/Radarr/wiki/FAQ#i-use-radarr-on-a-mac-and-it-suddenly-stopped-working-what-happened", ex, fileName); } throw new CorruptDatabaseException("Database file: {0} is corrupt, restore from backup if available. See: https://github.com/Radarr/Radarr/wiki/FAQ#i-am-getting-an-error-database-disk-image-is-malformed", ex, fileName); } } catch (Exception e) { throw new RadarrStartupException(e, "Error creating main or log database"); } var db = new Database(migrationContext.MigrationType.ToString(), () => { var dataMapper = new DataMapper(SQLiteFactory.Instance, connectionString) { SqlMode = SqlModes.Text, }; return(dataMapper); }); return(db); }
private void DeleteMetadata(int id, string path) { _metaFileService.Delete(id); _diskProvider.DeleteFile(path); }
public int MirrorFolder(string sourcePath, string targetPath) { var filesCopied = 0; Ensure.That(sourcePath, () => sourcePath).IsValidPath(); Ensure.That(targetPath, () => targetPath).IsValidPath(); _logger.Debug("Mirror [{0}] > [{1}]", sourcePath, targetPath); if (!_diskProvider.FolderExists(targetPath)) { _diskProvider.CreateFolder(targetPath); } var sourceFolders = _diskProvider.GetDirectoryInfos(sourcePath); var targetFolders = _diskProvider.GetDirectoryInfos(targetPath); foreach (var subDir in targetFolders.Where(v => !sourceFolders.Any(d => d.Name == v.Name))) { _diskProvider.DeleteFolder(subDir.FullName, true); } foreach (var subDir in sourceFolders) { filesCopied += MirrorFolder(subDir.FullName, Path.Combine(targetPath, subDir.Name)); } var sourceFiles = _diskProvider.GetFileInfos(sourcePath); var targetFiles = _diskProvider.GetFileInfos(targetPath); foreach (var targetFile in targetFiles.Where(v => !sourceFiles.Any(d => d.Name == v.Name))) { _diskProvider.DeleteFile(targetFile.FullName); } foreach (var sourceFile in sourceFiles) { var targetFile = Path.Combine(targetPath, sourceFile.Name); if (CompareFiles(sourceFile.FullName, targetFile)) { continue; } TransferFile(sourceFile.FullName, targetFile, TransferMode.Copy, true, true); filesCopied++; } return(filesCopied); }