FanArtUpdatesPrescanTask.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Providers.Music
  15. {
  16. class FanArtUpdatesPrescanTask : ILibraryPrescanTask
  17. {
  18. private const string UpdatesUrl = "http://api.fanart.tv/webservice/newmusic/{0}/{1}/";
  19. /// <summary>
  20. /// The _HTTP client
  21. /// </summary>
  22. private readonly IHttpClient _httpClient;
  23. /// <summary>
  24. /// The _logger
  25. /// </summary>
  26. private readonly ILogger _logger;
  27. /// <summary>
  28. /// The _config
  29. /// </summary>
  30. private readonly IServerConfigurationManager _config;
  31. private readonly IJsonSerializer _jsonSerializer;
  32. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  33. public FanArtUpdatesPrescanTask(IJsonSerializer jsonSerializer, IServerConfigurationManager config, ILogger logger, IHttpClient httpClient)
  34. {
  35. _jsonSerializer = jsonSerializer;
  36. _config = config;
  37. _logger = logger;
  38. _httpClient = httpClient;
  39. }
  40. /// <summary>
  41. /// Runs the specified progress.
  42. /// </summary>
  43. /// <param name="progress">The progress.</param>
  44. /// <param name="cancellationToken">The cancellation token.</param>
  45. /// <returns>Task.</returns>
  46. public async Task Run(IProgress<double> progress, CancellationToken cancellationToken)
  47. {
  48. if (!_config.Configuration.EnableInternetProviders)
  49. {
  50. progress.Report(100);
  51. return;
  52. }
  53. var path = FanArtArtistProvider.GetArtistDataPath(_config.CommonApplicationPaths);
  54. var timestampFile = Path.Combine(path, "time.txt");
  55. var timestampFileInfo = new FileInfo(timestampFile);
  56. // Don't check for tvdb updates anymore frequently than 24 hours
  57. if (timestampFileInfo.Exists && (DateTime.UtcNow - timestampFileInfo.LastWriteTimeUtc).TotalDays < 1)
  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 existingDictionary = existingArtistIds.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase);
  102. var updates = _jsonSerializer.DeserializeFromString<List<FanArtUpdate>>(json);
  103. return updates.Select(i => i.id).Where(existingDictionary.ContainsKey);
  104. }
  105. }
  106. }
  107. /// <summary>
  108. /// Updates the artists.
  109. /// </summary>
  110. /// <param name="idList">The id list.</param>
  111. /// <param name="artistsDataPath">The artists data path.</param>
  112. /// <param name="progress">The progress.</param>
  113. /// <param name="cancellationToken">The cancellation token.</param>
  114. /// <returns>Task.</returns>
  115. private async Task UpdateArtists(IEnumerable<string> idList, string artistsDataPath, IProgress<double> progress, CancellationToken cancellationToken)
  116. {
  117. var list = idList.ToList();
  118. var numComplete = 0;
  119. foreach (var id in list)
  120. {
  121. await UpdateArtist(id, artistsDataPath, cancellationToken).ConfigureAwait(false);
  122. numComplete++;
  123. double percent = numComplete;
  124. percent /= list.Count;
  125. percent *= 95;
  126. progress.Report(percent + 5);
  127. }
  128. }
  129. /// <summary>
  130. /// Updates the artist.
  131. /// </summary>
  132. /// <param name="musicBrainzId">The musicBrainzId.</param>
  133. /// <param name="artistsDataPath">The artists data path.</param>
  134. /// <param name="cancellationToken">The cancellation token.</param>
  135. /// <returns>Task.</returns>
  136. private Task UpdateArtist(string musicBrainzId, string artistsDataPath, CancellationToken cancellationToken)
  137. {
  138. _logger.Info("Updating artist " + musicBrainzId);
  139. artistsDataPath = Path.Combine(artistsDataPath, musicBrainzId);
  140. if (!Directory.Exists(artistsDataPath))
  141. {
  142. Directory.CreateDirectory(artistsDataPath);
  143. }
  144. return FanArtArtistProvider.Current.DownloadArtistXml(artistsDataPath, musicBrainzId, cancellationToken);
  145. }
  146. /// <summary>
  147. /// Dates the time to unix timestamp.
  148. /// </summary>
  149. /// <param name="dateTime">The date time.</param>
  150. /// <returns>System.Double.</returns>
  151. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  152. {
  153. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  154. }
  155. public class FanArtUpdate
  156. {
  157. public string id { get; set; }
  158. public string name { get; set; }
  159. public string new_images { get; set; }
  160. public string total_images { get; set; }
  161. }
  162. }
  163. }