DeleteCacheFileTask.cs 5.8 KB

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