TvdbPrescanTask.cs 12 KB

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