DeleteTranscodeFileTask.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Model.Globalization;
  9. using MediaBrowser.Model.IO;
  10. using MediaBrowser.Model.Tasks;
  11. using Microsoft.Extensions.Logging;
  12. namespace Emby.Server.Implementations.ScheduledTasks.Tasks
  13. {
  14. /// <summary>
  15. /// Deletes all transcoding temp files.
  16. /// </summary>
  17. public class DeleteTranscodeFileTask : IScheduledTask, IConfigurableScheduledTask
  18. {
  19. private readonly ILogger<DeleteTranscodeFileTask> _logger;
  20. private readonly IConfigurationManager _configurationManager;
  21. private readonly IFileSystem _fileSystem;
  22. private readonly ILocalizationManager _localization;
  23. /// <summary>
  24. /// Initializes a new instance of the <see cref="DeleteTranscodeFileTask"/> class.
  25. /// </summary>
  26. /// <param name="logger">Instance of the <see cref="ILogger{DeleteTranscodeFileTask}"/> interface.</param>
  27. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  28. /// <param name="configurationManager">Instance of the <see cref="IConfigurationManager"/> interface.</param>
  29. /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  30. public DeleteTranscodeFileTask(
  31. ILogger<DeleteTranscodeFileTask> logger,
  32. IFileSystem fileSystem,
  33. IConfigurationManager configurationManager,
  34. ILocalizationManager localization)
  35. {
  36. _logger = logger;
  37. _fileSystem = fileSystem;
  38. _configurationManager = configurationManager;
  39. _localization = localization;
  40. }
  41. /// <inheritdoc />
  42. public string Name => _localization.GetLocalizedString("TaskCleanTranscode");
  43. /// <inheritdoc />
  44. public string Description => _localization.GetLocalizedString("TaskCleanTranscodeDescription");
  45. /// <inheritdoc />
  46. public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
  47. /// <inheritdoc />
  48. public string Key => "DeleteTranscodeFiles";
  49. /// <inheritdoc />
  50. public bool IsHidden => false;
  51. /// <inheritdoc />
  52. public bool IsEnabled => true;
  53. /// <inheritdoc />
  54. public bool IsLogged => true;
  55. /// <summary>
  56. /// Creates the triggers that define when the task will run.
  57. /// </summary>
  58. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  59. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  60. {
  61. return new[]
  62. {
  63. new TaskTriggerInfo
  64. {
  65. Type = TaskTriggerInfo.TriggerInterval,
  66. IntervalTicks = TimeSpan.FromHours(24).Ticks
  67. }
  68. };
  69. }
  70. /// <inheritdoc />
  71. public Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
  72. {
  73. var minDateModified = DateTime.UtcNow.AddDays(-1);
  74. progress.Report(50);
  75. DeleteTempFilesFromDirectory(_configurationManager.GetTranscodePath(), minDateModified, progress, cancellationToken);
  76. return Task.CompletedTask;
  77. }
  78. /// <summary>
  79. /// Deletes the transcoded temp files from directory with a last write time less than a given date.
  80. /// </summary>
  81. /// <param name="directory">The directory.</param>
  82. /// <param name="minDateModified">The min date modified.</param>
  83. /// <param name="progress">The progress.</param>
  84. /// <param name="cancellationToken">The task cancellation token.</param>
  85. private void DeleteTempFilesFromDirectory(string directory, DateTime minDateModified, IProgress<double> progress, CancellationToken cancellationToken)
  86. {
  87. var filesToDelete = _fileSystem.GetFiles(directory, true)
  88. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  89. .ToList();
  90. var index = 0;
  91. foreach (var file in filesToDelete)
  92. {
  93. double percent = index;
  94. percent /= filesToDelete.Count;
  95. progress.Report(100 * percent);
  96. cancellationToken.ThrowIfCancellationRequested();
  97. DeleteFile(file.FullName);
  98. index++;
  99. }
  100. DeleteEmptyFolders(directory);
  101. progress.Report(100);
  102. }
  103. private void DeleteEmptyFolders(string parent)
  104. {
  105. foreach (var directory in _fileSystem.GetDirectoryPaths(parent))
  106. {
  107. DeleteEmptyFolders(directory);
  108. if (!_fileSystem.GetFileSystemEntryPaths(directory).Any())
  109. {
  110. try
  111. {
  112. Directory.Delete(directory, false);
  113. }
  114. catch (UnauthorizedAccessException ex)
  115. {
  116. _logger.LogError(ex, "Error deleting directory {Path}", directory);
  117. }
  118. catch (IOException ex)
  119. {
  120. _logger.LogError(ex, "Error deleting directory {Path}", directory);
  121. }
  122. }
  123. }
  124. }
  125. private void DeleteFile(string path)
  126. {
  127. try
  128. {
  129. _fileSystem.DeleteFile(path);
  130. }
  131. catch (UnauthorizedAccessException ex)
  132. {
  133. _logger.LogError(ex, "Error deleting file {Path}", path);
  134. }
  135. catch (IOException ex)
  136. {
  137. _logger.LogError(ex, "Error deleting file {Path}", path);
  138. }
  139. }
  140. }
  141. }