MovieUpdatesPrescanTask.cs 9.2 KB

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