SeriesPostScanTask.cs 8.4 KB

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