SeriesPostScanTask.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Entities.TV;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Localization;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. using CommonIO;
  14. using MediaBrowser.Common.ScheduledTasks;
  15. using MediaBrowser.Controller.Entities;
  16. using MediaBrowser.Controller.Plugins;
  17. namespace MediaBrowser.Providers.TV
  18. {
  19. class SeriesGroup : List<Series>, IGrouping<string, Series>
  20. {
  21. public string Key { get; set; }
  22. }
  23. class SeriesPostScanTask : ILibraryPostScanTask, IHasOrder
  24. {
  25. /// <summary>
  26. /// The _library manager
  27. /// </summary>
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly IServerConfigurationManager _config;
  30. private readonly ILogger _logger;
  31. private readonly ILocalizationManager _localization;
  32. private readonly IFileSystem _fileSystem;
  33. public SeriesPostScanTask(ILibraryManager libraryManager, ILogger logger, IServerConfigurationManager config, ILocalizationManager localization, IFileSystem fileSystem)
  34. {
  35. _libraryManager = libraryManager;
  36. _logger = logger;
  37. _config = config;
  38. _localization = localization;
  39. _fileSystem = fileSystem;
  40. }
  41. public Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  42. {
  43. return RunInternal(progress, cancellationToken);
  44. }
  45. private async Task RunInternal(IProgress<double> progress, CancellationToken cancellationToken)
  46. {
  47. var seriesList = _libraryManager.GetItemList(new InternalItemsQuery()
  48. {
  49. IncludeItemTypes = new[] { typeof(Series).Name },
  50. Recursive = true,
  51. GroupByPresentationUniqueKey = false
  52. }).Cast<Series>().ToList();
  53. var seriesGroups = FindSeriesGroups(seriesList).Where(g => !string.IsNullOrEmpty(g.Key)).ToList();
  54. await new MissingEpisodeProvider(_logger, _config, _libraryManager, _localization, _fileSystem)
  55. .Run(seriesGroups, true, cancellationToken).ConfigureAwait(false);
  56. var numComplete = 0;
  57. foreach (var series in seriesList)
  58. {
  59. cancellationToken.ThrowIfCancellationRequested();
  60. var episodes = series.GetRecursiveChildren(i => i is Episode)
  61. .Cast<Episode>()
  62. .ToList();
  63. var physicalEpisodes = episodes.Where(i => i.LocationType != LocationType.Virtual)
  64. .ToList();
  65. series.SpecialFeatureIds = physicalEpisodes
  66. .Where(i => i.ParentIndexNumber.HasValue && i.ParentIndexNumber.Value == 0)
  67. .Select(i => i.Id)
  68. .ToList();
  69. numComplete++;
  70. double percent = numComplete;
  71. percent /= seriesList.Count;
  72. percent *= 100;
  73. progress.Report(percent);
  74. }
  75. }
  76. internal static IEnumerable<IGrouping<string, Series>> FindSeriesGroups(List<Series> seriesList)
  77. {
  78. var links = seriesList.ToDictionary(s => s, s => seriesList.Where(c => c != s && ShareProviderId(s, c)).ToList());
  79. var visited = new HashSet<Series>();
  80. foreach (var series in seriesList)
  81. {
  82. if (!visited.Contains(series))
  83. {
  84. var group = new SeriesGroup();
  85. FindAllLinked(series, visited, links, group);
  86. group.Key = group.Select(s => s.GetProviderId(MetadataProviders.Tvdb)).FirstOrDefault(id => !string.IsNullOrEmpty(id));
  87. yield return group;
  88. }
  89. }
  90. }
  91. private static void FindAllLinked(Series series, HashSet<Series> visited, IDictionary<Series, List<Series>> linksMap, List<Series> results)
  92. {
  93. results.Add(series);
  94. visited.Add(series);
  95. var links = linksMap[series];
  96. foreach (var s in links)
  97. {
  98. if (!visited.Contains(s))
  99. {
  100. FindAllLinked(s, visited, linksMap, results);
  101. }
  102. }
  103. }
  104. private static bool ShareProviderId(Series a, Series b)
  105. {
  106. return a.ProviderIds.Any(id =>
  107. {
  108. string value;
  109. return b.ProviderIds.TryGetValue(id.Key, out value) && id.Value == value;
  110. });
  111. }
  112. public int Order
  113. {
  114. get
  115. {
  116. // Run after tvdb update task
  117. return 1;
  118. }
  119. }
  120. }
  121. public class CleanMissingEpisodesEntryPoint : IServerEntryPoint
  122. {
  123. private readonly ILibraryManager _libraryManager;
  124. private readonly IServerConfigurationManager _config;
  125. private readonly ILogger _logger;
  126. private readonly ILocalizationManager _localization;
  127. private readonly IFileSystem _fileSystem;
  128. private readonly object _libraryChangedSyncLock = new object();
  129. private const int LibraryUpdateDuration = 180000;
  130. private readonly ITaskManager _taskManager;
  131. public CleanMissingEpisodesEntryPoint(ILibraryManager libraryManager, IServerConfigurationManager config, ILogger logger, ILocalizationManager localization, IFileSystem fileSystem, ITaskManager taskManager)
  132. {
  133. _libraryManager = libraryManager;
  134. _config = config;
  135. _logger = logger;
  136. _localization = localization;
  137. _fileSystem = fileSystem;
  138. _taskManager = taskManager;
  139. }
  140. private Timer LibraryUpdateTimer { get; set; }
  141. public void Run()
  142. {
  143. _libraryManager.ItemAdded += _libraryManager_ItemAdded;
  144. }
  145. private void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  146. {
  147. if (!FilterItem(e.Item))
  148. {
  149. return;
  150. }
  151. lock (_libraryChangedSyncLock)
  152. {
  153. if (LibraryUpdateTimer == null)
  154. {
  155. LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration, Timeout.Infinite);
  156. }
  157. else
  158. {
  159. LibraryUpdateTimer.Change(LibraryUpdateDuration, Timeout.Infinite);
  160. }
  161. }
  162. }
  163. private async void LibraryUpdateTimerCallback(object state)
  164. {
  165. try
  166. {
  167. if (MissingEpisodeProvider.IsRunning)
  168. {
  169. return;
  170. }
  171. if (_libraryManager.IsScanRunning)
  172. {
  173. return;
  174. }
  175. var seriesList = _libraryManager.GetItemList(new InternalItemsQuery()
  176. {
  177. IncludeItemTypes = new[] { typeof(Series).Name },
  178. Recursive = true,
  179. GroupByPresentationUniqueKey = false
  180. }).Cast<Series>().ToList();
  181. var seriesGroups = SeriesPostScanTask.FindSeriesGroups(seriesList).Where(g => !string.IsNullOrEmpty(g.Key)).ToList();
  182. await new MissingEpisodeProvider(_logger, _config, _libraryManager, _localization, _fileSystem)
  183. .Run(seriesGroups, false, CancellationToken.None).ConfigureAwait(false);
  184. }
  185. catch (Exception ex)
  186. {
  187. _logger.ErrorException("Error in SeriesPostScanTask", ex);
  188. }
  189. }
  190. private bool FilterItem(BaseItem item)
  191. {
  192. return item is Episode && item.LocationType != LocationType.Virtual;
  193. }
  194. /// <summary>
  195. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  196. /// </summary>
  197. public void Dispose()
  198. {
  199. Dispose(true);
  200. }
  201. /// <summary>
  202. /// Releases unmanaged and - optionally - managed resources.
  203. /// </summary>
  204. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  205. protected virtual void Dispose(bool dispose)
  206. {
  207. if (dispose)
  208. {
  209. if (LibraryUpdateTimer != null)
  210. {
  211. LibraryUpdateTimer.Dispose();
  212. LibraryUpdateTimer = null;
  213. }
  214. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  215. }
  216. }
  217. }
  218. }