FanArtMovieUpdatesPostScanTask.cs 7.1 KB

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