FanArtArtistProvider.cs 12 KB

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