MovieUpdatesPrescanTask.cs 9.1 KB

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