PersonUpdatesPreScanTask.cs 8.2 KB

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