DeleteCacheFileTask.cs 5.6 KB

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