ChapterImagesTask.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Configuration;
  8. using MediaBrowser.Controller.Dto;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Library;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Persistence;
  13. using MediaBrowser.Controller.Providers;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Tasks;
  17. using Microsoft.Extensions.Logging;
  18. using MediaBrowser.Model.Globalization;
  19. namespace Emby.Server.Implementations.ScheduledTasks
  20. {
  21. /// <summary>
  22. /// Class ChapterImagesTask.
  23. /// </summary>
  24. public class ChapterImagesTask : IScheduledTask
  25. {
  26. /// <summary>
  27. /// The _logger.
  28. /// </summary>
  29. private readonly ILogger<ChapterImagesTask> _logger;
  30. /// <summary>
  31. /// The _library manager.
  32. /// </summary>
  33. private readonly ILibraryManager _libraryManager;
  34. private readonly IItemRepository _itemRepo;
  35. private readonly IApplicationPaths _appPaths;
  36. private readonly IEncodingManager _encodingManager;
  37. private readonly IFileSystem _fileSystem;
  38. private readonly ILocalizationManager _localization;
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="ChapterImagesTask" /> class.
  41. /// </summary>
  42. public ChapterImagesTask(
  43. ILoggerFactory loggerFactory,
  44. ILibraryManager libraryManager,
  45. IItemRepository itemRepo,
  46. IApplicationPaths appPaths,
  47. IEncodingManager encodingManager,
  48. IFileSystem fileSystem,
  49. ILocalizationManager localization)
  50. {
  51. _logger = loggerFactory.CreateLogger<ChapterImagesTask>();
  52. _libraryManager = libraryManager;
  53. _itemRepo = itemRepo;
  54. _appPaths = appPaths;
  55. _encodingManager = encodingManager;
  56. _fileSystem = fileSystem;
  57. _localization = localization;
  58. }
  59. /// <summary>
  60. /// Creates the triggers that define when the task will run.
  61. /// </summary>
  62. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  63. {
  64. return new[]
  65. {
  66. new TaskTriggerInfo
  67. {
  68. Type = TaskTriggerInfo.TriggerDaily,
  69. TimeOfDayTicks = TimeSpan.FromHours(2).Ticks,
  70. MaxRuntimeTicks = TimeSpan.FromHours(4).Ticks
  71. }
  72. };
  73. }
  74. /// <summary>
  75. /// Returns the task to be executed.
  76. /// </summary>
  77. /// <param name="cancellationToken">The cancellation token.</param>
  78. /// <param name="progress">The progress.</param>
  79. /// <returns>Task.</returns>
  80. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  81. {
  82. var videos = _libraryManager.GetItemList(new InternalItemsQuery
  83. {
  84. MediaTypes = new[] { MediaType.Video },
  85. IsFolder = false,
  86. Recursive = true,
  87. DtoOptions = new DtoOptions(false)
  88. {
  89. EnableImages = false
  90. },
  91. SourceTypes = new SourceType[] { SourceType.Library },
  92. HasChapterImages = false,
  93. IsVirtualItem = false
  94. })
  95. .OfType<Video>()
  96. .ToList();
  97. var numComplete = 0;
  98. var failHistoryPath = Path.Combine(_appPaths.CachePath, "chapter-failures.txt");
  99. List<string> previouslyFailedImages;
  100. if (File.Exists(failHistoryPath))
  101. {
  102. try
  103. {
  104. previouslyFailedImages = File.ReadAllText(failHistoryPath)
  105. .Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries)
  106. .ToList();
  107. }
  108. catch (IOException)
  109. {
  110. previouslyFailedImages = new List<string>();
  111. }
  112. }
  113. else
  114. {
  115. previouslyFailedImages = new List<string>();
  116. }
  117. var directoryService = new DirectoryService(_fileSystem);
  118. foreach (var video in videos)
  119. {
  120. cancellationToken.ThrowIfCancellationRequested();
  121. var key = video.Path + video.DateModified.Ticks;
  122. var extract = !previouslyFailedImages.Contains(key, StringComparer.OrdinalIgnoreCase);
  123. try
  124. {
  125. var chapters = _itemRepo.GetChapters(video);
  126. var success = await _encodingManager.RefreshChapterImages(video, directoryService, chapters, extract, true, cancellationToken).ConfigureAwait(false);
  127. if (!success)
  128. {
  129. previouslyFailedImages.Add(key);
  130. var parentPath = Path.GetDirectoryName(failHistoryPath);
  131. Directory.CreateDirectory(parentPath);
  132. string text = string.Join("|", previouslyFailedImages);
  133. File.WriteAllText(failHistoryPath, text);
  134. }
  135. numComplete++;
  136. double percent = numComplete;
  137. percent /= videos.Count;
  138. progress.Report(100 * percent);
  139. }
  140. catch (ObjectDisposedException)
  141. {
  142. // TODO Investigate and properly fix.
  143. break;
  144. }
  145. }
  146. }
  147. /// <inheritdoc />
  148. public string Name => _localization.GetLocalizedString("TaskRefreshChapterImages");
  149. /// <inheritdoc />
  150. public string Description => _localization.GetLocalizedString("TaskRefreshChapterImagesDescription");
  151. /// <inheritdoc />
  152. public string Category => _localization.GetLocalizedString("TasksLibraryCategory");
  153. /// <inheritdoc />
  154. public string Key => "RefreshChapterImages";
  155. /// <inheritdoc />
  156. public bool IsHidden => false;
  157. /// <inheritdoc />
  158. public bool IsEnabled => true;
  159. /// <inheritdoc />
  160. public bool IsLogged => true;
  161. }
  162. }