ChapterImagesTask.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.MediaEncoding;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MoreLinq;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Server.Implementations.ScheduledTasks
  17. {
  18. /// <summary>
  19. /// Class ChapterImagesTask
  20. /// </summary>
  21. class ChapterImagesTask : IScheduledTask
  22. {
  23. /// <summary>
  24. /// The _logger
  25. /// </summary>
  26. private readonly ILogger _logger;
  27. /// <summary>
  28. /// The _library manager
  29. /// </summary>
  30. private readonly ILibraryManager _libraryManager;
  31. private readonly List<Video> _newlyAddedItems = new List<Video>();
  32. private const int NewItemDelay = 30000;
  33. /// <summary>
  34. /// The current new item timer
  35. /// </summary>
  36. /// <value>The new item timer.</value>
  37. private Timer NewItemTimer { get; set; }
  38. private readonly IItemRepository _itemRepo;
  39. private readonly IApplicationPaths _appPaths;
  40. private readonly IEncodingManager _encodingManager;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="ChapterImagesTask" /> class.
  43. /// </summary>
  44. /// <param name="logManager">The log manager.</param>
  45. /// <param name="libraryManager">The library manager.</param>
  46. /// <param name="itemRepo">The item repo.</param>
  47. public ChapterImagesTask(ILogManager logManager, ILibraryManager libraryManager, IItemRepository itemRepo, IApplicationPaths appPaths, IEncodingManager encodingManager)
  48. {
  49. _logger = logManager.GetLogger(GetType().Name);
  50. _libraryManager = libraryManager;
  51. _itemRepo = itemRepo;
  52. _appPaths = appPaths;
  53. _encodingManager = encodingManager;
  54. libraryManager.ItemAdded += libraryManager_ItemAdded;
  55. libraryManager.ItemUpdated += libraryManager_ItemAdded;
  56. }
  57. void libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  58. {
  59. var video = e.Item as Video;
  60. if (video != null)
  61. {
  62. lock (_newlyAddedItems)
  63. {
  64. _newlyAddedItems.Add(video);
  65. if (NewItemTimer == null)
  66. {
  67. NewItemTimer = new Timer(NewItemTimerCallback, null, NewItemDelay, Timeout.Infinite);
  68. }
  69. else
  70. {
  71. NewItemTimer.Change(NewItemDelay, Timeout.Infinite);
  72. }
  73. }
  74. }
  75. }
  76. private async void NewItemTimerCallback(object state)
  77. {
  78. List<Video> newItems;
  79. // Lock the list and release all resources
  80. lock (_newlyAddedItems)
  81. {
  82. newItems = _newlyAddedItems.DistinctBy(i => i.Id).ToList();
  83. _newlyAddedItems.Clear();
  84. NewItemTimer.Dispose();
  85. NewItemTimer = null;
  86. }
  87. // Limit to video files to reduce changes of ffmpeg crash dialog
  88. foreach (var item in newItems
  89. .Where(i => i.LocationType == LocationType.FileSystem && i.VideoType == VideoType.VideoFile && string.IsNullOrEmpty(i.PrimaryImagePath) && i.DefaultVideoStreamIndex.HasValue)
  90. .Take(1))
  91. {
  92. try
  93. {
  94. var chapters = _itemRepo.GetChapters(item.Id).ToList();
  95. await _encodingManager.RefreshChapterImages(new ChapterImageRefreshOptions
  96. {
  97. SaveChapters = true,
  98. ExtractImages = true,
  99. Video = item,
  100. Chapters = chapters
  101. }, CancellationToken.None);
  102. }
  103. catch (Exception ex)
  104. {
  105. _logger.ErrorException("Error creating image for {0}", ex, item.Name);
  106. }
  107. }
  108. }
  109. /// <summary>
  110. /// Creates the triggers that define when the task will run
  111. /// </summary>
  112. /// <returns>IEnumerable{BaseTaskTrigger}.</returns>
  113. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  114. {
  115. return new ITaskTrigger[]
  116. {
  117. new DailyTrigger { TimeOfDay = TimeSpan.FromHours(4) }
  118. };
  119. }
  120. /// <summary>
  121. /// Returns the task to be executed
  122. /// </summary>
  123. /// <param name="cancellationToken">The cancellation token.</param>
  124. /// <param name="progress">The progress.</param>
  125. /// <returns>Task.</returns>
  126. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  127. {
  128. var videos = _libraryManager.RootFolder.RecursiveChildren
  129. .OfType<Video>()
  130. .ToList();
  131. var numComplete = 0;
  132. var failHistoryPath = Path.Combine(_appPaths.CachePath, "chapter-failures.txt");
  133. List<string> previouslyFailedImages;
  134. try
  135. {
  136. previouslyFailedImages = File.ReadAllText(failHistoryPath)
  137. .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
  138. .ToList();
  139. }
  140. catch (FileNotFoundException)
  141. {
  142. previouslyFailedImages = new List<string>();
  143. }
  144. catch (DirectoryNotFoundException)
  145. {
  146. previouslyFailedImages = new List<string>();
  147. }
  148. foreach (var video in videos)
  149. {
  150. cancellationToken.ThrowIfCancellationRequested();
  151. var key = video.Path + video.DateModified.Ticks;
  152. var extract = !previouslyFailedImages.Contains(key, StringComparer.OrdinalIgnoreCase);
  153. var chapters = _itemRepo.GetChapters(video.Id).ToList();
  154. var success = await _encodingManager.RefreshChapterImages(new ChapterImageRefreshOptions
  155. {
  156. SaveChapters = true,
  157. ExtractImages = extract,
  158. Video = video,
  159. Chapters = chapters
  160. }, CancellationToken.None);
  161. if (!success)
  162. {
  163. previouslyFailedImages.Add(key);
  164. var parentPath = Path.GetDirectoryName(failHistoryPath);
  165. Directory.CreateDirectory(parentPath);
  166. File.WriteAllText(failHistoryPath, string.Join("|", previouslyFailedImages.ToArray()));
  167. }
  168. numComplete++;
  169. double percent = numComplete;
  170. percent /= videos.Count;
  171. progress.Report(100 * percent);
  172. }
  173. }
  174. /// <summary>
  175. /// Gets the name of the task
  176. /// </summary>
  177. /// <value>The name.</value>
  178. public string Name
  179. {
  180. get
  181. {
  182. return "Chapter image extraction";
  183. }
  184. }
  185. /// <summary>
  186. /// Gets the description.
  187. /// </summary>
  188. /// <value>The description.</value>
  189. public string Description
  190. {
  191. get { return "Creates thumbnails for videos that have chapters."; }
  192. }
  193. /// <summary>
  194. /// Gets the category.
  195. /// </summary>
  196. /// <value>The category.</value>
  197. public string Category
  198. {
  199. get
  200. {
  201. return "Library";
  202. }
  203. }
  204. }
  205. }