FanArtMovieUpdatesPrescanTask.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.Providers.Music;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Net;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Globalization;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MediaBrowser.Controller.Providers.Movies
  17. {
  18. class FanArtMovieUpdatesPrescanTask : ILibraryPrescanTask
  19. {
  20. private const string UpdatesUrl = "http://api.fanart.tv/webservice/newmovies/{0}/{1}/";
  21. /// <summary>
  22. /// The _HTTP client
  23. /// </summary>
  24. private readonly IHttpClient _httpClient;
  25. /// <summary>
  26. /// The _logger
  27. /// </summary>
  28. private readonly ILogger _logger;
  29. /// <summary>
  30. /// The _config
  31. /// </summary>
  32. private readonly IServerConfigurationManager _config;
  33. private readonly IJsonSerializer _jsonSerializer;
  34. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  35. public FanArtMovieUpdatesPrescanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient)
  36. {
  37. _jsonSerializer = jsonSerializer;
  38. _config = config;
  39. _logger = logger;
  40. _httpClient = httpClient;
  41. }
  42. /// <summary>
  43. /// Runs the specified progress.
  44. /// </summary>
  45. /// <param name="progress">The progress.</param>
  46. /// <param name="cancellationToken">The cancellation token.</param>
  47. /// <returns>Task.</returns>
  48. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  49. {
  50. if (!_config.Configuration.EnableInternetProviders)
  51. {
  52. progress.Report(100);
  53. return;
  54. }
  55. var path = FanArtMovieProvider.GetMoviesDataPath(_config.CommonApplicationPaths);
  56. var timestampFile = Path.Combine(path, "time.txt");
  57. var timestampFileInfo = new FileInfo(timestampFile);
  58. if (_config.Configuration.MetadataRefreshDays > 0 && timestampFileInfo.Exists && (DateTime.UtcNow - timestampFileInfo.LastWriteTimeUtc).TotalDays < _config.Configuration.MetadataRefreshDays)
  59. {
  60. return;
  61. }
  62. // Find out the last time we queried for updates
  63. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  64. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  65. // If this is our first time, don't do any updates and just record the timestamp
  66. if (!string.IsNullOrEmpty(lastUpdateTime))
  67. {
  68. var moviesToUpdate = await GetMovieIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);
  69. progress.Report(5);
  70. await UpdateMovies(moviesToUpdate, path, progress, cancellationToken).ConfigureAwait(false);
  71. }
  72. var newUpdateTime = Convert.ToInt64(DateTimeToUnixTimestamp(DateTime.UtcNow)).ToString(UsCulture);
  73. File.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  74. progress.Report(100);
  75. }
  76. private async Task<IEnumerable<string>> GetMovieIdsToUpdate(IEnumerable<string> existingIds, string lastUpdateTime, CancellationToken cancellationToken)
  77. {
  78. // First get last time
  79. using (var stream = await _httpClient.Get(new HttpRequestOptions
  80. {
  81. Url = string.Format(UpdatesUrl, FanartBaseProvider.ApiKey, lastUpdateTime),
  82. CancellationToken = cancellationToken,
  83. EnableHttpCompression = true,
  84. ResourcePool = FanartBaseProvider.FanArtResourcePool
  85. }).ConfigureAwait(false))
  86. {
  87. // If empty fanart will return a string of "null", rather than an empty list
  88. using (var reader = new StreamReader(stream))
  89. {
  90. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  91. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase))
  92. {
  93. return new List<string>();
  94. }
  95. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdatesPrescanTask.FanArtUpdate>>(json);
  96. return updates.Select(i => i.id).Where(i => existingIds.Contains(i, StringComparer.OrdinalIgnoreCase));
  97. }
  98. }
  99. }
  100. private async Task UpdateMovies(IEnumerable<string> idList, string moviesDataPath, IProgress<double> progress, CancellationToken cancellationToken)
  101. {
  102. var list = idList.ToList();
  103. var numComplete = 0;
  104. foreach (var id in list)
  105. {
  106. try
  107. {
  108. await UpdateMovie(id, moviesDataPath, cancellationToken).ConfigureAwait(false);
  109. }
  110. catch (HttpException ex)
  111. {
  112. // Already logged at lower levels, but don't fail the whole operation, unless something other than a timeout
  113. if (!ex.IsTimedOut)
  114. {
  115. throw;
  116. }
  117. }
  118. numComplete++;
  119. double percent = numComplete;
  120. percent /= list.Count;
  121. percent *= 95;
  122. progress.Report(percent + 5);
  123. }
  124. }
  125. private Task UpdateMovie(string tmdbId, string movieDataPath, CancellationToken cancellationToken)
  126. {
  127. _logger.Info("Updating movie " + tmdbId);
  128. movieDataPath = Path.Combine(movieDataPath, tmdbId);
  129. if (!Directory.Exists(movieDataPath))
  130. {
  131. Directory.CreateDirectory(movieDataPath);
  132. }
  133. return FanArtMovieProvider.Current.DownloadMovieXml(movieDataPath, tmdbId, cancellationToken);
  134. }
  135. /// <summary>
  136. /// Dates the time to unix timestamp.
  137. /// </summary>
  138. /// <param name="dateTime">The date time.</param>
  139. /// <returns>System.Double.</returns>
  140. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  141. {
  142. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  143. }
  144. public class FanArtUpdate
  145. {
  146. public string id { get; set; }
  147. public string name { get; set; }
  148. public string new_images { get; set; }
  149. public string total_images { get; set; }
  150. }
  151. }
  152. }