FanArtArtistProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Common.Net;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Entities.Audio;
  14. using MediaBrowser.Controller.Providers;
  15. using MediaBrowser.Model.Dto;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Extensions;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.Net;
  20. using MediaBrowser.Model.Providers;
  21. using MediaBrowser.Model.Serialization;
  22. using MediaBrowser.Providers.TV;
  23. namespace MediaBrowser.Providers.Music
  24. {
  25. public class FanartArtistProvider : IRemoteImageProvider, IHasOrder
  26. {
  27. internal const string ApiKey = "184e1a2b1fe3b94935365411f919f638";
  28. private const string FanArtBaseUrl = "https://webservice.fanart.tv/v3.1/music/{1}?api_key={0}";
  29. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  30. private readonly IServerConfigurationManager _config;
  31. private readonly IHttpClient _httpClient;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly IJsonSerializer _jsonSerializer;
  34. internal static FanartArtistProvider Current;
  35. public FanartArtistProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
  36. {
  37. _config = config;
  38. _httpClient = httpClient;
  39. _fileSystem = fileSystem;
  40. _jsonSerializer = jsonSerializer;
  41. Current = this;
  42. }
  43. public string Name => ProviderName;
  44. public static string ProviderName => "FanArt";
  45. public bool Supports(BaseItem item)
  46. {
  47. return item is MusicArtist;
  48. }
  49. public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
  50. {
  51. return new List<ImageType>
  52. {
  53. ImageType.Primary,
  54. ImageType.Logo,
  55. ImageType.Art,
  56. ImageType.Banner,
  57. ImageType.Backdrop
  58. };
  59. }
  60. public async Task<IEnumerable<RemoteImageInfo>> GetImages(BaseItem item, CancellationToken cancellationToken)
  61. {
  62. var artist = (MusicArtist)item;
  63. var list = new List<RemoteImageInfo>();
  64. var artistMusicBrainzId = artist.GetProviderId(MetadataProviders.MusicBrainzArtist);
  65. if (!string.IsNullOrEmpty(artistMusicBrainzId))
  66. {
  67. await EnsureArtistJson(artistMusicBrainzId, cancellationToken).ConfigureAwait(false);
  68. var artistJsonPath = GetArtistJsonPath(_config.CommonApplicationPaths, artistMusicBrainzId);
  69. try
  70. {
  71. AddImages(list, artistJsonPath, cancellationToken);
  72. }
  73. catch (FileNotFoundException)
  74. {
  75. }
  76. catch (IOException)
  77. {
  78. }
  79. }
  80. var language = item.GetPreferredMetadataLanguage();
  81. var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
  82. // Sort first by width to prioritize HD versions
  83. return list.OrderByDescending(i => i.Width ?? 0)
  84. .ThenByDescending(i =>
  85. {
  86. if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
  87. {
  88. return 3;
  89. }
  90. if (!isLanguageEn)
  91. {
  92. if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
  93. {
  94. return 2;
  95. }
  96. }
  97. if (string.IsNullOrEmpty(i.Language))
  98. {
  99. return isLanguageEn ? 3 : 2;
  100. }
  101. return 0;
  102. })
  103. .ThenByDescending(i => i.CommunityRating ?? 0)
  104. .ThenByDescending(i => i.VoteCount ?? 0);
  105. }
  106. /// <summary>
  107. /// Adds the images.
  108. /// </summary>
  109. /// <param name="list">The list.</param>
  110. /// <param name="path">The path.</param>
  111. /// <param name="cancellationToken">The cancellation token.</param>
  112. private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
  113. {
  114. var obj = _jsonSerializer.DeserializeFromFile<FanartArtistResponse>(path);
  115. PopulateImages(list, obj.artistbackground, ImageType.Backdrop, 1920, 1080);
  116. PopulateImages(list, obj.artistthumb, ImageType.Primary, 500, 281);
  117. PopulateImages(list, obj.hdmusiclogo, ImageType.Logo, 800, 310);
  118. PopulateImages(list, obj.musicbanner, ImageType.Banner, 1000, 185);
  119. PopulateImages(list, obj.musiclogo, ImageType.Logo, 400, 155);
  120. PopulateImages(list, obj.hdmusicarts, ImageType.Art, 1000, 562);
  121. PopulateImages(list, obj.musicarts, ImageType.Art, 500, 281);
  122. }
  123. private void PopulateImages(List<RemoteImageInfo> list,
  124. List<FanartArtistImage> images,
  125. ImageType type,
  126. int width,
  127. int height)
  128. {
  129. if (images == null)
  130. {
  131. return;
  132. }
  133. list.AddRange(images.Select(i =>
  134. {
  135. var url = i.url;
  136. if (!string.IsNullOrEmpty(url))
  137. {
  138. var likesString = i.likes;
  139. var info = new RemoteImageInfo
  140. {
  141. RatingType = RatingType.Likes,
  142. Type = type,
  143. Width = width,
  144. Height = height,
  145. ProviderName = Name,
  146. Url = url.Replace("http://", "https://", StringComparison.OrdinalIgnoreCase),
  147. Language = i.lang
  148. };
  149. if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Integer, _usCulture, out var likes))
  150. {
  151. info.CommunityRating = likes;
  152. }
  153. return info;
  154. }
  155. return null;
  156. }).Where(i => i != null));
  157. }
  158. public int Order => 0;
  159. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  160. {
  161. return _httpClient.GetResponse(new HttpRequestOptions
  162. {
  163. CancellationToken = cancellationToken,
  164. Url = url
  165. });
  166. }
  167. internal Task EnsureArtistJson(string musicBrainzId, CancellationToken cancellationToken)
  168. {
  169. var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
  170. var fileInfo = _fileSystem.GetFileSystemInfo(jsonPath);
  171. if (fileInfo.Exists)
  172. {
  173. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
  174. {
  175. return Task.CompletedTask;
  176. }
  177. }
  178. return DownloadArtistJson(musicBrainzId, cancellationToken);
  179. }
  180. /// <summary>
  181. /// Downloads the artist data.
  182. /// </summary>
  183. /// <param name="musicBrainzId">The music brainz id.</param>
  184. /// <param name="cancellationToken">The cancellation token.</param>
  185. /// <returns>Task{System.Boolean}.</returns>
  186. internal async Task DownloadArtistJson(string musicBrainzId, CancellationToken cancellationToken)
  187. {
  188. cancellationToken.ThrowIfCancellationRequested();
  189. var url = string.Format(FanArtBaseUrl, ApiKey, musicBrainzId);
  190. var clientKey = FanartSeriesProvider.Current.GetFanartOptions().UserApiKey;
  191. if (!string.IsNullOrWhiteSpace(clientKey))
  192. {
  193. url += "&client_key=" + clientKey;
  194. }
  195. var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
  196. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(jsonPath));
  197. try
  198. {
  199. using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
  200. {
  201. Url = url,
  202. CancellationToken = cancellationToken,
  203. BufferContent = true
  204. }, "GET").ConfigureAwait(false))
  205. {
  206. using (var response = httpResponse.Content)
  207. {
  208. using (var saveFileStream = _fileSystem.GetFileStream(jsonPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  209. {
  210. await response.CopyToAsync(saveFileStream).ConfigureAwait(false);
  211. }
  212. }
  213. }
  214. }
  215. catch (HttpException ex)
  216. {
  217. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  218. {
  219. _jsonSerializer.SerializeToFile(new FanartArtistResponse(), jsonPath);
  220. }
  221. else
  222. {
  223. throw;
  224. }
  225. }
  226. }
  227. /// <summary>
  228. /// Gets the artist data path.
  229. /// </summary>
  230. /// <param name="appPaths">The application paths.</param>
  231. /// <param name="musicBrainzArtistId">The music brainz artist identifier.</param>
  232. /// <returns>System.String.</returns>
  233. private static string GetArtistDataPath(IApplicationPaths appPaths, string musicBrainzArtistId)
  234. {
  235. var dataPath = Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
  236. return dataPath;
  237. }
  238. /// <summary>
  239. /// Gets the artist data path.
  240. /// </summary>
  241. /// <param name="appPaths">The application paths.</param>
  242. /// <returns>System.String.</returns>
  243. internal static string GetArtistDataPath(IApplicationPaths appPaths)
  244. {
  245. var dataPath = Path.Combine(appPaths.CachePath, "fanart-music");
  246. return dataPath;
  247. }
  248. internal static string GetArtistJsonPath(IApplicationPaths appPaths, string musicBrainzArtistId)
  249. {
  250. var dataPath = GetArtistDataPath(appPaths, musicBrainzArtistId);
  251. return Path.Combine(dataPath, "fanart.json");
  252. }
  253. public class FanartArtistImage
  254. {
  255. public string id { get; set; }
  256. public string url { get; set; }
  257. public string likes { get; set; }
  258. public string disc { get; set; }
  259. public string size { get; set; }
  260. public string lang { get; set; }
  261. }
  262. public class Album
  263. {
  264. public string release_group_id { get; set; }
  265. public List<FanartArtistImage> cdart { get; set; }
  266. public List<FanartArtistImage> albumcover { get; set; }
  267. }
  268. public class FanartArtistResponse
  269. {
  270. public string name { get; set; }
  271. public string mbid_id { get; set; }
  272. public List<FanartArtistImage> artistthumb { get; set; }
  273. public List<FanartArtistImage> artistbackground { get; set; }
  274. public List<FanartArtistImage> hdmusiclogo { get; set; }
  275. public List<FanartArtistImage> musicbanner { get; set; }
  276. public List<FanartArtistImage> musiclogo { get; set; }
  277. public List<FanartArtistImage> musicarts { get; set; }
  278. public List<FanartArtistImage> hdmusicarts { get; set; }
  279. public List<Album> albums { get; set; }
  280. }
  281. }
  282. }