SeriesPostScanTask.cs 8.5 KB

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