DeleteCacheFileTask.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Model.Logging;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using CommonIO;
  11. namespace MediaBrowser.Common.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<ITaskTrigger> GetDefaultTriggers()
  39. {
  40. // Until we can vary these default triggers per server and MBT, we need something that makes sense for both
  41. return new ITaskTrigger[] {
  42. // Every so often
  43. new IntervalTrigger { Interval = TimeSpan.FromHours(24)}
  44. };
  45. }
  46. /// <summary>
  47. /// Returns the task to be executed
  48. /// </summary>
  49. /// <param name="cancellationToken">The cancellation token.</param>
  50. /// <param name="progress">The progress.</param>
  51. /// <returns>Task.</returns>
  52. public Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  53. {
  54. var minDateModified = DateTime.UtcNow.AddDays(-30);
  55. try
  56. {
  57. DeleteCacheFilesFromDirectory(cancellationToken, ApplicationPaths.CachePath, minDateModified, progress);
  58. }
  59. catch (DirectoryNotFoundException)
  60. {
  61. // No biggie here. Nothing to delete
  62. }
  63. progress.Report(90);
  64. minDateModified = DateTime.UtcNow.AddDays(-1);
  65. try
  66. {
  67. DeleteCacheFilesFromDirectory(cancellationToken, ApplicationPaths.TempDirectory, minDateModified, progress);
  68. }
  69. catch (DirectoryNotFoundException)
  70. {
  71. // No biggie here. Nothing to delete
  72. }
  73. return Task.FromResult(true);
  74. }
  75. /// <summary>
  76. /// Deletes the cache files from directory with a last write time less than a given date
  77. /// </summary>
  78. /// <param name="cancellationToken">The task cancellation token.</param>
  79. /// <param name="directory">The directory.</param>
  80. /// <param name="minDateModified">The min date modified.</param>
  81. /// <param name="progress">The progress.</param>
  82. private void DeleteCacheFilesFromDirectory(CancellationToken cancellationToken, string directory, DateTime minDateModified, IProgress<double> progress)
  83. {
  84. var filesToDelete = _fileSystem.GetFiles(directory, true)
  85. .Where(f => _fileSystem.GetLastWriteTimeUtc(f) < minDateModified)
  86. .ToList();
  87. var index = 0;
  88. foreach (var file in filesToDelete)
  89. {
  90. double percent = index;
  91. percent /= filesToDelete.Count;
  92. progress.Report(100 * percent);
  93. cancellationToken.ThrowIfCancellationRequested();
  94. DeleteFile(file.FullName);
  95. index++;
  96. }
  97. DeleteEmptyFolders(directory);
  98. progress.Report(100);
  99. }
  100. private void DeleteEmptyFolders(string parent)
  101. {
  102. foreach (var directory in _fileSystem.GetDirectoryPaths(parent))
  103. {
  104. DeleteEmptyFolders(directory);
  105. if (!_fileSystem.GetFileSystemEntryPaths(directory).Any())
  106. {
  107. try
  108. {
  109. _fileSystem.DeleteDirectory(directory, false);
  110. }
  111. catch (UnauthorizedAccessException ex)
  112. {
  113. _logger.ErrorException("Error deleting directory {0}", ex, directory);
  114. }
  115. catch (IOException ex)
  116. {
  117. _logger.ErrorException("Error deleting directory {0}", ex, directory);
  118. }
  119. }
  120. }
  121. }
  122. private void DeleteFile(string path)
  123. {
  124. try
  125. {
  126. _fileSystem.DeleteFile(path);
  127. }
  128. catch (UnauthorizedAccessException ex)
  129. {
  130. _logger.ErrorException("Error deleting file {0}", ex, path);
  131. }
  132. catch (IOException ex)
  133. {
  134. _logger.ErrorException("Error deleting file {0}", ex, path);
  135. }
  136. }
  137. /// <summary>
  138. /// Gets the name of the task
  139. /// </summary>
  140. /// <value>The name.</value>
  141. public string Name
  142. {
  143. get { return "Cache file cleanup"; }
  144. }
  145. /// <summary>
  146. /// Gets the description.
  147. /// </summary>
  148. /// <value>The description.</value>
  149. public string Description
  150. {
  151. get { return "Deletes cache files no longer needed by the system"; }
  152. }
  153. /// <summary>
  154. /// Gets the category.
  155. /// </summary>
  156. /// <value>The category.</value>
  157. public string Category
  158. {
  159. get
  160. {
  161. return "Maintenance";
  162. }
  163. }
  164. /// <summary>
  165. /// Gets a value indicating whether this instance is hidden.
  166. /// </summary>
  167. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  168. public bool IsHidden
  169. {
  170. get { return true; }
  171. }
  172. public bool IsEnabled
  173. {
  174. get { return true; }
  175. }
  176. }
  177. }