FanArtArtistProvider.cs 12 KB

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