DeleteCacheFileTask.cs 5.8 KB

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