DeleteCacheFileTask.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. // 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(-2);
  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. _fileSystem.DeleteDirectory(directory, false);
  108. }
  109. }
  110. }
  111. private void DeleteFile(string path)
  112. {
  113. try
  114. {
  115. _fileSystem.DeleteFile(path);
  116. }
  117. catch (IOException ex)
  118. {
  119. _logger.ErrorException("Error deleting file {0}", ex, path);
  120. }
  121. }
  122. /// <summary>
  123. /// Gets the name of the task
  124. /// </summary>
  125. /// <value>The name.</value>
  126. public string Name
  127. {
  128. get { return "Cache file cleanup"; }
  129. }
  130. /// <summary>
  131. /// Gets the description.
  132. /// </summary>
  133. /// <value>The description.</value>
  134. public string Description
  135. {
  136. get { return "Deletes cache files no longer needed by the system"; }
  137. }
  138. /// <summary>
  139. /// Gets the category.
  140. /// </summary>
  141. /// <value>The category.</value>
  142. public string Category
  143. {
  144. get
  145. {
  146. return "Maintenance";
  147. }
  148. }
  149. /// <summary>
  150. /// Gets a value indicating whether this instance is hidden.
  151. /// </summary>
  152. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  153. public bool IsHidden
  154. {
  155. get { return true; }
  156. }
  157. public bool IsEnabled
  158. {
  159. get { return true; }
  160. }
  161. }
  162. }