DeleteCacheFileTask.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  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. // At startup
  43. new StartupTrigger {DelayMs = 60000},
  44. // Every so often
  45. new IntervalTrigger { Interval = TimeSpan.FromHours(24)}
  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(-2);
  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.FromResult(true);
  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 = new DirectoryInfo(directory).EnumerateFiles("*", SearchOption.AllDirectories)
  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 static void DeleteEmptyFolders(string parent)
  103. {
  104. foreach (var directory in Directory.GetDirectories(parent))
  105. {
  106. DeleteEmptyFolders(directory);
  107. if (!Directory.EnumerateFileSystemEntries(directory).Any())
  108. {
  109. Directory.Delete(directory, false);
  110. }
  111. }
  112. }
  113. private void DeleteFile(string path)
  114. {
  115. try
  116. {
  117. _fileSystem.DeleteFile(path);
  118. }
  119. catch (IOException ex)
  120. {
  121. _logger.ErrorException("Error deleting file {0}", ex, path);
  122. }
  123. }
  124. /// <summary>
  125. /// Gets the name of the task
  126. /// </summary>
  127. /// <value>The name.</value>
  128. public string Name
  129. {
  130. get { return "Cache file cleanup"; }
  131. }
  132. /// <summary>
  133. /// Gets the description.
  134. /// </summary>
  135. /// <value>The description.</value>
  136. public string Description
  137. {
  138. get { return "Deletes cache files no longer needed by the system"; }
  139. }
  140. /// <summary>
  141. /// Gets the category.
  142. /// </summary>
  143. /// <value>The category.</value>
  144. public string Category
  145. {
  146. get
  147. {
  148. return "Maintenance";
  149. }
  150. }
  151. /// <summary>
  152. /// Gets a value indicating whether this instance is hidden.
  153. /// </summary>
  154. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  155. public bool IsHidden
  156. {
  157. get { return true; }
  158. }
  159. public bool IsEnabled
  160. {
  161. get { return true; }
  162. }
  163. }
  164. }