DeleteCacheFileTask.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. using MediaBrowser.Model.Tasks;
  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<TaskTriggerInfo> GetDefaultTriggers()
  40. {
  41. return new[] {
  42. // Every so often
  43. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
  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. public string Key
  146. {
  147. get { return "DeleteCacheFiles"; }
  148. }
  149. /// <summary>
  150. /// Gets the description.
  151. /// </summary>
  152. /// <value>The description.</value>
  153. public string Description
  154. {
  155. get { return "Deletes cache files no longer needed by the system"; }
  156. }
  157. /// <summary>
  158. /// Gets the category.
  159. /// </summary>
  160. /// <value>The category.</value>
  161. public string Category
  162. {
  163. get
  164. {
  165. return "Maintenance";
  166. }
  167. }
  168. /// <summary>
  169. /// Gets a value indicating whether this instance is hidden.
  170. /// </summary>
  171. /// <value><c>true</c> if this instance is hidden; otherwise, <c>false</c>.</value>
  172. public bool IsHidden
  173. {
  174. get { return true; }
  175. }
  176. public bool IsEnabled
  177. {
  178. get { return true; }
  179. }
  180. public bool IsLogged
  181. {
  182. get { return true; }
  183. }
  184. }
  185. }