SubtitleScheduledTask.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.ScheduledTasks;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Controller.Entities.TV;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.Subtitles;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Providers;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.IO;
  18. using MediaBrowser.Model.Serialization;
  19. namespace MediaBrowser.Providers.MediaInfo
  20. {
  21. public class SubtitleScheduledTask : IScheduledTask
  22. {
  23. private readonly ILibraryManager _libraryManager;
  24. private readonly IServerConfigurationManager _config;
  25. private readonly ISubtitleManager _subtitleManager;
  26. private readonly IMediaSourceManager _mediaSourceManager;
  27. private readonly ILogger _logger;
  28. private IJsonSerializer _json;
  29. public SubtitleScheduledTask(ILibraryManager libraryManager, IJsonSerializer json, IServerConfigurationManager config, ISubtitleManager subtitleManager, ILogger logger, IMediaSourceManager mediaSourceManager)
  30. {
  31. _libraryManager = libraryManager;
  32. _config = config;
  33. _subtitleManager = subtitleManager;
  34. _logger = logger;
  35. _mediaSourceManager = mediaSourceManager;
  36. _json = json;
  37. }
  38. public string Name
  39. {
  40. get { return "Download missing subtitles"; }
  41. }
  42. public string Description
  43. {
  44. get { return "Searches the internet for missing subtitles based on metadata configuration."; }
  45. }
  46. public string Category
  47. {
  48. get { return "Library"; }
  49. }
  50. private SubtitleOptions GetOptions()
  51. {
  52. return _config.GetConfiguration<SubtitleOptions>("subtitles");
  53. }
  54. public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress)
  55. {
  56. var options = GetOptions();
  57. var types = new List<string>();
  58. if (options.DownloadEpisodeSubtitles)
  59. {
  60. types.Add("Episode");
  61. }
  62. if (options.DownloadMovieSubtitles)
  63. {
  64. types.Add("Movie");
  65. }
  66. if (types.Count == 0)
  67. {
  68. return;
  69. }
  70. var videos = _libraryManager.GetItemList(new InternalItemsQuery
  71. {
  72. MediaTypes = new string[] { MediaType.Video },
  73. IsVirtualItem = false,
  74. ExcludeLocationTypes = new LocationType[] { LocationType.Remote, LocationType.Virtual },
  75. IncludeItemTypes = types.ToArray()
  76. }).OfType<Video>()
  77. .ToList();
  78. var failHistoryPath = Path.Combine(_config.ApplicationPaths.CachePath, "subtitlehistory.json");
  79. var history = GetHistory(failHistoryPath);
  80. var numComplete = 0;
  81. foreach (var video in videos)
  82. {
  83. DateTime lastAttempt;
  84. if (history.TryGetValue(video.Id.ToString("N"), out lastAttempt))
  85. {
  86. if ((DateTime.UtcNow - lastAttempt).TotalDays <= 7)
  87. {
  88. continue;
  89. }
  90. }
  91. try
  92. {
  93. var shouldRetry = await DownloadSubtitles(video, options, cancellationToken).ConfigureAwait(false);
  94. if (shouldRetry)
  95. {
  96. history[video.Id.ToString("N")] = DateTime.UtcNow;
  97. }
  98. else
  99. {
  100. history.Remove(video.Id.ToString("N"));
  101. }
  102. }
  103. catch (Exception ex)
  104. {
  105. _logger.ErrorException("Error downloading subtitles for {0}", ex, video.Path);
  106. history[video.Id.ToString("N")] = DateTime.UtcNow;
  107. }
  108. // Update progress
  109. numComplete++;
  110. double percent = numComplete;
  111. percent /= videos.Count;
  112. progress.Report(100 * percent);
  113. }
  114. _json.SerializeToFile(history, failHistoryPath);
  115. }
  116. private Dictionary<string,DateTime> GetHistory(string path)
  117. {
  118. try
  119. {
  120. return _json.DeserializeFromFile<Dictionary<string, DateTime>>(path);
  121. }
  122. catch
  123. {
  124. return new Dictionary<string, DateTime>();
  125. }
  126. }
  127. private async Task<bool> DownloadSubtitles(Video video, SubtitleOptions options, CancellationToken cancellationToken)
  128. {
  129. if ((options.DownloadEpisodeSubtitles &&
  130. video is Episode) ||
  131. (options.DownloadMovieSubtitles &&
  132. video is Movie))
  133. {
  134. var mediaStreams = _mediaSourceManager.GetStaticMediaSources(video, false).First().MediaStreams;
  135. var downloadedLanguages = await new SubtitleDownloader(_logger,
  136. _subtitleManager)
  137. .DownloadSubtitles(video,
  138. mediaStreams,
  139. options.SkipIfEmbeddedSubtitlesPresent,
  140. options.SkipIfAudioTrackMatches,
  141. options.RequirePerfectMatch,
  142. options.DownloadLanguages,
  143. cancellationToken).ConfigureAwait(false);
  144. // Rescan
  145. if (downloadedLanguages.Count > 0)
  146. {
  147. await video.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  148. return false;
  149. }
  150. return true;
  151. }
  152. return false;
  153. }
  154. public IEnumerable<ITaskTrigger> GetDefaultTriggers()
  155. {
  156. return new ITaskTrigger[]
  157. {
  158. new IntervalTrigger{ Interval = TimeSpan.FromHours(8)}
  159. };
  160. }
  161. }
  162. }