TvdbPrescanTask.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 path = TvdbSeriesProvider.GetSeriesDataPath(_config.CommonApplicationPaths);
  76. Directory.CreateDirectory(path);
  77. var timestampFile = Path.Combine(path, "time.txt");
  78. var timestampFileInfo = new FileInfo(timestampFile);
  79. // Don't check for tvdb updates anymore frequently than 24 hours
  80. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 1)
  81. {
  82. return;
  83. }
  84. // Find out the last time we queried tvdb for updates
  85. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  86. string newUpdateTime;
  87. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  88. // If this is our first time, update all series
  89. if (string.IsNullOrEmpty(lastUpdateTime))
  90. {
  91. // First get tvdb server time
  92. using (var stream = await _httpClient.Get(new HttpRequestOptions
  93. {
  94. Url = ServerTimeUrl,
  95. CancellationToken = cancellationToken,
  96. EnableHttpCompression = true,
  97. ResourcePool = TvdbSeriesProvider.Current.TvDbResourcePool
  98. }).ConfigureAwait(false))
  99. {
  100. newUpdateTime = GetUpdateTime(stream);
  101. }
  102. await UpdateSeries(existingDirectories, path, null, progress, cancellationToken).ConfigureAwait(false);
  103. }
  104. else
  105. {
  106. var seriesToUpdate = await GetSeriesIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);
  107. newUpdateTime = seriesToUpdate.Item2;
  108. long lastUpdateValue;
  109. long.TryParse(lastUpdateTime, NumberStyles.Any, UsCulture, out lastUpdateValue);
  110. var nullableUpdateValue = lastUpdateValue == 0 ? (long?)null : lastUpdateValue;
  111. await UpdateSeries(seriesToUpdate.Item1, path, nullableUpdateValue, progress, cancellationToken).ConfigureAwait(false);
  112. }
  113. File.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  114. progress.Report(100);
  115. }
  116. /// <summary>
  117. /// Gets the update time.
  118. /// </summary>
  119. /// <param name="response">The response.</param>
  120. /// <returns>System.String.</returns>
  121. private string GetUpdateTime(Stream response)
  122. {
  123. var settings = new XmlReaderSettings
  124. {
  125. CheckCharacters = false,
  126. IgnoreProcessingInstructions = true,
  127. IgnoreComments = true,
  128. ValidationType = ValidationType.None
  129. };
  130. using (var streamReader = new StreamReader(response, Encoding.UTF8))
  131. {
  132. // Use XmlReader for best performance
  133. using (var reader = XmlReader.Create(streamReader, settings))
  134. {
  135. reader.MoveToContent();
  136. // Loop through each element
  137. while (reader.Read())
  138. {
  139. if (reader.NodeType == XmlNodeType.Element)
  140. {
  141. switch (reader.Name)
  142. {
  143. case "Time":
  144. {
  145. return (reader.ReadElementContentAsString() ?? string.Empty).Trim();
  146. }
  147. default:
  148. reader.Skip();
  149. break;
  150. }
  151. }
  152. }
  153. }
  154. }
  155. return null;
  156. }
  157. /// <summary>
  158. /// Gets the series ids to update.
  159. /// </summary>
  160. /// <param name="existingSeriesIds">The existing series ids.</param>
  161. /// <param name="lastUpdateTime">The last update time.</param>
  162. /// <param name="cancellationToken">The cancellation token.</param>
  163. /// <returns>Task{IEnumerable{System.String}}.</returns>
  164. private async Task<Tuple<IEnumerable<string>, string>> GetSeriesIdsToUpdate(IEnumerable<string> existingSeriesIds, string lastUpdateTime, CancellationToken cancellationToken)
  165. {
  166. // First get last time
  167. using (var stream = await _httpClient.Get(new HttpRequestOptions
  168. {
  169. Url = string.Format(UpdatesUrl, lastUpdateTime),
  170. CancellationToken = cancellationToken,
  171. EnableHttpCompression = true,
  172. ResourcePool = TvdbSeriesProvider.Current.TvDbResourcePool
  173. }).ConfigureAwait(false))
  174. {
  175. var data = GetUpdatedSeriesIdList(stream);
  176. var existingDictionary = existingSeriesIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  177. var seriesList = data.Item1
  178. .Where(i => !string.IsNullOrWhiteSpace(i) && existingDictionary.ContainsKey(i));
  179. return new Tuple<IEnumerable<string>, string>(seriesList, data.Item2);
  180. }
  181. }
  182. private Tuple<List<string>, string> GetUpdatedSeriesIdList(Stream stream)
  183. {
  184. string updateTime = null;
  185. var idList = new List<string>();
  186. var settings = new XmlReaderSettings
  187. {
  188. CheckCharacters = false,
  189. IgnoreProcessingInstructions = true,
  190. IgnoreComments = true,
  191. ValidationType = ValidationType.None
  192. };
  193. using (var streamReader = new StreamReader(stream, Encoding.UTF8))
  194. {
  195. // Use XmlReader for best performance
  196. using (var reader = XmlReader.Create(streamReader, settings))
  197. {
  198. reader.MoveToContent();
  199. // Loop through each element
  200. while (reader.Read())
  201. {
  202. if (reader.NodeType == XmlNodeType.Element)
  203. {
  204. switch (reader.Name)
  205. {
  206. case "Time":
  207. {
  208. updateTime = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
  209. break;
  210. }
  211. case "Series":
  212. {
  213. var id = (reader.ReadElementContentAsString() ?? string.Empty).Trim();
  214. idList.Add(id);
  215. break;
  216. }
  217. default:
  218. reader.Skip();
  219. break;
  220. }
  221. }
  222. }
  223. }
  224. }
  225. return new Tuple<List<string>, string>(idList, updateTime);
  226. }
  227. /// <summary>
  228. /// Updates the series.
  229. /// </summary>
  230. /// <param name="seriesIds">The series ids.</param>
  231. /// <param name="seriesDataPath">The series data path.</param>
  232. /// <param name="lastTvDbUpdateTime">The last tv db update time.</param>
  233. /// <param name="progress">The progress.</param>
  234. /// <param name="cancellationToken">The cancellation token.</param>
  235. /// <returns>Task.</returns>
  236. private async Task UpdateSeries(IEnumerable<string> seriesIds, string seriesDataPath, long? lastTvDbUpdateTime, IProgress<double> progress, CancellationToken cancellationToken)
  237. {
  238. var list = seriesIds.ToList();
  239. var numComplete = 0;
  240. // Gather all series into a lookup by tvdb id
  241. var allSeries = _libraryManager.RootFolder.RecursiveChildren
  242. .OfType<Series>()
  243. .Where(i => !string.IsNullOrEmpty(i.GetProviderId(MetadataProviders.Tvdb)))
  244. .ToLookup(i => i.GetProviderId(MetadataProviders.Tvdb));
  245. foreach (var seriesId in list)
  246. {
  247. // Find the preferred language(s) for the movie in the library
  248. var languages = allSeries[seriesId]
  249. .Select(i => i.GetPreferredMetadataLanguage())
  250. .Distinct(StringComparer.OrdinalIgnoreCase)
  251. .ToList();
  252. foreach (var language in languages)
  253. {
  254. try
  255. {
  256. await UpdateSeries(seriesId, seriesDataPath, lastTvDbUpdateTime, language, cancellationToken).ConfigureAwait(false);
  257. }
  258. catch (HttpException ex)
  259. {
  260. _logger.ErrorException("Error updating tvdb series id {0}, language {1}", ex, seriesId, language);
  261. // Already logged at lower levels, but don't fail the whole operation, unless timed out
  262. // We have to fail this to make it run again otherwise new episode data could potentially be missing
  263. if (ex.IsTimedOut)
  264. {
  265. throw;
  266. }
  267. }
  268. }
  269. numComplete++;
  270. double percent = numComplete;
  271. percent /= list.Count;
  272. percent *= 100;
  273. progress.Report(percent);
  274. }
  275. }
  276. /// <summary>
  277. /// Updates the series.
  278. /// </summary>
  279. /// <param name="id">The id.</param>
  280. /// <param name="seriesDataPath">The series data path.</param>
  281. /// <param name="lastTvDbUpdateTime">The last tv db update time.</param>
  282. /// <param name="preferredMetadataLanguage">The preferred metadata language.</param>
  283. /// <param name="cancellationToken">The cancellation token.</param>
  284. /// <returns>Task.</returns>
  285. private Task UpdateSeries(string id, string seriesDataPath, long? lastTvDbUpdateTime, string preferredMetadataLanguage, CancellationToken cancellationToken)
  286. {
  287. _logger.Info("Updating series from tvdb " + id + ", language " + preferredMetadataLanguage);
  288. seriesDataPath = Path.Combine(seriesDataPath, id);
  289. Directory.CreateDirectory(seriesDataPath);
  290. return TvdbSeriesProvider.Current.DownloadSeriesZip(id, seriesDataPath, lastTvDbUpdateTime, preferredMetadataLanguage, cancellationToken);
  291. }
  292. }
  293. }