ImageCleanupTask.cs 7.4 KB

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