FanArtUpdatesPostScanTask.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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 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. using MediaBrowser.Providers.TV;
  17. namespace MediaBrowser.Providers.Music
  18. {
  19. class FanartUpdatesPostScanTask : ILibraryPostScanTask
  20. {
  21. private const string UpdatesUrl = "http://api.fanart.tv/webservice/newmusic/{0}/{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 FanartUpdatesPostScanTask(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 = FanartArtistProvider.GetArtistDataPath(_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 artistsToUpdate = await GetArtistIdsToUpdate(existingDirectories, lastUpdateTime, options, cancellationToken).ConfigureAwait(false);
  75. progress.Report(5);
  76. await UpdateArtists(artistsToUpdate, 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 artist ids to update.
  84. /// </summary>
  85. /// <param name="existingArtistIds">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>> GetArtistIdsToUpdate(IEnumerable<string> existingArtistIds, 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))
  110. {
  111. return new List<string>();
  112. }
  113. var existingDictionary = existingArtistIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  114. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdate>>(json);
  115. return updates.Select(i => i.id).Where(existingDictionary.ContainsKey);
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// Updates the artists.
  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 UpdateArtists(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. await UpdateArtist(id, cancellationToken).ConfigureAwait(false);
  133. numComplete++;
  134. double percent = numComplete;
  135. percent /= list.Count;
  136. percent *= 95;
  137. progress.Report(percent + 5);
  138. }
  139. }
  140. /// <summary>
  141. /// Updates the artist.
  142. /// </summary>
  143. /// <param name="musicBrainzId">The musicBrainzId.</param>
  144. /// <param name="cancellationToken">The cancellation token.</param>
  145. /// <returns>Task.</returns>
  146. private Task UpdateArtist(string musicBrainzId, CancellationToken cancellationToken)
  147. {
  148. _logger.Info("Updating artist " + musicBrainzId);
  149. return FanartArtistProvider.Current.DownloadArtistXml(musicBrainzId, cancellationToken);
  150. }
  151. /// <summary>
  152. /// Dates the time to unix timestamp.
  153. /// </summary>
  154. /// <param name="dateTime">The date time.</param>
  155. /// <returns>System.Double.</returns>
  156. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  157. {
  158. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  159. }
  160. public class FanArtUpdate
  161. {
  162. public string id { get; set; }
  163. public string name { get; set; }
  164. public string new_images { get; set; }
  165. public string total_images { get; set; }
  166. }
  167. }
  168. }