ImageCleanupTask.cs 6.5 KB

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