FanArtMovieUpdatesPrescanTask.cs 6.5 KB

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