FanArtUpdatesPrescanTask.cs 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. var path = FanArtArtistProvider.GetArtistDataPath(_config.CommonApplicationPaths);
  50. var timestampFile = Path.Combine(path, "time.txt");
  51. var timestampFileInfo = new FileInfo(timestampFile);
  52. if (_config.Configuration.MetadataRefreshDays > 0 && timestampFileInfo.Exists && (DateTime.UtcNow - timestampFileInfo.LastWriteTimeUtc).TotalDays < _config.Configuration.MetadataRefreshDays)
  53. {
  54. return;
  55. }
  56. // Find out the last time we queried tvdb for updates
  57. var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;
  58. var existingDirectories = Directory.EnumerateDirectories(path).Select(Path.GetFileName).ToList();
  59. // If this is our first time, don't do any updates and just record the timestamp
  60. if (!string.IsNullOrEmpty(lastUpdateTime))
  61. {
  62. var artistsToUpdate = await GetArtistIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);
  63. progress.Report(5);
  64. await UpdateArtists(artistsToUpdate, path, progress, cancellationToken).ConfigureAwait(false);
  65. }
  66. var newUpdateTime = Convert.ToInt64(DateTimeToUnixTimestamp(DateTime.UtcNow)).ToString(UsCulture);
  67. File.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
  68. progress.Report(100);
  69. }
  70. /// <summary>
  71. /// Gets the artist ids to update.
  72. /// </summary>
  73. /// <param name="existingSeriesIds">The existing series ids.</param>
  74. /// <param name="lastUpdateTime">The last update time.</param>
  75. /// <param name="cancellationToken">The cancellation token.</param>
  76. /// <returns>Task{IEnumerable{System.String}}.</returns>
  77. private async Task<IEnumerable<string>> GetArtistIdsToUpdate(IEnumerable<string> existingSeriesIds, string lastUpdateTime, CancellationToken cancellationToken)
  78. {
  79. // First get last time
  80. using (var stream = await _httpClient.Get(new HttpRequestOptions
  81. {
  82. Url = string.Format(UpdatesUrl, FanartBaseProvider.ApiKey, lastUpdateTime),
  83. CancellationToken = cancellationToken,
  84. EnableHttpCompression = true,
  85. ResourcePool = FanartBaseProvider.FanArtResourcePool
  86. }).ConfigureAwait(false))
  87. {
  88. // If empty fanart will return a string of "null", rather than an empty list
  89. using (var reader = new StreamReader(stream))
  90. {
  91. var json = await reader.ReadToEndAsync().ConfigureAwait(false);
  92. if (string.Equals(json, "null", StringComparison.OrdinalIgnoreCase))
  93. {
  94. return new List<string>();
  95. }
  96. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdate>>(json);
  97. return updates.Select(i => i.id).Where(i => existingSeriesIds.Contains(i, StringComparer.OrdinalIgnoreCase));
  98. }
  99. }
  100. }
  101. /// <summary>
  102. /// Updates the artists.
  103. /// </summary>
  104. /// <param name="idList">The id list.</param>
  105. /// <param name="artistsDataPath">The artists data path.</param>
  106. /// <param name="progress">The progress.</param>
  107. /// <param name="cancellationToken">The cancellation token.</param>
  108. /// <returns>Task.</returns>
  109. private async Task UpdateArtists(IEnumerable<string> idList, string artistsDataPath, IProgress<double> progress, CancellationToken cancellationToken)
  110. {
  111. var list = idList.ToList();
  112. var numComplete = 0;
  113. foreach (var id in list)
  114. {
  115. try
  116. {
  117. await UpdateArtist(id, artistsDataPath, cancellationToken).ConfigureAwait(false);
  118. }
  119. catch (HttpException ex)
  120. {
  121. // Already logged at lower levels, but don't fail the whole operation, unless something other than a timeout
  122. if (!ex.IsTimedOut)
  123. {
  124. throw;
  125. }
  126. }
  127. numComplete++;
  128. double percent = numComplete;
  129. percent /= list.Count;
  130. percent *= 95;
  131. progress.Report(percent + 5);
  132. }
  133. }
  134. /// <summary>
  135. /// Updates the artist.
  136. /// </summary>
  137. /// <param name="musicBrainzId">The musicBrainzId.</param>
  138. /// <param name="artistsDataPath">The artists data path.</param>
  139. /// <param name="cancellationToken">The cancellation token.</param>
  140. /// <returns>Task.</returns>
  141. private Task UpdateArtist(string musicBrainzId, string artistsDataPath, CancellationToken cancellationToken)
  142. {
  143. _logger.Info("Updating artist " + musicBrainzId);
  144. artistsDataPath = Path.Combine(artistsDataPath, musicBrainzId);
  145. if (!Directory.Exists(artistsDataPath))
  146. {
  147. Directory.CreateDirectory(artistsDataPath);
  148. }
  149. return FanArtArtistProvider.Current.DownloadArtistXml(artistsDataPath, 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. }