FanArtUpdatesPrescanTask.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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 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. await UpdateArtist(id, artistsDataPath, cancellationToken).ConfigureAwait(false);
  121. numComplete++;
  122. double percent = numComplete;
  123. percent /= list.Count;
  124. percent *= 95;
  125. progress.Report(percent + 5);
  126. }
  127. }
  128. /// <summary>
  129. /// Updates the artist.
  130. /// </summary>
  131. /// <param name="musicBrainzId">The musicBrainzId.</param>
  132. /// <param name="artistsDataPath">The artists data path.</param>
  133. /// <param name="cancellationToken">The cancellation token.</param>
  134. /// <returns>Task.</returns>
  135. private Task UpdateArtist(string musicBrainzId, string artistsDataPath, CancellationToken cancellationToken)
  136. {
  137. _logger.Info("Updating artist " + musicBrainzId);
  138. artistsDataPath = Path.Combine(artistsDataPath, musicBrainzId);
  139. if (!Directory.Exists(artistsDataPath))
  140. {
  141. Directory.CreateDirectory(artistsDataPath);
  142. }
  143. return FanArtArtistProvider.Current.DownloadArtistXml(artistsDataPath, musicBrainzId, cancellationToken);
  144. }
  145. /// <summary>
  146. /// Dates the time to unix timestamp.
  147. /// </summary>
  148. /// <param name="dateTime">The date time.</param>
  149. /// <returns>System.Double.</returns>
  150. private static double DateTimeToUnixTimestamp(DateTime dateTime)
  151. {
  152. return (dateTime - new DateTime(1970, 1, 1).ToUniversalTime()).TotalSeconds;
  153. }
  154. public class FanArtUpdate
  155. {
  156. public string id { get; set; }
  157. public string name { get; set; }
  158. public string new_images { get; set; }
  159. public string total_images { get; set; }
  160. }
  161. }
  162. }