TvdbPrescanTask.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Net;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Xml;
  18. using CommonIO;
  19. namespace MediaBrowser.Providers.TV
  20. {
  21. /// <summary>
  22. /// Class TvdbPrescanTask
  23. /// </summary>
  24. public class TvdbPrescanTask : ILibraryPostScanTask
  25. {
  26. /// <summary>
  27. /// The server time URL
  28. /// </summary>
  29. private const string ServerTimeUrl = "http://thetvdb.com/api/Updates.php?type=none";
  30. /// <summary>
  31. /// The updates URL
  32. /// </summary>
  33. private const string UpdatesUrl = "http://thetvdb.com/api/Updates.php?type=all&time={0}";
  34. /// <summary>
  35. /// The _HTTP client
  36. /// </summary>
  37. private readonly IHttpClient _httpClient;
  38. /// <summary>
  39. /// The _logger
  40. /// </summary>
  41. private readonly ILogger _logger;
  42. /// <summary>
  43. /// The _config
  44. /// </summary>
  45. private readonly IServerConfigurationManager _config;
  46. private readonly IFileSystem _fileSystem;
  47. private readonly ILibraryManager _libraryManager;
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="TvdbPrescanTask"/> class.
  50. /// </summary>
  51. /// <param name="logger">The logger.</param>
  52. /// <param name="httpClient">The HTTP client.</param>
  53. /// <param name="config">The config.</param>
  54. public TvdbPrescanTask(ILogger logger, IHttpClient httpClient, IServerConfigurationManager config, IFileSystem fileSystem, ILibraryManager libraryManager)
  55. {
  56. _logger = logger;
  57. _httpClient = httpClient;
  58. _config = config;
  59. _fileSystem = fileSystem;
  60. _libraryManager = libraryManager;
  61. }
  62. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  63. /// <summary>
  64. /// Runs the specified progress.
  65. /// </summary>
  66. /// <param name="progress">The progress.</param>
  67. /// <param name="cancellationToken">The cancellation token.</param>
  68. /// <returns>Task.</returns>
  69. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  70. {
  71. if (!_config.Configuration.EnableInternetProviders)
  72. {
  73. progress.Report(100);
  74. return;
  75. }
  76. var seriesConfig = _config.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, typeof(Series).Name, StringComparison.OrdinalIgnoreCase));
  77. if (seriesConfig != null && seriesConfig.DisabledMetadataFetchers.Contains(TvdbSeriesProvider.Current.Name, StringComparer.OrdinalIgnoreCase))
  78. {
  79. progress.Report(100);
  80. return;
  81. }
  82. var path = TvdbSeriesProvider.GetSeriesDataPath(_config.CommonApplicationPaths);
  83. _fileSystem.CreateDirectory(path);
  84. var timestampFile = Path.Combine(path, "time.txt");
  85. var timestampFileInfo = _fileSystem.GetFileInfo(timestampFile);
  86. // Don't check for tvdb updates anymore frequently than 24 hours
  87. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 1)
  88. {
  89. return;
  90. }
  91. // Find out the last time we queried tvdb for updates
  92. var lastUpdateTime = timestampFileInfo.Exists ? _fileSystem.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  93. string newUpdateTime;
  94. var existingDirectories = Directory.EnumerateDirectories(path)
  95. .Select(Path.GetFileName)
  96. .ToList();
  97. var seriesIdsInLibrary = _libraryManager.RootFolder
  98. .GetRecursiveChildren(i => i is Series && !string.IsNullOrEmpty(i.GetProviderId(MetadataProviders.Tvdb)))
  99. .Cast<Series>()
  100. .Select(i => i.GetProviderId(MetadataProviders.Tvdb))
  101. .ToList();
  102. var missingSeries = seriesIdsInLibrary.Except(existingDirectories, StringComparer.OrdinalIgnoreCase)
  103. .ToList();
  104. // If this is our first time, update all series
  105. if (string.IsNullOrEmpty(lastUpdateTime))
  106. {
  107. // First get tvdb server time
  108. using (var stream = await _httpClient.Get(new HttpRequestOptions
  109. {
  110. Url = ServerTimeUrl,
  111. CancellationToken = cancellationToken,
  112. EnableHttpCompression = true,
  113. ResourcePool = TvdbSeriesProvider.Current.TvDbResourcePool
  114. }).ConfigureAwait(false))
  115. {
  116. newUpdateTime = GetUpdateTime(stream);
  117. }
  118. existingDirectories.AddRange(missingSeries);
  119. await UpdateSeries(existingDirectories, path, null, progress, cancellationToken).ConfigureAwait(false);
  120. }
  121. else
  122. {
  123. var seriesToUpdate = await GetSeriesIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);
  124. newUpdateTime = seriesToUpdate.Item2;
  125. long lastUpdateValue;
  126. long.TryParse(lastUpdateTime, NumberStyles.Any, UsCulture, out lastUpdateValue);
  127. var nullableUpdateValue = lastUpdateValue == 0 ? (long?)null : lastUpdateValue;
  128. var listToUpdate = seriesToUpdate.Item1.ToList();
  129. listToUpdate.AddRange(missingSeries);
  130. await UpdateSeries(listToUpdate, path, nullableUpdateValue, progress, cancellationToken).ConfigureAwait(false);
  131. }
  132. _fileSystem.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  133. progress.Report(100);
  134. }
  135. /// <summary>
  136. /// Gets the update time.
  137. /// </summary>
  138. /// <param name="response">The response.</param>
  139. /// <returns>System.String.</returns>
  140. private string GetUpdateTime(Stream response)
  141. {
  142. var settings = new XmlReaderSettings
  143. {
  144. CheckCharacters = false,
  145. IgnoreProcessingInstructions = true,
  146. IgnoreComments = true,
  147. ValidationType = ValidationType.None
  148. };
  149. using (var streamReader = new StreamReader(response, Encoding.UTF8))
  150. {
  151. // Use XmlReader for best performance
  152. using (var reader = XmlReader.Create(streamReader, settings))
  153. {
  154. reader.MoveToContent();
  155. // Loop through each element
  156. while (reader.Read())
  157. {
  158. if (reader.NodeType == XmlNodeType.Element)
  159. {
  160. switch (reader.Name)
  161. {
  162. case "Time":
  163. {
  164. return (reader.ReadElementContentAsString() ?? string.Empty).Trim();
  165. }
  166. default:
  167. reader.Skip();
  168. break;
  169. }
  170. }
  171. }
  172. }
  173. }
  174. return null;
  175. }
  176. /// <summary>
  177. /// Gets the series ids to update.
  178. /// </summary>
  179. /// <param name="existingSeriesIds">The existing series ids.</param>
  180. /// <param name="lastUpdateTime">The last update time.</param>
  181. /// <param name="cancellationToken">The cancellation token.</param>
  182. /// <returns>Task{IEnumerable{System.String}}.</returns>
  183. private async Task<Tuple<IEnumerable<string>, string>> GetSeriesIdsToUpdate(IEnumerable<string> existingSeriesIds, string lastUpdateTime, CancellationToken cancellationToken)
  184. {
  185. // First get last time
  186. using (var stream = await _httpClient.Get(new HttpRequestOptions
  187. {
  188. Url = string.Format(UpdatesUrl, lastUpdateTime),
  189. CancellationToken = cancellationToken,
  190. EnableHttpCompression = true,
  191. ResourcePool = TvdbSeriesProvider.Current.TvDbResourcePool
  192. }).ConfigureAwait(false))
  193. {
  194. var data = GetUpdatedSeriesIdList(stream);
  195. var existingDictionary = existingSeriesIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  196. var seriesList = data.Item1
  197. .Where(i => !string.IsNullOrWhiteSpace(i) && existingDictionary.ContainsKey(i));
  198. return new Tuple<IEnumerable<string>, string>(seriesList, data.Item2);
  199. }
  200. }
  201. private Tuple<List<string>, string> GetUpdatedSeriesIdList(Stream stream)
  202. {
  203. string updateTime = null;
  204. var idList = new List<string>();
  205. var settings = new XmlReaderSettings
  206. {
  207. CheckCharacters = false,
  208. IgnoreProcessingInstructions = true,
  209. IgnoreComments = true,
  210. ValidationType = ValidationType.None
  211. };
  212. using (var streamReader = new StreamReader(stream, Encoding.UTF8))
  213. {
  214. // Use XmlReader for best performance
  215. using (var reader = XmlReader.Create(streamReader, settings))
  216. {
  217. reader.MoveToContent();
  218. // Loop through each element
  219. while (reader.Read())
  220. {
  221. if (reader.NodeType == XmlNodeType.Element)
  222. {
  223. switch (reader.Name)
  224. {
  225. case "Time":
  226. {
  227. updateTime = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
  228. break;
  229. }
  230. case "Series":
  231. {
  232. var id = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
  233. idList.Add(id);
  234. break;
  235. }
  236. default:
  237. reader.Skip();
  238. break;
  239. }
  240. }
  241. }
  242. }
  243. }
  244. return new Tuple<List<string>, string>(idList, updateTime);
  245. }
  246. /// <summary>
  247. /// Updates the series.
  248. /// </summary>
  249. /// <param name="seriesIds">The series ids.</param>
  250. /// <param name="seriesDataPath">The series data path.</param>
  251. /// <param name="lastTvDbUpdateTime">The last tv db update time.</param>
  252. /// <param name="progress">The progress.</param>
  253. /// <param name="cancellationToken">The cancellation token.</param>
  254. /// <returns>Task.</returns>
  255. private async Task UpdateSeries(IEnumerable<string> seriesIds, string seriesDataPath, long? lastTvDbUpdateTime, IProgress<double> progress, CancellationToken cancellationToken)
  256. {
  257. var list = seriesIds.ToList();
  258. var numComplete = 0;
  259. // Gather all series into a lookup by tvdb id
  260. var allSeries = _libraryManager.RootFolder
  261. .GetRecursiveChildren(i => i is Series && !string.IsNullOrEmpty(i.GetProviderId(MetadataProviders.Tvdb)))
  262. .Cast<Series>()
  263. .ToLookup(i => i.GetProviderId(MetadataProviders.Tvdb));
  264. foreach (var seriesId in list)
  265. {
  266. // Find the preferred language(s) for the movie in the library
  267. var languages = allSeries[seriesId]
  268. .Select(i => i.GetPreferredMetadataLanguage())
  269. .Distinct(StringComparer.OrdinalIgnoreCase)
  270. .ToList();
  271. foreach (var language in languages)
  272. {
  273. try
  274. {
  275. await UpdateSeries(seriesId, seriesDataPath, lastTvDbUpdateTime, language, cancellationToken).ConfigureAwait(false);
  276. }
  277. catch (HttpException ex)
  278. {
  279. _logger.ErrorException("Error updating tvdb series id {0}, language {1}", ex, seriesId, language);
  280. // Already logged at lower levels, but don't fail the whole operation, unless timed out
  281. // We have to fail this to make it run again otherwise new episode data could potentially be missing
  282. if (ex.IsTimedOut)
  283. {
  284. throw;
  285. }
  286. }
  287. }
  288. numComplete++;
  289. double percent = numComplete;
  290. percent /= list.Count;
  291. percent *= 100;
  292. progress.Report(percent);
  293. }
  294. }
  295. /// <summary>
  296. /// Updates the series.
  297. /// </summary>
  298. /// <param name="id">The id.</param>
  299. /// <param name="seriesDataPath">The series data path.</param>
  300. /// <param name="lastTvDbUpdateTime">The last tv db update time.</param>
  301. /// <param name="preferredMetadataLanguage">The preferred metadata language.</param>
  302. /// <param name="cancellationToken">The cancellation token.</param>
  303. /// <returns>Task.</returns>
  304. private Task UpdateSeries(string id, string seriesDataPath, long? lastTvDbUpdateTime, string preferredMetadataLanguage, CancellationToken cancellationToken)
  305. {
  306. _logger.Info("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage);
  307. seriesDataPath = Path.Combine(seriesDataPath, id);
  308. _fileSystem.CreateDirectory(seriesDataPath);
  309. return TvdbSeriesProvider.Current.DownloadSeriesZip(id, MetadataProviders.Tvdb.ToString(), seriesDataPath, lastTvDbUpdateTime, preferredMetadataLanguage, cancellationToken);
  310. }
  311. }
  312. }