DeleteTranscodeFileTask.cs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. /// <summary>
  71. /// Returns the task to be executed.
  72. /// </summary>
  73. /// <param name="cancellationToken">The cancellation token.</param>
  74. /// <param name="progress">The progress.</param>
  75. /// <returns>Task.</returns>
  76. public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  77. {
  78. var minDateModified = DateTime.UtcNow.AddDays(-1);
  79. progress.Report(50);
  80. DeleteTempFilesFromDirectory(cancellationToken, _configurationManager.GetTranscodePath(), minDateModified, progress);
  81. return Task.CompletedTask;
  82. }
  83. /// <summary>
  84. /// Deletes the transcoded temp files from directory with a last write time less than a given date.
  85. /// </summary>
  86. /// <param name="cancellationToken">The task cancellation token.</param>
  87. /// <param name="directory">The directory.</param>
  88. /// <param name="minDateModified">The min date modified.</param>
  89. /// <param name="progress">The progress.</param>
  90. private void DeleteTempFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  91. {
  92. var filesToDelete = _fileSystem.GetFiles(directory, true)
  93. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  94. .ToList();
  95. var index = 0;
  96. foreach (var file in filesToDelete)
  97. {
  98. double percent = index;
  99. percent /= filesToDelete.Count;
  100. progress.Report(100 * percent);
  101. cancellationToken.ThrowIfCancellationRequested();
  102. DeleteFile(file.FullName);
  103. index++;
  104. }
  105. DeleteEmptyFolders(directory);
  106. progress.Report(100);
  107. }
  108. private void DeleteEmptyFolders(string parent)
  109. {
  110. foreach (var directory in _fileSystem.GetDirectoryPaths(parent))
  111. {
  112. DeleteEmptyFolders(directory);
  113. if (!_fileSystem.GetFileSystemEntryPaths(directory).Any())
  114. {
  115. try
  116. {
  117. Directory.Delete(directory, false);
  118. }
  119. catch (UnauthorizedAccessException ex)
  120. {
  121. _logger.LogError(ex, "Error deleting directory {path}", directory);
  122. }
  123. catch (IOException ex)
  124. {
  125. _logger.LogError(ex, "Error deleting directory {path}", directory);
  126. }
  127. }
  128. }
  129. }
  130. private void DeleteFile(string path)
  131. {
  132. try
  133. {
  134. _fileSystem.DeleteFile(path);
  135. }
  136. catch (UnauthorizedAccessException ex)
  137. {
  138. _logger.LogError(ex, "Error deleting file {path}", path);
  139. }
  140. catch (IOException ex)
  141. {
  142. _logger.LogError(ex, "Error deleting file {path}", path);
  143. }
  144. }
  145. }
  146. }