TvdbPrescanTask.cs 12 KB

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