2
0

ImageCleanupTask.cs 6.7 KB

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