SubtitleScheduledTask.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Movies;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Subtitles;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Providers;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using System.IO;
  17. using MediaBrowser.Model.Serialization;
  18. using MediaBrowser.Model.Tasks;
  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 readonly 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. var result = _json.DeserializeFromFile<Dictionary<string, DateTime>>(path);
  121. if (result != null)
  122. {
  123. return result;
  124. }
  125. }
  126. catch
  127. {
  128. }
  129. return new Dictionary<string, DateTime>();
  130. }
  131. private async Task<bool> DownloadSubtitles(Video video, SubtitleOptions options, CancellationToken cancellationToken)
  132. {
  133. if ((options.DownloadEpisodeSubtitles &&
  134. video is Episode) ||
  135. (options.DownloadMovieSubtitles &&
  136. video is Movie))
  137. {
  138. var mediaStreams = _mediaSourceManager.GetStaticMediaSources(video, false).First().MediaStreams;
  139. var downloadedLanguages = await new SubtitleDownloader(_logger,
  140. _subtitleManager)
  141. .DownloadSubtitles(video,
  142. mediaStreams,
  143. options.SkipIfEmbeddedSubtitlesPresent,
  144. options.SkipIfAudioTrackMatches,
  145. options.RequirePerfectMatch,
  146. options.DownloadLanguages,
  147. cancellationToken).ConfigureAwait(false);
  148. // Rescan
  149. if (downloadedLanguages.Count > 0)
  150. {
  151. await video.RefreshMetadata(cancellationToken).ConfigureAwait(false);
  152. return false;
  153. }
  154. return true;
  155. }
  156. return false;
  157. }
  158. public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
  159. {
  160. return new[] {
  161. // Every so often
  162. new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerInterval, IntervalTicks = TimeSpan.FromHours(24).Ticks}
  163. };
  164. }
  165. public string Key
  166. {
  167. get { return "DownloadSubtitles"; }
  168. }
  169. }
  170. }