DeleteCacheFileTask.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 old cache files.
  16. /// </summary>
  17. public class DeleteCacheFileTask : IScheduledTask, IConfigurableScheduledTask
  18. {
  19. /// <summary>
  20. /// Gets or sets the application paths.
  21. /// </summary>
  22. /// <value>The application paths.</value>
  23. private readonly IApplicationPaths _applicationPaths;
  24. private readonly ILogger<DeleteCacheFileTask> _logger;
  25. private readonly IFileSystem _fileSystem;
  26. private readonly ILocalizationManager _localization;
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="DeleteCacheFileTask" /> class.
  29. /// </summary>
  30. /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
  31. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  32. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  33. /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
  34. public DeleteCacheFileTask(
  35. IApplicationPaths appPaths,
  36. ILogger<DeleteCacheFileTask> logger,
  37. IFileSystem fileSystem,
  38. ILocalizationManager localization)
  39. {
  40. _applicationPaths = appPaths;
  41. _logger = logger;
  42. _fileSystem = fileSystem;
  43. _localization = localization;
  44. }
  45. /// <inheritdoc />
  46. public string Name => _localization.GetLocalizedString("TaskCleanCache");
  47. /// <inheritdoc />
  48. public string Description => _localization.GetLocalizedString("TaskCleanCacheDescription");
  49. /// <inheritdoc />
  50. public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
  51. /// <inheritdoc />
  52. public string Key => "DeleteCacheFiles";
  53. /// <inheritdoc />
  54. public bool IsHidden => false;
  55. /// <inheritdoc />
  56. public bool IsEnabled => true;
  57. /// <inheritdoc />
  58. public bool IsLogged => true;
  59. /// <summary>
  60. /// Creates the triggers that define when the task will run.
  61. /// </summary>
  62. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  63. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  64. {
  65. return new[]
  66. {
  67. // Every so often
  68. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
  69. };
  70. }
  71. /// <summary>
  72. /// Returns the task to be executed.
  73. /// </summary>
  74. /// <param name="cancellationToken">The cancellation token.</param>
  75. /// <param name="progress">The progress.</param>
  76. /// <returns>Task.</returns>
  77. public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  78. {
  79. var minDateModified = DateTime.UtcNow.AddDays(-30);
  80. try
  81. {
  82. DeleteCacheFilesFromDirectory(cancellationToken, _applicationPaths.CachePath, minDateModified, progress);
  83. }
  84. catch (DirectoryNotFoundException)
  85. {
  86. // No biggie here. Nothing to delete
  87. }
  88. progress.Report(90);
  89. minDateModified = DateTime.UtcNow.AddDays(-1);
  90. try
  91. {
  92. DeleteCacheFilesFromDirectory(cancellationToken, _applicationPaths.TempDirectory, minDateModified, progress);
  93. }
  94. catch (DirectoryNotFoundException)
  95. {
  96. // No biggie here. Nothing to delete
  97. }
  98. return Task.CompletedTask;
  99. }
  100. /// <summary>
  101. /// Deletes the cache files from directory with a last write time less than a given date.
  102. /// </summary>
  103. /// <param name="cancellationToken">The task cancellation token.</param>
  104. /// <param name="directory">The directory.</param>
  105. /// <param name="minDateModified">The min date modified.</param>
  106. /// <param name="progress">The progress.</param>
  107. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  108. {
  109. var filesToDelete = _fileSystem.GetFiles(directory, true)
  110. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  111. .ToList();
  112. var index = 0;
  113. foreach (var file in filesToDelete)
  114. {
  115. double percent = index;
  116. percent /= filesToDelete.Count;
  117. progress.Report(100 * percent);
  118. cancellationToken.ThrowIfCancellationRequested();
  119. DeleteFile(file.FullName);
  120. index++;
  121. }
  122. DeleteEmptyFolders(directory);
  123. progress.Report(100);
  124. }
  125. private void DeleteEmptyFolders(string parent)
  126. {
  127. foreach (var directory in _fileSystem.GetDirectoryPaths(parent))
  128. {
  129. DeleteEmptyFolders(directory);
  130. if (!_fileSystem.GetFileSystemEntryPaths(directory).Any())
  131. {
  132. try
  133. {
  134. Directory.Delete(directory, false);
  135. }
  136. catch (UnauthorizedAccessException ex)
  137. {
  138. _logger.LogError(ex, "Error deleting directory {Path}", directory);
  139. }
  140. catch (IOException ex)
  141. {
  142. _logger.LogError(ex, "Error deleting directory {Path}", directory);
  143. }
  144. }
  145. }
  146. }
  147. private void DeleteFile(string path)
  148. {
  149. try
  150. {
  151. _fileSystem.DeleteFile(path);
  152. }
  153. catch (UnauthorizedAccessException ex)
  154. {
  155. _logger.LogError(ex, "Error deleting file {Path}", path);
  156. }
  157. catch (IOException ex)
  158. {
  159. _logger.LogError(ex, "Error deleting file {Path}", path);
  160. }
  161. }
  162. }
  163. }