TvdbPrescanTask.cs 14 KB

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