FanArtTvUpdatesPrescanTask.cs 7.5 KB

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