FanArtArtistProvider.cs 12 KB

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