MovieUpdatesPrescanTask.cs 9.2 KB

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