SeriesPostScanTask.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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.Controller.Entities;
  15. using MediaBrowser.Controller.Plugins;
  16. using MediaBrowser.Model.Tasks;
  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 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. return new MissingEpisodeProvider(_logger, _config, _libraryManager, _localization, _fileSystem).Run(seriesGroups, true, cancellationToken);
  55. }
  56. internal static IEnumerable<IGrouping<string, Series>> FindSeriesGroups(List<Series> seriesList)
  57. {
  58. var links = seriesList.ToDictionary(s => s, s => seriesList.Where(c => c != s && ShareProviderId(s, c)).ToList());
  59. var visited = new HashSet<Series>();
  60. foreach (var series in seriesList)
  61. {
  62. if (!visited.Contains(series))
  63. {
  64. var group = new SeriesGroup();
  65. FindAllLinked(series, visited, links, group);
  66. group.Key = group.Select(s => s.GetProviderId(MetadataProviders.Tvdb)).FirstOrDefault(id => !string.IsNullOrEmpty(id));
  67. yield return group;
  68. }
  69. }
  70. }
  71. private static void FindAllLinked(Series series, HashSet<Series> visited, IDictionary<Series, List<Series>> linksMap, List<Series> results)
  72. {
  73. results.Add(series);
  74. visited.Add(series);
  75. var links = linksMap[series];
  76. foreach (var s in links)
  77. {
  78. if (!visited.Contains(s))
  79. {
  80. FindAllLinked(s, visited, linksMap, results);
  81. }
  82. }
  83. }
  84. private static bool ShareProviderId(Series a, Series b)
  85. {
  86. return a.ProviderIds.Any(id =>
  87. {
  88. string value;
  89. return b.ProviderIds.TryGetValue(id.Key, out value) && id.Value == value;
  90. });
  91. }
  92. public int Order
  93. {
  94. get
  95. {
  96. // Run after tvdb update task
  97. return 1;
  98. }
  99. }
  100. }
  101. public class CleanMissingEpisodesEntryPoint : IServerEntryPoint
  102. {
  103. private readonly ILibraryManager _libraryManager;
  104. private readonly IServerConfigurationManager _config;
  105. private readonly ILogger _logger;
  106. private readonly ILocalizationManager _localization;
  107. private readonly IFileSystem _fileSystem;
  108. private readonly object _libraryChangedSyncLock = new object();
  109. private const int LibraryUpdateDuration = 180000;
  110. private readonly ITaskManager _taskManager;
  111. public CleanMissingEpisodesEntryPoint(ILibraryManager libraryManager, IServerConfigurationManager config, ILogger logger, ILocalizationManager localization, IFileSystem fileSystem, ITaskManager taskManager)
  112. {
  113. _libraryManager = libraryManager;
  114. _config = config;
  115. _logger = logger;
  116. _localization = localization;
  117. _fileSystem = fileSystem;
  118. _taskManager = taskManager;
  119. }
  120. private Timer LibraryUpdateTimer { get; set; }
  121. public void Run()
  122. {
  123. _libraryManager.ItemAdded += _libraryManager_ItemAdded;
  124. }
  125. private void _libraryManager_ItemAdded(object sender, ItemChangeEventArgs e)
  126. {
  127. if (!FilterItem(e.Item))
  128. {
  129. return;
  130. }
  131. lock (_libraryChangedSyncLock)
  132. {
  133. if (LibraryUpdateTimer == null)
  134. {
  135. LibraryUpdateTimer = new Timer(LibraryUpdateTimerCallback, null, LibraryUpdateDuration, Timeout.Infinite);
  136. }
  137. else
  138. {
  139. LibraryUpdateTimer.Change(LibraryUpdateDuration, Timeout.Infinite);
  140. }
  141. }
  142. }
  143. private async void LibraryUpdateTimerCallback(object state)
  144. {
  145. try
  146. {
  147. if (MissingEpisodeProvider.IsRunning)
  148. {
  149. return;
  150. }
  151. if (_libraryManager.IsScanRunning)
  152. {
  153. return;
  154. }
  155. var seriesList = _libraryManager.GetItemList(new InternalItemsQuery()
  156. {
  157. IncludeItemTypes = new[] { typeof(Series).Name },
  158. Recursive = true,
  159. GroupByPresentationUniqueKey = false
  160. }).Cast<Series>().ToList();
  161. var seriesGroups = SeriesPostScanTask.FindSeriesGroups(seriesList).Where(g => !string.IsNullOrEmpty(g.Key)).ToList();
  162. await new MissingEpisodeProvider(_logger, _config, _libraryManager, _localization, _fileSystem)
  163. .Run(seriesGroups, false, CancellationToken.None).ConfigureAwait(false);
  164. }
  165. catch (Exception ex)
  166. {
  167. _logger.ErrorException("Error in SeriesPostScanTask", ex);
  168. }
  169. }
  170. private bool FilterItem(BaseItem item)
  171. {
  172. return item is Episode && item.LocationType != LocationType.Virtual;
  173. }
  174. /// <summary>
  175. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  176. /// </summary>
  177. public void Dispose()
  178. {
  179. Dispose(true);
  180. }
  181. /// <summary>
  182. /// Releases unmanaged and - optionally - managed resources.
  183. /// </summary>
  184. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  185. protected virtual void Dispose(bool dispose)
  186. {
  187. if (dispose)
  188. {
  189. if (LibraryUpdateTimer != null)
  190. {
  191. LibraryUpdateTimer.Dispose();
  192. LibraryUpdateTimer = null;
  193. }
  194. _libraryManager.ItemAdded -= _libraryManager_ItemAdded;
  195. }
  196. }
  197. }
  198. }