SeriesPostScanTask.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. }).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. if (MissingEpisodeProvider.IsRunning)
  166. {
  167. return;
  168. }
  169. if (_libraryManager.IsScanRunning)
  170. {
  171. return ;
  172. }
  173. var seriesList = _libraryManager.GetItemList(new InternalItemsQuery()
  174. {
  175. IncludeItemTypes = new[] { typeof(Series).Name },
  176. Recursive = true
  177. }).Cast<Series>().ToList();
  178. var seriesGroups = SeriesPostScanTask.FindSeriesGroups(seriesList).Where(g => !string.IsNullOrEmpty(g.Key)).ToList();
  179. await new MissingEpisodeProvider(_logger, _config, _libraryManager, _localization, _fileSystem)
  180. .Run(seriesGroups, false, CancellationToken.None).ConfigureAwait(false);
  181. }
  182. private bool FilterItem(BaseItem item)
  183. {
  184. return item is Episode && item.LocationType != LocationType.Virtual;
  185. }
  186. /// <summary>
  187. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  188. /// </summary>
  189. public void Dispose()
  190. {
  191. Dispose(true);
  192. }
  193. /// <summary>
  194. /// Releases unmanaged and - optionally - managed resources.
  195. /// </summary>
  196. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  197. protected virtual void Dispose(bool dispose)
  198. {
  199. if (dispose)
  200. {
  201. if (LibraryUpdateTimer != null)
  202. {
  203. LibraryUpdateTimer.Dispose();
  204. LibraryUpdateTimer = null;
  205. }
  206. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  207. }
  208. }
  209. }
  210. }