PersonUpdatesPreScanTask.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  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 PersonUpdatesPreScanTask : IPeoplePrescanTask
  18. {
  19. /// <summary>
  20. /// The updates URL
  21. /// </summary>
  22. private const string UpdatesUrl = "http://api.themoviedb.org/3/person/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. private readonly IFileSystem _fileSystem;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="PersonUpdatesPreScanTask"/> class.
  39. /// </summary>
  40. /// <param name="logger">The logger.</param>
  41. /// <param name="httpClient">The HTTP client.</param>
  42. /// <param name="config">The config.</param>
  43. public PersonUpdatesPreScanTask(ILogger logger, IHttpClient httpClient, IServerConfigurationManager config, IJsonSerializer json, IFileSystem fileSystem)
  44. {
  45. _logger = logger;
  46. _httpClient = httpClient;
  47. _config = config;
  48. _json = json;
  49. _fileSystem = fileSystem;
  50. }
  51. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  52. /// <summary>
  53. /// Runs the specified progress.
  54. /// </summary>
  55. /// <param name="progress">The progress.</param>
  56. /// <param name="cancellationToken">The cancellation token.</param>
  57. /// <returns>Task.</returns>
  58. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  59. {
  60. if (!_config.Configuration.EnableInternetProviders || !_config.Configuration.EnableTmdbUpdates)
  61. {
  62. progress.Report(100);
  63. return;
  64. }
  65. var path = MovieDbPersonProvider.GetPersonsDataPath(_config.CommonApplicationPaths);
  66. Directory.CreateDirectory(path);
  67. var timestampFile = Path.Combine(path, "time.txt");
  68. var timestampFileInfo = new FileInfo(timestampFile);
  69. // Don't check for updates every single time
  70. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 3)
  71. {
  72. return;
  73. }
  74. // Find out the last time we queried tvdb for updates
  75. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  76. var existingDirectories = GetExistingIds(path).ToList();
  77. if (!string.IsNullOrEmpty(lastUpdateTime))
  78. {
  79. long lastUpdateTicks;
  80. if (long.TryParse(lastUpdateTime, NumberStyles.Any, UsCulture, out lastUpdateTicks))
  81. {
  82. var lastUpdateDate = new DateTime(lastUpdateTicks, DateTimeKind.Utc);
  83. // They only allow up to 14 days of updates
  84. if ((DateTime.UtcNow - lastUpdateDate).TotalDays > 13)
  85. {
  86. lastUpdateDate = DateTime.UtcNow.AddDays(-13);
  87. }
  88. var updatedIds = await GetIdsToUpdate(lastUpdateDate, 1, cancellationToken).ConfigureAwait(false);
  89. var existingDictionary = existingDirectories.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  90. var idsToUpdate = updatedIds.Where(i => !string.IsNullOrWhiteSpace(i) && existingDictionary.ContainsKey(i));
  91. await UpdatePeople(idsToUpdate, progress, cancellationToken).ConfigureAwait(false);
  92. }
  93. }
  94. File.WriteAllText(timestampFile, DateTime.UtcNow.Ticks.ToString(UsCulture), Encoding.UTF8);
  95. progress.Report(100);
  96. }
  97. /// <summary>
  98. /// Gets the existing ids.
  99. /// </summary>
  100. /// <param name="path">The path.</param>
  101. /// <returns>IEnumerable{System.String}.</returns>
  102. private IEnumerable<string> GetExistingIds(string path)
  103. {
  104. return Directory.EnumerateDirectories(path)
  105. .SelectMany(Directory.EnumerateDirectories)
  106. .Select(Path.GetFileNameWithoutExtension);
  107. }
  108. /// <summary>
  109. /// Gets the ids to update.
  110. /// </summary>
  111. /// <param name="lastUpdateTime">The last update time.</param>
  112. /// <param name="page">The page.</param>
  113. /// <param name="cancellationToken">The cancellation token.</param>
  114. /// <returns>Task{IEnumerable{System.String}}.</returns>
  115. private async Task<IEnumerable<string>> GetIdsToUpdate(DateTime lastUpdateTime, int page, CancellationToken cancellationToken)
  116. {
  117. var hasMorePages = false;
  118. var list = new List<string>();
  119. // First get last time
  120. using (var stream = await _httpClient.Get(new HttpRequestOptions
  121. {
  122. Url = string.Format(UpdatesUrl, lastUpdateTime.ToString("yyyy-MM-dd"), MovieDbProvider.ApiKey, page),
  123. CancellationToken = cancellationToken,
  124. EnableHttpCompression = true,
  125. ResourcePool = MovieDbProvider.Current.MovieDbResourcePool,
  126. AcceptHeader = MovieDbProvider.AcceptHeader
  127. }).ConfigureAwait(false))
  128. {
  129. var obj = _json.DeserializeFromStream<RootObject>(stream);
  130. var data = obj.results.Select(i => i.id.ToString(UsCulture));
  131. list.AddRange(data);
  132. hasMorePages = page < obj.total_pages;
  133. }
  134. if (hasMorePages)
  135. {
  136. var more = await GetIdsToUpdate(lastUpdateTime, page + 1, cancellationToken).ConfigureAwait(false);
  137. list.AddRange(more);
  138. }
  139. return list;
  140. }
  141. /// <summary>
  142. /// Updates the people.
  143. /// </summary>
  144. /// <param name="ids">The ids.</param>
  145. /// <param name="progress">The progress.</param>
  146. /// <param name="cancellationToken">The cancellation token.</param>
  147. /// <returns>Task.</returns>
  148. private async Task UpdatePeople(IEnumerable<string> ids, IProgress<double> progress, CancellationToken cancellationToken)
  149. {
  150. var list = ids.ToList();
  151. var numComplete = 0;
  152. foreach (var id in list)
  153. {
  154. try
  155. {
  156. await UpdatePerson(id, cancellationToken).ConfigureAwait(false);
  157. }
  158. catch (Exception ex)
  159. {
  160. _logger.ErrorException("Error updating tmdb person id {0}", ex, id);
  161. }
  162. numComplete++;
  163. double percent = numComplete;
  164. percent /= list.Count;
  165. percent *= 100;
  166. progress.Report(percent);
  167. }
  168. }
  169. /// <summary>
  170. /// Updates the person.
  171. /// </summary>
  172. /// <param name="id">The id.</param>
  173. /// <param name="cancellationToken">The cancellation token.</param>
  174. /// <returns>Task.</returns>
  175. private Task UpdatePerson(string id, CancellationToken cancellationToken)
  176. {
  177. _logger.Info("Updating person from tmdb " + id);
  178. return MovieDbPersonProvider.Current.DownloadPersonInfo(id, cancellationToken);
  179. }
  180. class Result
  181. {
  182. public int id { get; set; }
  183. public bool? adult { get; set; }
  184. }
  185. class RootObject
  186. {
  187. public List<Result> results { get; set; }
  188. public int page { get; set; }
  189. public int total_pages { get; set; }
  190. public int total_results { get; set; }
  191. public RootObject()
  192. {
  193. results = new List<Result>();
  194. }
  195. }
  196. }
  197. }