FanArtMovieUpdatesPrescanTask.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using MediaBrowser.Providers.Music;
  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.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 readonly IFileSystem _fileSystem;
  35. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  36. public FanArtMovieUpdatesPrescanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IFileSystem fileSystem)
  37. {
  38. _jsonSerializer = jsonSerializer;
  39. _config = config;
  40. _logger = logger;
  41. _httpClient = httpClient;
  42. _fileSystem = fileSystem;
  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. Directory.CreateDirectory(path);
  59. var timestampFile = Path.Combine(path, "time.txt");
  60. var timestampFileInfo = new FileInfo(timestampFile);
  61. // Don't check for tvdb updates anymore frequently than 24 hours
  62. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 1)
  63. {
  64. return;
  65. }
  66. // Find out the last time we queried for updates
  67. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  68. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  69. // If this is our first time, don't do any updates and just record the timestamp
  70. if (!string.IsNullOrEmpty(lastUpdateTime))
  71. {
  72. var moviesToUpdate = await GetMovieIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);
  73. progress.Report(5);
  74. await UpdateMovies(moviesToUpdate, progress, cancellationToken).ConfigureAwait(false);
  75. }
  76. var newUpdateTime = Convert.ToInt64(DateTimeToUnixTimestamp(DateTime.UtcNow)).ToString(UsCulture);
  77. File.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  78. progress.Report(100);
  79. }
  80. private async Task<IEnumerable<string>> GetMovieIdsToUpdate(IEnumerable<string> existingIds, string lastUpdateTime, CancellationToken cancellationToken)
  81. {
  82. // First get last time
  83. using (var stream = await _httpClient.Get(new HttpRequestOptions
  84. {
  85. Url = string.Format(UpdatesUrl, FanartBaseProvider.ApiKey, lastUpdateTime),
  86. CancellationToken = cancellationToken,
  87. EnableHttpCompression = true,
  88. ResourcePool = FanartBaseProvider.FanArtResourcePool
  89. }).ConfigureAwait(false))
  90. {
  91. // If empty fanart will return a string of "null", rather than an empty list
  92. using (var reader = new StreamReader(stream))
  93. {
  94. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  95. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase))
  96. {
  97. return new List<string>();
  98. }
  99. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdatesPrescanTask.FanArtUpdate>>(json);
  100. var existingDictionary = existingIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  101. return updates.Select(i => i.id).Where(existingDictionary.ContainsKey);
  102. }
  103. }
  104. }
  105. private async Task UpdateMovies(IEnumerable<string> idList, IProgress<double> progress, CancellationToken cancellationToken)
  106. {
  107. var list = idList.ToList();
  108. var numComplete = 0;
  109. foreach (var id in list)
  110. {
  111. _logger.Info("Updating movie " + id);
  112. await FanArtMovieProvider.Current.DownloadMovieXml(id, cancellationToken).ConfigureAwait(false);
  113. numComplete++;
  114. double percent = numComplete;
  115. percent /= list.Count;
  116. percent *= 95;
  117. progress.Report(percent + 5);
  118. }
  119. }
  120. /// <summary>
  121. /// Dates the time to unix timestamp.
  122. /// </summary>
  123. /// <param name="dateTime">The date time.</param>
  124. /// <returns>System.Double.</returns>
  125. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  126. {
  127. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  128. }
  129. public class FanArtUpdate
  130. {
  131. public string id { get; set; }
  132. public string name { get; set; }
  133. public string new_images { get; set; }
  134. public string total_images { get; set; }
  135. }
  136. }
  137. }