MovieUpdatesPrescanTask.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Common.Progress;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Providers.Movies
  16. {
  17. public class MovieUpdatesPreScanTask : ILibraryPrescanTask
  18. {
  19. /// <summary>
  20. /// The updates URL
  21. /// </summary>
  22. private const string UpdatesUrl = "http://api.themoviedb.org/3/movie/changes?start_date={0}&api_key={1}&page={2}";
  23. /// <summary>
  24. /// The _HTTP client
  25. /// </summary>
  26. private readonly IHttpClient _httpClient;
  27. /// <summary>
  28. /// The _logger
  29. /// </summary>
  30. private readonly ILogger _logger;
  31. /// <summary>
  32. /// The _config
  33. /// </summary>
  34. private readonly IServerConfigurationManager _config;
  35. private readonly IJsonSerializer _json;
  36. /// <summary>
  37. /// Initializes a new instance of the <see cref="MovieUpdatesPreScanTask"/> class.
  38. /// </summary>
  39. /// <param name="logger">The logger.</param>
  40. /// <param name="httpClient">The HTTP client.</param>
  41. /// <param name="config">The config.</param>
  42. /// <param name="json">The json.</param>
  43. public MovieUpdatesPreScanTask(ILogger logger, IHttpClient httpClient, IServerConfigurationManager config, IJsonSerializer json)
  44. {
  45. _logger = logger;
  46. _httpClient = httpClient;
  47. _config = config;
  48. _json = json;
  49. }
  50. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  51. /// <summary>
  52. /// Runs the specified progress.
  53. /// </summary>
  54. /// <param name="progress">The progress.</param>
  55. /// <param name="cancellationToken">The cancellation token.</param>
  56. /// <returns>Task.</returns>
  57. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  58. {
  59. if (!_config.Configuration.EnableInternetProviders || !_config.Configuration.EnableTmdbUpdates)
  60. {
  61. progress.Report(100);
  62. return;
  63. }
  64. var innerProgress = new ActionableProgress<double>();
  65. innerProgress.RegisterAction(pct => progress.Report(pct * .8));
  66. await Run(innerProgress, false, cancellationToken).ConfigureAwait(false);
  67. progress.Report(80);
  68. //innerProgress = new ActionableProgress<double>();
  69. //innerProgress.RegisterAction(pct => progress.Report(80 + pct * .2));
  70. //await Run(innerProgress, true, cancellationToken).ConfigureAwait(false);
  71. progress.Report(100);
  72. }
  73. /// <summary>
  74. /// Runs the specified progress.
  75. /// </summary>
  76. /// <param name="progress">The progress.</param>
  77. /// <param name="runForBoxSets">if set to <c>true</c> [run for box sets].</param>
  78. /// <param name="cancellationToken">The cancellation token.</param>
  79. /// <returns>Task.</returns>
  80. private async Task Run(IProgress<double> progress, bool runForBoxSets, CancellationToken cancellationToken)
  81. {
  82. var path = runForBoxSets ? MovieDbProvider.GetBoxSetsDataPath(_config.CommonApplicationPaths) : MovieDbProvider.GetMoviesDataPath(_config.CommonApplicationPaths);
  83. Directory.CreateDirectory(path);
  84. var timestampFile = Path.Combine(path, "time.txt");
  85. var timestampFileInfo = new FileInfo(timestampFile);
  86. // Don't check for tvdb updates anymore frequently than 24 hours
  87. if (timestampFileInfo.Exists && (DateTime.UtcNow - timestampFileInfo.LastWriteTimeUtc).TotalDays < 1)
  88. {
  89. return;
  90. }
  91. // Find out the last time we queried tvdb for updates
  92. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  93. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  94. if (!string.IsNullOrEmpty(lastUpdateTime))
  95. {
  96. long lastUpdateTicks;
  97. if (long.TryParse(lastUpdateTime, NumberStyles.Any, UsCulture, out lastUpdateTicks))
  98. {
  99. var lastUpdateDate = new DateTime(lastUpdateTicks, DateTimeKind.Utc);
  100. // They only allow up to 14 days of updates
  101. if ((DateTime.UtcNow - lastUpdateDate).TotalDays > 13)
  102. {
  103. lastUpdateDate = DateTime.UtcNow.AddDays(-13);
  104. }
  105. var updatedIds = await GetIdsToUpdate(lastUpdateDate, 1, cancellationToken).ConfigureAwait(false);
  106. var existingDictionary = existingDirectories.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  107. var idsToUpdate = updatedIds.Where(i => !string.IsNullOrWhiteSpace(i) && existingDictionary.ContainsKey(i));
  108. await UpdateMovies(idsToUpdate, runForBoxSets, path, progress, cancellationToken).ConfigureAwait(false);
  109. }
  110. }
  111. File.WriteAllText(timestampFile, DateTime.UtcNow.Ticks.ToString(UsCulture), Encoding.UTF8);
  112. progress.Report(100);
  113. }
  114. /// <summary>
  115. /// Gets the ids to update.
  116. /// </summary>
  117. /// <param name="lastUpdateTime">The last update time.</param>
  118. /// <param name="page">The page.</param>
  119. /// <param name="cancellationToken">The cancellation token.</param>
  120. /// <returns>Task{IEnumerable{System.String}}.</returns>
  121. private async Task<IEnumerable<string>> GetIdsToUpdate(DateTime lastUpdateTime, int page, CancellationToken cancellationToken)
  122. {
  123. bool hasMorePages;
  124. var list = new List<string>();
  125. // First get last time
  126. using (var stream = await _httpClient.Get(new HttpRequestOptions
  127. {
  128. Url = string.Format(UpdatesUrl, lastUpdateTime.ToString("yyyy-MM-dd"), MovieDbProvider.ApiKey, page),
  129. CancellationToken = cancellationToken,
  130. EnableHttpCompression = true,
  131. ResourcePool = MovieDbProvider.Current.MovieDbResourcePool,
  132. AcceptHeader = MovieDbProvider.AcceptHeader
  133. }).ConfigureAwait(false))
  134. {
  135. var obj = _json.DeserializeFromStream<RootObject>(stream);
  136. var data = obj.results.Select(i => i.id.ToString(UsCulture));
  137. list.AddRange(data);
  138. hasMorePages = page < obj.total_pages;
  139. }
  140. if (hasMorePages)
  141. {
  142. var more = await GetIdsToUpdate(lastUpdateTime, page + 1, cancellationToken).ConfigureAwait(false);
  143. list.AddRange(more);
  144. }
  145. return list;
  146. }
  147. /// <summary>
  148. /// Updates the movies.
  149. /// </summary>
  150. /// <param name="ids">The ids.</param>
  151. /// <param name="isBoxSet">if set to <c>true</c> [is box set].</param>
  152. /// <param name="moviesDataPath">The movies data path.</param>
  153. /// <param name="progress">The progress.</param>
  154. /// <param name="cancellationToken">The cancellation token.</param>
  155. /// <returns>Task.</returns>
  156. private async Task UpdateMovies(IEnumerable<string> ids, bool isBoxSet, string moviesDataPath, IProgress<double> progress, CancellationToken cancellationToken)
  157. {
  158. var list = ids.ToList();
  159. var numComplete = 0;
  160. foreach (var id in list)
  161. {
  162. try
  163. {
  164. await UpdateMovie(id, isBoxSet, moviesDataPath, cancellationToken).ConfigureAwait(false);
  165. }
  166. catch (Exception ex)
  167. {
  168. _logger.ErrorException("Error updating tmdb movie id {0}", ex, id);
  169. }
  170. numComplete++;
  171. double percent = numComplete;
  172. percent /= list.Count;
  173. percent *= 100;
  174. progress.Report(percent);
  175. }
  176. }
  177. /// <summary>
  178. /// Updates the movie.
  179. /// </summary>
  180. /// <param name="id">The id.</param>
  181. /// <param name="isBoxSet">if set to <c>true</c> [is box set].</param>
  182. /// <param name="dataPath">The data path.</param>
  183. /// <param name="cancellationToken">The cancellation token.</param>
  184. /// <returns>Task.</returns>
  185. private Task UpdateMovie(string id, bool isBoxSet, string dataPath, CancellationToken cancellationToken)
  186. {
  187. _logger.Info("Updating movie from tmdb " + id);
  188. var itemDataPath = Path.Combine(dataPath, id);
  189. Directory.CreateDirectory(dataPath);
  190. return MovieDbProvider.Current.DownloadMovieInfo(id, isBoxSet, itemDataPath, cancellationToken);
  191. }
  192. class Result
  193. {
  194. public int id { get; set; }
  195. public bool? adult { get; set; }
  196. }
  197. class RootObject
  198. {
  199. public List<Result> results { get; set; }
  200. public int page { get; set; }
  201. public int total_pages { get; set; }
  202. public int total_results { get; set; }
  203. public RootObject()
  204. {
  205. results = new List<Result>();
  206. }
  207. }
  208. }
  209. }