FanArtTvUpdatesPostScanTask.cs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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 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. namespace MediaBrowser.Providers.TV
  18. {
  19. class FanArtTvUpdatesPostScanTask : ILibraryPostScanTask
  20. {
  21. private const string UpdatesUrl = "http://webservice.fanart.tv/v3/tv/latest?api_key={0}&date={1}";
  22. /// <summary>
  23. /// The _HTTP client
  24. /// </summary>
  25. private readonly IHttpClient _httpClient;
  26. /// <summary>
  27. /// The _logger
  28. /// </summary>
  29. private readonly ILogger _logger;
  30. /// <summary>
  31. /// The _config
  32. /// </summary>
  33. private readonly IServerConfigurationManager _config;
  34. private readonly IJsonSerializer _jsonSerializer;
  35. private readonly IFileSystem _fileSystem;
  36. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  37. public FanArtTvUpdatesPostScanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IFileSystem fileSystem)
  38. {
  39. _jsonSerializer = jsonSerializer;
  40. _config = config;
  41. _logger = logger;
  42. _httpClient = httpClient;
  43. _fileSystem = fileSystem;
  44. }
  45. /// <summary>
  46. /// Runs the specified progress.
  47. /// </summary>
  48. /// <param name="progress">The progress.</param>
  49. /// <param name="cancellationToken">The cancellation token.</param>
  50. /// <returns>Task.</returns>
  51. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  52. {
  53. var options = FanartSeriesProvider.Current.GetFanartOptions();
  54. if (!options.EnableAutomaticUpdates)
  55. {
  56. progress.Report(100);
  57. return;
  58. }
  59. var path = FanartSeriesProvider.GetSeriesDataPath(_config.CommonApplicationPaths);
  60. Directory.CreateDirectory(path);
  61. var timestampFile = Path.Combine(path, "time.txt");
  62. var timestampFileInfo = new FileInfo(timestampFile);
  63. // Don't check for updates every single time
  64. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 3)
  65. {
  66. return;
  67. }
  68. // Find out the last time we queried for updates
  69. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  70. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  71. // If this is our first time, don't do any updates and just record the timestamp
  72. if (!string.IsNullOrEmpty(lastUpdateTime))
  73. {
  74. var seriesToUpdate = await GetSeriesIdsToUpdate(existingDirectories, lastUpdateTime, options, cancellationToken).ConfigureAwait(false);
  75. progress.Report(5);
  76. await UpdateSeries(seriesToUpdate, progress, cancellationToken).ConfigureAwait(false);
  77. }
  78. var newUpdateTime = Convert.ToInt64(DateTimeToUnixTimestamp(DateTime.UtcNow)).ToString(UsCulture);
  79. File.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  80. progress.Report(100);
  81. }
  82. /// <summary>
  83. /// Gets the series ids to update.
  84. /// </summary>
  85. /// <param name="existingSeriesIds">The existing series ids.</param>
  86. /// <param name="lastUpdateTime">The last update time.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. /// <returns>Task{IEnumerable{System.String}}.</returns>
  89. private async Task<IEnumerable<string>> GetSeriesIdsToUpdate(IEnumerable<string> existingSeriesIds, string lastUpdateTime, FanartOptions options, CancellationToken cancellationToken)
  90. {
  91. var url = string.Format(UpdatesUrl, FanartArtistProvider.ApiKey, lastUpdateTime);
  92. if (!string.IsNullOrWhiteSpace(options.UserApiKey))
  93. {
  94. url += "&client_key=" + options.UserApiKey;
  95. }
  96. // First get last time
  97. using (var stream = await _httpClient.Get(new HttpRequestOptions
  98. {
  99. Url = url,
  100. CancellationToken = cancellationToken,
  101. EnableHttpCompression = true,
  102. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
  103. }).ConfigureAwait(false))
  104. {
  105. // If empty fanart will return a string of "null", rather than an empty list
  106. using (var reader = new StreamReader(stream))
  107. {
  108. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  109. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(json))
  110. {
  111. return new List<string>();
  112. }
  113. var existingDictionary = existingSeriesIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  114. var updates = _jsonSerializer.DeserializeFromString<List<FanartUpdatesPostScanTask.FanArtUpdate>>(json);
  115. return updates.Select(i => i.id).Where(existingDictionary.ContainsKey);
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// Updates the series.
  121. /// </summary>
  122. /// <param name="idList">The id list.</param>
  123. /// <param name="progress">The progress.</param>
  124. /// <param name="cancellationToken">The cancellation token.</param>
  125. /// <returns>Task.</returns>
  126. private async Task UpdateSeries(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 series " + id);
  133. await FanartSeriesProvider.Current.DownloadSeriesJson(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 FanArtUpdate
  151. {
  152. public string id { get; set; }
  153. public string name { get; set; }
  154. public string new_images { get; set; }
  155. public string total_images { get; set; }
  156. }
  157. }
  158. }