FanArtUpdatesPrescanTask.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Net;
  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.Controller.Providers.Music
  16. {
  17. class FanArtUpdatesPrescanTask : ILibraryPrescanTask
  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 static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  34. public FanArtUpdatesPrescanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient)
  35. {
  36. _jsonSerializer = jsonSerializer;
  37. _config = config;
  38. _logger = logger;
  39. _httpClient = httpClient;
  40. }
  41. /// <summary>
  42. /// Runs the specified progress.
  43. /// </summary>
  44. /// <param name="progress">The progress.</param>
  45. /// <param name="cancellationToken">The cancellation token.</param>
  46. /// <returns>Task.</returns>
  47. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  48. {
  49. if (!_config.Configuration.EnableInternetProviders)
  50. {
  51. progress.Report(100);
  52. return;
  53. }
  54. var path = FanArtArtistProvider.GetArtistDataPath(_config.CommonApplicationPaths);
  55. var timestampFile = Path.Combine(path, "time.txt");
  56. var timestampFileInfo = new FileInfo(timestampFile);
  57. if (_config.Configuration.MetadataRefreshDays > 0 && timestampFileInfo.Exists && (DateTime.UtcNow - timestampFileInfo.LastWriteTimeUtc).TotalDays < _config.Configuration.MetadataRefreshDays)
  58. {
  59. return;
  60. }
  61. // Find out the last time we queried for updates
  62. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  63. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  64. // If this is our first time, don't do any updates and just record the timestamp
  65. if (!string.IsNullOrEmpty(lastUpdateTime))
  66. {
  67. var artistsToUpdate = await GetArtistIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);
  68. progress.Report(5);
  69. await UpdateArtists(artistsToUpdate, path, progress, cancellationToken).ConfigureAwait(false);
  70. }
  71. var newUpdateTime = Convert.ToInt64(DateTimeToUnixTimestamp(DateTime.UtcNow)).ToString(UsCulture);
  72. File.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  73. progress.Report(100);
  74. }
  75. /// <summary>
  76. /// Gets the artist ids to update.
  77. /// </summary>
  78. /// <param name="existingArtistIds">The existing series ids.</param>
  79. /// <param name="lastUpdateTime">The last update time.</param>
  80. /// <param name="cancellationToken">The cancellation token.</param>
  81. /// <returns>Task{IEnumerable{System.String}}.</returns>
  82. private async Task<IEnumerable<string>> GetArtistIdsToUpdate(IEnumerable<string> existingArtistIds, string lastUpdateTime, CancellationToken cancellationToken)
  83. {
  84. // First get last time
  85. using (var stream = await _httpClient.Get(new HttpRequestOptions
  86. {
  87. Url = string.Format(UpdatesUrl, FanartBaseProvider.ApiKey, lastUpdateTime),
  88. CancellationToken = cancellationToken,
  89. EnableHttpCompression = true,
  90. ResourcePool = FanartBaseProvider.FanArtResourcePool
  91. }).ConfigureAwait(false))
  92. {
  93. // If empty fanart will return a string of "null", rather than an empty list
  94. using (var reader = new StreamReader(stream))
  95. {
  96. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  97. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase))
  98. {
  99. return new List<string>();
  100. }
  101. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdate>>(json);
  102. return updates.Select(i => i.id).Where(i => existingArtistIds.Contains(i, StringComparer.OrdinalIgnoreCase));
  103. }
  104. }
  105. }
  106. /// <summary>
  107. /// Updates the artists.
  108. /// </summary>
  109. /// <param name="idList">The id list.</param>
  110. /// <param name="artistsDataPath">The artists data path.</param>
  111. /// <param name="progress">The progress.</param>
  112. /// <param name="cancellationToken">The cancellation token.</param>
  113. /// <returns>Task.</returns>
  114. private async Task UpdateArtists(IEnumerable<string> idList, string artistsDataPath, IProgress<double> progress, CancellationToken cancellationToken)
  115. {
  116. var list = idList.ToList();
  117. var numComplete = 0;
  118. foreach (var id in list)
  119. {
  120. try
  121. {
  122. await UpdateArtist(id, artistsDataPath, cancellationToken).ConfigureAwait(false);
  123. }
  124. catch (HttpException ex)
  125. {
  126. // Already logged at lower levels, but don't fail the whole operation, unless something other than a timeout
  127. if (!ex.IsTimedOut)
  128. {
  129. throw;
  130. }
  131. }
  132. numComplete++;
  133. double percent = numComplete;
  134. percent /= list.Count;
  135. percent *= 95;
  136. progress.Report(percent + 5);
  137. }
  138. }
  139. /// <summary>
  140. /// Updates the artist.
  141. /// </summary>
  142. /// <param name="musicBrainzId">The musicBrainzId.</param>
  143. /// <param name="artistsDataPath">The artists data path.</param>
  144. /// <param name="cancellationToken">The cancellation token.</param>
  145. /// <returns>Task.</returns>
  146. private Task UpdateArtist(string musicBrainzId, string artistsDataPath, CancellationToken cancellationToken)
  147. {
  148. _logger.Info("Updating artist " + musicBrainzId);
  149. artistsDataPath = Path.Combine(artistsDataPath, musicBrainzId);
  150. if (!Directory.Exists(artistsDataPath))
  151. {
  152. Directory.CreateDirectory(artistsDataPath);
  153. }
  154. return FanArtArtistProvider.Current.DownloadArtistXml(artistsDataPath, musicBrainzId, cancellationToken);
  155. }
  156. /// <summary>
  157. /// Dates the time to unix timestamp.
  158. /// </summary>
  159. /// <param name="dateTime">The date time.</param>
  160. /// <returns>System.Double.</returns>
  161. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  162. {
  163. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  164. }
  165. public class FanArtUpdate
  166. {
  167. public string id { get; set; }
  168. public string name { get; set; }
  169. public string new_images { get; set; }
  170. public string total_images { get; set; }
  171. }
  172. }
  173. }