ImageCleanupTask.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. using MediaBrowser.Common.ScheduledTasks;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Movies;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Server.Implementations.ScheduledTasks
  15. {
  16. /// <summary>
  17. /// Class ImageCleanupTask
  18. /// </summary>
  19. public class ImageCleanupTask : IScheduledTask
  20. {
  21. /// <summary>
  22. /// The _kernel
  23. /// </summary>
  24. private readonly Kernel _kernel;
  25. /// <summary>
  26. /// The _logger
  27. /// </summary>
  28. private readonly ILogger _logger;
  29. private readonly ILibraryManager _libraryManager;
  30. private readonly IServerApplicationPaths _appPaths;
  31. private readonly IItemRepository _itemRepo;
  32. /// <summary>
  33. /// Initializes a new instance of the <see cref="ImageCleanupTask" /> class.
  34. /// </summary>
  35. /// <param name="kernel">The kernel.</param>
  36. /// <param name="logger">The logger.</param>
  37. /// <param name="libraryManager">The library manager.</param>
  38. /// <param name="appPaths">The app paths.</param>
  39. public ImageCleanupTask(Kernel kernel, ILogger logger, ILibraryManager libraryManager, IServerApplicationPaths appPaths, IItemRepository itemRepo)
  40. {
  41. _kernel = kernel;
  42. _logger = logger;
  43. _libraryManager = libraryManager;
  44. _appPaths = appPaths;
  45. _itemRepo = itemRepo;
  46. }
  47. /// <summary>
  48. /// Creates the triggers that define when the task will run
  49. /// </summary>
  50. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  51. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  52. {
  53. return new ITaskTrigger[]
  54. {
  55. new DailyTrigger { TimeOfDay = TimeSpan.FromHours(2) }
  56. };
  57. }
  58. /// <summary>
  59. /// Returns the task to be executed
  60. /// </summary>
  61. /// <param name="cancellationToken">The cancellation token.</param>
  62. /// <param name="progress">The progress.</param>
  63. /// <returns>Task.</returns>
  64. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  65. {
  66. var items = _libraryManager.RootFolder.RecursiveChildren.ToList();
  67. foreach (var video in items.OfType<Video>().Where(v => v.Chapters != null))
  68. {
  69. await _kernel.FFMpegManager.PopulateChapterImages(video, cancellationToken, false, true).ConfigureAwait(false);
  70. }
  71. // First gather all image files
  72. var files = GetFiles(_kernel.FFMpegManager.AudioImagesDataPath)
  73. .Concat(GetFiles(_kernel.FFMpegManager.VideoImagesDataPath))
  74. .Concat(GetFiles(_appPaths.DownloadedImagesDataPath))
  75. .ToList();
  76. // Now gather all items
  77. items.Add(_libraryManager.RootFolder);
  78. // Determine all possible image paths
  79. var pathsInUse = items.SelectMany(GetPathsInUse)
  80. .Distinct(StringComparer.OrdinalIgnoreCase)
  81. .ToDictionary(p => p, StringComparer.OrdinalIgnoreCase);
  82. var numComplete = 0;
  83. foreach (var file in files)
  84. {
  85. cancellationToken.ThrowIfCancellationRequested();
  86. if (!pathsInUse.ContainsKey(file))
  87. {
  88. cancellationToken.ThrowIfCancellationRequested();
  89. try
  90. {
  91. File.Delete(file);
  92. }
  93. catch (IOException ex)
  94. {
  95. _logger.ErrorException("Error deleting {0}", ex, file);
  96. }
  97. }
  98. // Update progress
  99. numComplete++;
  100. double percent = numComplete;
  101. percent /= files.Count;
  102. progress.Report(100 * percent);
  103. }
  104. }
  105. /// <summary>
  106. /// Gets the paths in use.
  107. /// </summary>
  108. /// <param name="item">The item.</param>
  109. /// <returns>IEnumerable{System.String}.</returns>
  110. private IEnumerable<string> GetPathsInUse(BaseItem item)
  111. {
  112. IEnumerable<string> images = new List<string>();
  113. if (item.Images != null)
  114. {
  115. images = images.Concat(item.Images.Values);
  116. }
  117. if (item.BackdropImagePaths != null)
  118. {
  119. images = images.Concat(item.BackdropImagePaths);
  120. }
  121. if (item.ScreenshotImagePaths != null)
  122. {
  123. images = images.Concat(item.ScreenshotImagePaths);
  124. }
  125. var localTrailers = _itemRepo.GetItems(item.LocalTrailerIds).ToList();
  126. images = localTrailers.Aggregate(images, (current, subItem) => current.Concat(GetPathsInUse(subItem)));
  127. var themeSongs = _itemRepo.GetItems(item.ThemeSongIds).ToList();
  128. images = themeSongs.Aggregate(images, (current, subItem) => current.Concat(GetPathsInUse(subItem)));
  129. var themeVideos = _itemRepo.GetItems(item.ThemeVideoIds).ToList();
  130. images = themeVideos.Aggregate(images, (current, subItem) => current.Concat(GetPathsInUse(subItem)));
  131. var video = item as Video;
  132. if (video != null && video.Chapters != null)
  133. {
  134. images = images.Concat(video.Chapters.Where(i => !string.IsNullOrEmpty(i.ImagePath)).Select(i => i.ImagePath));
  135. }
  136. var movie = item as Movie;
  137. if (movie != null)
  138. {
  139. var specialFeattures = _itemRepo.GetItems(movie.SpecialFeatureIds).ToList();
  140. images = specialFeattures.Aggregate(images, (current, subItem) => current.Concat(GetPathsInUse(subItem)));
  141. }
  142. return images;
  143. }
  144. /// <summary>
  145. /// Gets the files.
  146. /// </summary>
  147. /// <param name="path">The path.</param>
  148. /// <returns>IEnumerable{System.String}.</returns>
  149. private IEnumerable<string> GetFiles(string path)
  150. {
  151. return Directory.EnumerateFiles(path, "*.jpg", SearchOption.AllDirectories).Concat(Directory.EnumerateFiles(path, "*.png", SearchOption.AllDirectories));
  152. }
  153. /// <summary>
  154. /// Gets the name of the task
  155. /// </summary>
  156. /// <value>The name.</value>
  157. public string Name
  158. {
  159. get { return "Images cleanup"; }
  160. }
  161. /// <summary>
  162. /// Gets the description.
  163. /// </summary>
  164. /// <value>The description.</value>
  165. public string Description
  166. {
  167. get { return "Deletes downloaded and extracted images that are no longer being used."; }
  168. }
  169. /// <summary>
  170. /// Gets the category.
  171. /// </summary>
  172. /// <value>The category.</value>
  173. public string Category
  174. {
  175. get
  176. {
  177. return "Maintenance";
  178. }
  179. }
  180. }
  181. }