DeleteCacheFileTask.cs 6.1 KB

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