DeleteCacheFileTask.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. public DeleteCacheFileTask(
  31. IApplicationPaths appPaths,
  32. ILogger<DeleteCacheFileTask> logger,
  33. IFileSystem fileSystem,
  34. ILocalizationManager localization)
  35. {
  36. _applicationPaths = appPaths;
  37. _logger = logger;
  38. _fileSystem = fileSystem;
  39. _localization = localization;
  40. }
  41. /// <inheritdoc />
  42. public string Name => _localization.GetLocalizedString("TaskCleanCache");
  43. /// <inheritdoc />
  44. public string Description => _localization.GetLocalizedString("TaskCleanCacheDescription");
  45. /// <inheritdoc />
  46. public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
  47. /// <inheritdoc />
  48. public string Key => "DeleteCacheFiles";
  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. // Every so often
  64. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks }
  65. };
  66. }
  67. /// <summary>
  68. /// Returns the task to be executed.
  69. /// </summary>
  70. /// <param name="cancellationToken">The cancellation token.</param>
  71. /// <param name="progress">The progress.</param>
  72. /// <returns>Task.</returns>
  73. public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  74. {
  75. var minDateModified = DateTime.UtcNow.AddDays(-30);
  76. try
  77. {
  78. DeleteCacheFilesFromDirectory(cancellationToken, _applicationPaths.CachePath, minDateModified, progress);
  79. }
  80. catch (DirectoryNotFoundException)
  81. {
  82. // No biggie here. Nothing to delete
  83. }
  84. progress.Report(90);
  85. minDateModified = DateTime.UtcNow.AddDays(-1);
  86. try
  87. {
  88. DeleteCacheFilesFromDirectory(cancellationToken, _applicationPaths.TempDirectory, minDateModified, progress);
  89. }
  90. catch (DirectoryNotFoundException)
  91. {
  92. // No biggie here. Nothing to delete
  93. }
  94. return Task.CompletedTask;
  95. }
  96. /// <summary>
  97. /// Deletes the cache files from directory with a last write time less than a given date.
  98. /// </summary>
  99. /// <param name="cancellationToken">The task cancellation token.</param>
  100. /// <param name="directory">The directory.</param>
  101. /// <param name="minDateModified">The min date modified.</param>
  102. /// <param name="progress">The progress.</param>
  103. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  104. {
  105. var filesToDelete = _fileSystem.GetFiles(directory, true)
  106. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  107. .ToList();
  108. var index = 0;
  109. foreach (var file in filesToDelete)
  110. {
  111. double percent = index;
  112. percent /= filesToDelete.Count;
  113. progress.Report(100 * percent);
  114. cancellationToken.ThrowIfCancellationRequested();
  115. DeleteFile(file.FullName);
  116. index++;
  117. }
  118. DeleteEmptyFolders(directory);
  119. progress.Report(100);
  120. }
  121. private void DeleteEmptyFolders(string parent)
  122. {
  123. foreach (var directory in _fileSystem.GetDirectoryPaths(parent))
  124. {
  125. DeleteEmptyFolders(directory);
  126. if (!_fileSystem.GetFileSystemEntryPaths(directory).Any())
  127. {
  128. try
  129. {
  130. Directory.Delete(directory, false);
  131. }
  132. catch (UnauthorizedAccessException ex)
  133. {
  134. _logger.LogError(ex, "Error deleting directory {path}", directory);
  135. }
  136. catch (IOException ex)
  137. {
  138. _logger.LogError(ex, "Error deleting directory {path}", directory);
  139. }
  140. }
  141. }
  142. }
  143. private void DeleteFile(string path)
  144. {
  145. try
  146. {
  147. _fileSystem.DeleteFile(path);
  148. }
  149. catch (UnauthorizedAccessException ex)
  150. {
  151. _logger.LogError(ex, "Error deleting file {path}", path);
  152. }
  153. catch (IOException ex)
  154. {
  155. _logger.LogError(ex, "Error deleting file {path}", path);
  156. }
  157. }
  158. }
  159. }