FanArtUpdatesPrescanTask.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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 System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Providers.Music
  16. {
  17. class FanArtUpdatesPrescanTask : ILibraryPostScanTask
  18. {
  19. private const string UpdatesUrl = "http://api.fanart.tv/webservice/newmusic/{0}/{1}/";
  20. /// <summary>
  21. /// The _HTTP client
  22. /// </summary>
  23. private readonly IHttpClient _httpClient;
  24. /// <summary>
  25. /// The _logger
  26. /// </summary>
  27. private readonly ILogger _logger;
  28. /// <summary>
  29. /// The _config
  30. /// </summary>
  31. private readonly IServerConfigurationManager _config;
  32. private readonly IJsonSerializer _jsonSerializer;
  33. private readonly IFileSystem _fileSystem;
  34. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  35. public FanArtUpdatesPrescanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient, IFileSystem fileSystem)
  36. {
  37. _jsonSerializer = jsonSerializer;
  38. _config = config;
  39. _logger = logger;
  40. _httpClient = httpClient;
  41. _fileSystem = fileSystem;
  42. }
  43. /// <summary>
  44. /// Runs the specified progress.
  45. /// </summary>
  46. /// <param name="progress">The progress.</param>
  47. /// <param name="cancellationToken">The cancellation token.</param>
  48. /// <returns>Task.</returns>
  49. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  50. {
  51. if (!_config.Configuration.EnableInternetProviders)
  52. {
  53. progress.Report(100);
  54. return;
  55. }
  56. var path = FanArtArtistProvider.GetArtistDataPath(_config.CommonApplicationPaths);
  57. Directory.CreateDirectory(path);
  58. var timestampFile = Path.Combine(path, "time.txt");
  59. var timestampFileInfo = new FileInfo(timestampFile);
  60. // Don't check for updates every single time
  61. if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 3)
  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 artistsToUpdate = await GetArtistIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);
  72. progress.Report(5);
  73. await UpdateArtists(artistsToUpdate, 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. /// <summary>
  80. /// Gets the artist ids to update.
  81. /// </summary>
  82. /// <param name="existingArtistIds">The existing series ids.</param>
  83. /// <param name="lastUpdateTime">The last update time.</param>
  84. /// <param name="cancellationToken">The cancellation token.</param>
  85. /// <returns>Task{IEnumerable{System.String}}.</returns>
  86. private async Task<IEnumerable<string>> GetArtistIdsToUpdate(IEnumerable<string> existingArtistIds, string lastUpdateTime, CancellationToken cancellationToken)
  87. {
  88. // First get last time
  89. using (var stream = await _httpClient.Get(new HttpRequestOptions
  90. {
  91. Url = string.Format(UpdatesUrl, FanartBaseProvider.ApiKey, lastUpdateTime),
  92. CancellationToken = cancellationToken,
  93. EnableHttpCompression = true,
  94. ResourcePool = FanartBaseProvider.FanArtResourcePool
  95. }).ConfigureAwait(false))
  96. {
  97. // If empty fanart will return a string of "null", rather than an empty list
  98. using (var reader = new StreamReader(stream))
  99. {
  100. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  101. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase))
  102. {
  103. return new List<string>();
  104. }
  105. var existingDictionary = existingArtistIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  106. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdate>>(json);
  107. return updates.Select(i => i.id).Where(existingDictionary.ContainsKey);
  108. }
  109. }
  110. }
  111. /// <summary>
  112. /// Updates the artists.
  113. /// </summary>
  114. /// <param name="idList">The id list.</param>
  115. /// <param name="artistsDataPath">The artists data path.</param>
  116. /// <param name="progress">The progress.</param>
  117. /// <param name="cancellationToken">The cancellation token.</param>
  118. /// <returns>Task.</returns>
  119. private async Task UpdateArtists(IEnumerable<string> idList, string artistsDataPath, IProgress<double> progress, CancellationToken cancellationToken)
  120. {
  121. var list = idList.ToList();
  122. var numComplete = 0;
  123. foreach (var id in list)
  124. {
  125. await UpdateArtist(id, artistsDataPath, cancellationToken).ConfigureAwait(false);
  126. numComplete++;
  127. double percent = numComplete;
  128. percent /= list.Count;
  129. percent *= 95;
  130. progress.Report(percent + 5);
  131. }
  132. }
  133. /// <summary>
  134. /// Updates the artist.
  135. /// </summary>
  136. /// <param name="musicBrainzId">The musicBrainzId.</param>
  137. /// <param name="artistsDataPath">The artists data path.</param>
  138. /// <param name="cancellationToken">The cancellation token.</param>
  139. /// <returns>Task.</returns>
  140. private Task UpdateArtist(string musicBrainzId, string artistsDataPath, CancellationToken cancellationToken)
  141. {
  142. _logger.Info("Updating artist " + musicBrainzId);
  143. artistsDataPath = Path.Combine(artistsDataPath, musicBrainzId);
  144. Directory.CreateDirectory(artistsDataPath);
  145. return FanArtArtistProvider.Current.DownloadArtistXml(artistsDataPath, musicBrainzId, cancellationToken);
  146. }
  147. /// <summary>
  148. /// Dates the time to unix timestamp.
  149. /// </summary>
  150. /// <param name="dateTime">The date time.</param>
  151. /// <returns>System.Double.</returns>
  152. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  153. {
  154. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  155. }
  156. public class FanArtUpdate
  157. {
  158. public string id { get; set; }
  159. public string name { get; set; }
  160. public string new_images { get; set; }
  161. public string total_images { get; set; }
  162. }
  163. }
  164. }