FanArtUpdatesPostScanTask.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 CommonIO;
  17. using MediaBrowser.Providers.TV;
  18. namespace MediaBrowser.Providers.Music
  19. {
  20. class FanartUpdatesPostScanTask : ILibraryPostScanTask
  21. {
  22. private const string UpdatesUrl = "http://api.fanart.tv/webservice/newmusic/{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 readonly IFileSystem _fileSystem;
  37. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  38. public FanartUpdatesPostScanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IFileSystem fileSystem)
  39. {
  40. _jsonSerializer = jsonSerializer;
  41. _config = config;
  42. _logger = logger;
  43. _httpClient = httpClient;
  44. _fileSystem = fileSystem;
  45. }
  46. /// <summary>
  47. /// Runs the specified progress.
  48. /// </summary>
  49. /// <param name="progress">The progress.</param>
  50. /// <param name="cancellationToken">The cancellation token.</param>
  51. /// <returns>Task.</returns>
  52. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  53. {
  54. var options = FanartSeriesProvider.Current.GetFanartOptions();
  55. if (!options.EnableAutomaticUpdates)
  56. {
  57. progress.Report(100);
  58. return;
  59. }
  60. var path = FanartArtistProvider.GetArtistDataPath(_config.CommonApplicationPaths);
  61. _fileSystem.CreateDirectory(path);
  62. var timestampFile = Path.Combine(path, "time.txt");
  63. var timestampFileInfo = _fileSystem.GetFileInfo(timestampFile);
  64. // Don't check for updates every single time
  65. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 3)
  66. {
  67. return;
  68. }
  69. // Find out the last time we queried for updates
  70. var lastUpdateTime = timestampFileInfo.Exists ? _fileSystem.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  71. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  72. // If this is our first time, don't do any updates and just record the timestamp
  73. if (!string.IsNullOrEmpty(lastUpdateTime))
  74. {
  75. var artistsToUpdate = await GetArtistIdsToUpdate(existingDirectories, lastUpdateTime, options, cancellationToken).ConfigureAwait(false);
  76. progress.Report(5);
  77. await UpdateArtists(artistsToUpdate, progress, cancellationToken).ConfigureAwait(false);
  78. }
  79. var newUpdateTime = Convert.ToInt64(DateTimeToUnixTimestamp(DateTime.UtcNow)).ToString(UsCulture);
  80. _fileSystem.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  81. progress.Report(100);
  82. }
  83. /// <summary>
  84. /// Gets the artist ids to update.
  85. /// </summary>
  86. /// <param name="existingArtistIds">The existing series ids.</param>
  87. /// <param name="lastUpdateTime">The last update time.</param>
  88. /// <param name="cancellationToken">The cancellation token.</param>
  89. /// <returns>Task{IEnumerable{System.String}}.</returns>
  90. private async Task<IEnumerable<string>> GetArtistIdsToUpdate(IEnumerable<string> existingArtistIds, string lastUpdateTime, FanartOptions options, CancellationToken cancellationToken)
  91. {
  92. var url = string.Format(UpdatesUrl, FanartArtistProvider.ApiKey, lastUpdateTime);
  93. if (!string.IsNullOrWhiteSpace(options.UserApiKey))
  94. {
  95. url += "&client_key=" + options.UserApiKey;
  96. }
  97. // First get last time
  98. using (var stream = await _httpClient.Get(new HttpRequestOptions
  99. {
  100. Url = url,
  101. CancellationToken = cancellationToken,
  102. EnableHttpCompression = true,
  103. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
  104. }).ConfigureAwait(false))
  105. {
  106. // If empty fanart will return a string of "null", rather than an empty list
  107. using (var reader = new StreamReader(stream))
  108. {
  109. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  110. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase))
  111. {
  112. return new List<string>();
  113. }
  114. var existingDictionary = existingArtistIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  115. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdate>>(json);
  116. return updates.Select(i => i.id).Where(existingDictionary.ContainsKey);
  117. }
  118. }
  119. }
  120. /// <summary>
  121. /// Updates the artists.
  122. /// </summary>
  123. /// <param name="idList">The id list.</param>
  124. /// <param name="progress">The progress.</param>
  125. /// <param name="cancellationToken">The cancellation token.</param>
  126. /// <returns>Task.</returns>
  127. private async Task UpdateArtists(IEnumerable<string> idList, IProgress<double> progress, CancellationToken cancellationToken)
  128. {
  129. var list = idList.ToList();
  130. var numComplete = 0;
  131. foreach (var id in list)
  132. {
  133. await UpdateArtist(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. /// Updates the artist.
  143. /// </summary>
  144. /// <param name="musicBrainzId">The musicBrainzId.</param>
  145. /// <param name="cancellationToken">The cancellation token.</param>
  146. /// <returns>Task.</returns>
  147. private Task UpdateArtist(string musicBrainzId, CancellationToken cancellationToken)
  148. {
  149. _logger.Info("Updating artist " + musicBrainzId);
  150. return FanartArtistProvider.Current.DownloadArtistJson(musicBrainzId, cancellationToken);
  151. }
  152. /// <summary>
  153. /// Dates the time to unix timestamp.
  154. /// </summary>
  155. /// <param name="dateTime">The date time.</param>
  156. /// <returns>System.Double.</returns>
  157. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  158. {
  159. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  160. }
  161. public class FanArtUpdate
  162. {
  163. public string id { get; set; }
  164. public string name { get; set; }
  165. public string new_images { get; set; }
  166. public string total_images { get; set; }
  167. }
  168. }
  169. }