DeleteCacheFileTask.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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.IO;
  9. using MediaBrowser.Model.Tasks;
  10. using Microsoft.Extensions.Logging;
  11. using MediaBrowser.Model.Globalization;
  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 IApplicationPaths ApplicationPaths { get; set; }
  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. /// <summary>
  42. /// Creates the triggers that define when the task will run
  43. /// </summary>
  44. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  45. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  46. {
  47. return new[] {
  48. // Every so often
  49. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
  50. };
  51. }
  52. /// <summary>
  53. /// Returns the task to be executed
  54. /// </summary>
  55. /// <param name="cancellationToken">The cancellation token.</param>
  56. /// <param name="progress">The progress.</param>
  57. /// <returns>Task.</returns>
  58. public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  59. {
  60. var minDateModified = DateTime.UtcNow.AddDays(-30);
  61. try
  62. {
  63. DeleteCacheFilesFromDirectory(cancellationToken, ApplicationPaths.CachePath, minDateModified, progress);
  64. }
  65. catch (DirectoryNotFoundException)
  66. {
  67. // No biggie here. Nothing to delete
  68. }
  69. progress.Report(90);
  70. minDateModified = DateTime.UtcNow.AddDays(-1);
  71. try
  72. {
  73. DeleteCacheFilesFromDirectory(cancellationToken, ApplicationPaths.TempDirectory, minDateModified, progress);
  74. }
  75. catch (DirectoryNotFoundException)
  76. {
  77. // No biggie here. Nothing to delete
  78. }
  79. return Task.CompletedTask;
  80. }
  81. /// <summary>
  82. /// Deletes the cache files from directory with a last write time less than a given date
  83. /// </summary>
  84. /// <param name="cancellationToken">The task cancellation token.</param>
  85. /// <param name="directory">The directory.</param>
  86. /// <param name="minDateModified">The min date modified.</param>
  87. /// <param name="progress">The progress.</param>
  88. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  89. {
  90. var filesToDelete = _fileSystem.GetFiles(directory, true)
  91. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  92. .ToList();
  93. var index = 0;
  94. foreach (var file in filesToDelete)
  95. {
  96. double percent = index;
  97. percent /= filesToDelete.Count;
  98. progress.Report(100 * percent);
  99. cancellationToken.ThrowIfCancellationRequested();
  100. DeleteFile(file.FullName);
  101. index++;
  102. }
  103. DeleteEmptyFolders(directory);
  104. progress.Report(100);
  105. }
  106. private void DeleteEmptyFolders(string parent)
  107. {
  108. foreach (var directory in _fileSystem.GetDirectoryPaths(parent))
  109. {
  110. DeleteEmptyFolders(directory);
  111. if (!_fileSystem.GetFileSystemEntryPaths(directory).Any())
  112. {
  113. try
  114. {
  115. Directory.Delete(directory, false);
  116. }
  117. catch (UnauthorizedAccessException ex)
  118. {
  119. _logger.LogError(ex, "Error deleting directory {path}", directory);
  120. }
  121. catch (IOException ex)
  122. {
  123. _logger.LogError(ex, "Error deleting directory {path}", directory);
  124. }
  125. }
  126. }
  127. }
  128. private void DeleteFile(string path)
  129. {
  130. try
  131. {
  132. _fileSystem.DeleteFile(path);
  133. }
  134. catch (UnauthorizedAccessException ex)
  135. {
  136. _logger.LogError(ex, "Error deleting file {path}", path);
  137. }
  138. catch (IOException ex)
  139. {
  140. _logger.LogError(ex, "Error deleting file {path}", path);
  141. }
  142. }
  143. /// <inheritdoc />
  144. public string Name => _localization.GetLocalizedString("TaskCleanCache");
  145. /// <inheritdoc />
  146. public string Description => _localization.GetLocalizedString("TaskCleanCacheDescription");
  147. /// <inheritdoc />
  148. public string Category => _localization.GetLocalizedString("TasksMaintenanceCategory");
  149. /// <inheritdoc />
  150. public string Key => "DeleteCacheFiles";
  151. /// <inheritdoc />
  152. public bool IsHidden => false;
  153. /// <inheritdoc />
  154. public bool IsEnabled => true;
  155. /// <inheritdoc />
  156. public bool IsLogged => true;
  157. }
  158. }