DeleteCacheFileTask.cs 6.3 KB

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