FanArtMovieUpdatesPostScanTask.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.Configuration;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using MediaBrowser.Providers.Music;
  9. using MediaBrowser.Providers.TV;
  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. class FanartMovieUpdatesPostScanTask : ILibraryPostScanTask
  22. {
  23. private const string UpdatesUrl = "http://webservice.fanart.tv/v3/movies/latest?api_key={0}&date={1}";
  24. /// <summary>
  25. /// The _HTTP client
  26. /// </summary>
  27. private readonly IHttpClient _httpClient;
  28. /// <summary>
  29. /// The _logger
  30. /// </summary>
  31. private readonly ILogger _logger;
  32. /// <summary>
  33. /// The _config
  34. /// </summary>
  35. private readonly IServerConfigurationManager _config;
  36. private readonly IJsonSerializer _jsonSerializer;
  37. private readonly IFileSystem _fileSystem;
  38. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  39. public FanartMovieUpdatesPostScanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IFileSystem fileSystem)
  40. {
  41. _jsonSerializer = jsonSerializer;
  42. _config = config;
  43. _logger = logger;
  44. _httpClient = httpClient;
  45. _fileSystem = fileSystem;
  46. }
  47. /// <summary>
  48. /// Runs the specified progress.
  49. /// </summary>
  50. /// <param name="progress">The progress.</param>
  51. /// <param name="cancellationToken">The cancellation token.</param>
  52. /// <returns>Task.</returns>
  53. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  54. {
  55. var options = FanartSeriesProvider.Current.GetFanartOptions();
  56. if (!options.EnableAutomaticUpdates)
  57. {
  58. progress.Report(100);
  59. return;
  60. }
  61. var path = FanartMovieImageProvider.GetMoviesDataPath(_config.CommonApplicationPaths);
  62. _fileSystem.CreateDirectory(path);
  63. var timestampFile = Path.Combine(path, "time.txt");
  64. var timestampFileInfo = _fileSystem.GetFileInfo(timestampFile);
  65. // Don't check for updates every single time
  66. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 3)
  67. {
  68. return;
  69. }
  70. // Find out the last time we queried for updates
  71. var lastUpdateTime = timestampFileInfo.Exists ? _fileSystem.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  72. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  73. // If this is our first time, don't do any updates and just record the timestamp
  74. if (!string.IsNullOrEmpty(lastUpdateTime))
  75. {
  76. var moviesToUpdate = await GetMovieIdsToUpdate(existingDirectories, lastUpdateTime, options, cancellationToken).ConfigureAwait(false);
  77. progress.Report(5);
  78. await UpdateMovies(moviesToUpdate, progress, cancellationToken).ConfigureAwait(false);
  79. }
  80. var newUpdateTime = Convert.ToInt64(DateTimeToUnixTimestamp(DateTime.UtcNow)).ToString(UsCulture);
  81. _fileSystem.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  82. progress.Report(100);
  83. }
  84. private async Task<IEnumerable<string>> GetMovieIdsToUpdate(IEnumerable<string> existingIds, string lastUpdateTime, FanartOptions options, CancellationToken cancellationToken)
  85. {
  86. var url = string.Format(UpdatesUrl, FanartArtistProvider.ApiKey, lastUpdateTime);
  87. var clientKey = options.UserApiKey;
  88. if (!string.IsNullOrWhiteSpace(clientKey))
  89. {
  90. url += "&client_key=" + clientKey;
  91. }
  92. // First get last time
  93. using (var stream = await _httpClient.Get(new HttpRequestOptions
  94. {
  95. Url = url,
  96. CancellationToken = cancellationToken,
  97. EnableHttpCompression = true,
  98. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
  99. }).ConfigureAwait(false))
  100. {
  101. using (var reader = new StreamReader(stream))
  102. {
  103. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  104. // If empty fanart will return a string of "null", rather than an empty list
  105. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase))
  106. {
  107. return new List<string>();
  108. }
  109. var updates = _jsonSerializer.DeserializeFromString<List<RootObject>>(json);
  110. var existingDictionary = existingIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  111. return updates.SelectMany(i =>
  112. {
  113. var list = new List<string>();
  114. if (!string.IsNullOrWhiteSpace(i.imdb_id))
  115. {
  116. list.Add(i.imdb_id);
  117. }
  118. if (!string.IsNullOrWhiteSpace(i.tmdb_id))
  119. {
  120. list.Add(i.tmdb_id);
  121. }
  122. return list;
  123. }).Where(existingDictionary.ContainsKey);
  124. }
  125. }
  126. }
  127. private async Task UpdateMovies(IEnumerable<string> idList, IProgress<double> progress, CancellationToken cancellationToken)
  128. {
  129. var list = idList.ToList();
  130. var numComplete = 0;
  131. foreach (var id in list)
  132. {
  133. _logger.Info("Updating movie " + id);
  134. await FanartMovieImageProvider.Current.DownloadMovieJson(id, cancellationToken).ConfigureAwait(false);
  135. numComplete++;
  136. double percent = numComplete;
  137. percent /= list.Count;
  138. percent *= 95;
  139. progress.Report(percent + 5);
  140. }
  141. }
  142. /// <summary>
  143. /// Dates the time to unix timestamp.
  144. /// </summary>
  145. /// <param name="dateTime">The date time.</param>
  146. /// <returns>System.Double.</returns>
  147. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  148. {
  149. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  150. }
  151. public class RootObject
  152. {
  153. public string tmdb_id { get; set; }
  154. public string imdb_id { get; set; }
  155. public string name { get; set; }
  156. public string new_images { get; set; }
  157. public string total_images { get; set; }
  158. }
  159. }
  160. }