DeleteCacheFileTask.cs 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 MediaBrowser.Common.IO;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Tasks;
  13. namespace MediaBrowser.Common.Implementations.ScheduledTasks.Tasks
  14. {
  15. /// <summary>
  16. /// Deletes old cache files
  17. /// </summary>
  18. public class DeleteCacheFileTask : IScheduledTask, IConfigurableScheduledTask
  19. {
  20. /// <summary>
  21. /// Gets or sets the application paths.
  22. /// </summary>
  23. /// <value>The application paths.</value>
  24. private IApplicationPaths ApplicationPaths { get; set; }
  25. private readonly ILogger _logger;
  26. private readonly IFileSystem _fileSystem;
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="DeleteCacheFileTask" /> class.
  29. /// </summary>
  30. public DeleteCacheFileTask(IApplicationPaths appPaths, ILogger logger, IFileSystem fileSystem)
  31. {
  32. ApplicationPaths = appPaths;
  33. _logger = logger;
  34. _fileSystem = fileSystem;
  35. }
  36. /// <summary>
  37. /// Creates the triggers that define when the task will run
  38. /// </summary>
  39. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  40. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  41. {
  42. return new[] {
  43. // Every so often
  44. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
  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(-1);
  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. try
  109. {
  110. _fileSystem.DeleteDirectory(directory, false);
  111. }
  112. catch (UnauthorizedAccessException ex)
  113. {
  114. _logger.ErrorException("Error deleting directory {0}", ex, directory);
  115. }
  116. catch (IOException ex)
  117. {
  118. _logger.ErrorException("Error deleting directory {0}", ex, directory);
  119. }
  120. }
  121. }
  122. }
  123. private void DeleteFile(string path)
  124. {
  125. try
  126. {
  127. _fileSystem.DeleteFile(path);
  128. }
  129. catch (UnauthorizedAccessException ex)
  130. {
  131. _logger.ErrorException("Error deleting file {0}", ex, path);
  132. }
  133. catch (IOException ex)
  134. {
  135. _logger.ErrorException("Error deleting file {0}", ex, path);
  136. }
  137. }
  138. /// <summary>
  139. /// Gets the name of the task
  140. /// </summary>
  141. /// <value>The name.</value>
  142. public string Name
  143. {
  144. get { return "Cache file cleanup"; }
  145. }
  146. public string Key
  147. {
  148. get { return "DeleteCacheFiles"; }
  149. }
  150. /// <summary>
  151. /// Gets the description.
  152. /// </summary>
  153. /// <value>The description.</value>
  154. public string Description
  155. {
  156. get { return "Deletes cache files no longer needed by the system"; }
  157. }
  158. /// <summary>
  159. /// Gets the category.
  160. /// </summary>
  161. /// <value>The category.</value>
  162. public string Category
  163. {
  164. get
  165. {
  166. return "Maintenance";
  167. }
  168. }
  169. /// <summary>
  170. /// Gets a value indicating whether this instance is hidden.
  171. /// </summary>
  172. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  173. public bool IsHidden
  174. {
  175. get { return true; }
  176. }
  177. public bool IsEnabled
  178. {
  179. get { return true; }
  180. }
  181. public bool IsLogged
  182. {
  183. get { return true; }
  184. }
  185. }
  186. }