FanArtArtistProvider.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. namespace MediaBrowser.Providers.Music
  25. {
  26. public class FanartArtistProvider : IRemoteImageProvider, IHasOrder
  27. {
  28. internal const string ApiKey = "5c6b04c68e904cfed1e6cbc9a9e683d4";
  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
  45. {
  46. get { return ProviderName; }
  47. }
  48. public static string ProviderName
  49. {
  50. get { return "FanArt"; }
  51. }
  52. public bool Supports(IHasMetadata item)
  53. {
  54. return item is MusicArtist;
  55. }
  56. public IEnumerable<ImageType> GetSupportedImages(IHasMetadata item)
  57. {
  58. return new List<ImageType>
  59. {
  60. ImageType.Primary,
  61. ImageType.Logo,
  62. ImageType.Art,
  63. ImageType.Banner,
  64. ImageType.Backdrop
  65. };
  66. }
  67. public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasMetadata item, CancellationToken cancellationToken)
  68. {
  69. var artist = (MusicArtist)item;
  70. var list = new List<RemoteImageInfo>();
  71. var artistMusicBrainzId = artist.GetProviderId(MetadataProviders.MusicBrainzArtist);
  72. if (!String.IsNullOrEmpty(artistMusicBrainzId))
  73. {
  74. await EnsureArtistJson(artistMusicBrainzId, cancellationToken).ConfigureAwait(false);
  75. var artistJsonPath = GetArtistJsonPath(_config.CommonApplicationPaths, artistMusicBrainzId);
  76. try
  77. {
  78. AddImages(list, artistJsonPath, cancellationToken);
  79. }
  80. catch (FileNotFoundException)
  81. {
  82. }
  83. catch (IOException)
  84. {
  85. }
  86. }
  87. var language = item.GetPreferredMetadataLanguage();
  88. var isLanguageEn = String.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
  89. // Sort first by width to prioritize HD versions
  90. return list.OrderByDescending(i => i.Width ?? 0)
  91. .ThenByDescending(i =>
  92. {
  93. if (String.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
  94. {
  95. return 3;
  96. }
  97. if (!isLanguageEn)
  98. {
  99. if (String.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
  100. {
  101. return 2;
  102. }
  103. }
  104. if (String.IsNullOrEmpty(i.Language))
  105. {
  106. return isLanguageEn ? 3 : 2;
  107. }
  108. return 0;
  109. })
  110. .ThenByDescending(i => i.CommunityRating ?? 0)
  111. .ThenByDescending(i => i.VoteCount ?? 0);
  112. }
  113. /// <summary>
  114. /// Adds the images.
  115. /// </summary>
  116. /// <param name="list">The list.</param>
  117. /// <param name="path">The path.</param>
  118. /// <param name="cancellationToken">The cancellation token.</param>
  119. private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
  120. {
  121. var obj = _jsonSerializer.DeserializeFromFile<FanartArtistResponse>(path);
  122. PopulateImages(list, obj.artistbackground, ImageType.Backdrop, 1920, 1080);
  123. PopulateImages(list, obj.artistthumb, ImageType.Primary, 500, 281);
  124. PopulateImages(list, obj.hdmusiclogo, ImageType.Logo, 800, 310);
  125. PopulateImages(list, obj.musicbanner, ImageType.Banner, 1000, 185);
  126. PopulateImages(list, obj.musiclogo, ImageType.Logo, 400, 155);
  127. PopulateImages(list, obj.hdmusicarts, ImageType.Art, 1000, 562);
  128. PopulateImages(list, obj.musicarts, ImageType.Art, 500, 281);
  129. }
  130. private Regex _regex_http = new Regex("^http://");
  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 = _regex_http.Replace(url, "https://", 1),
  156. Language = i.lang
  157. };
  158. if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Any, _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. private readonly Task _cachedTask = Task.FromResult(true);
  180. internal Task EnsureArtistJson(string musicBrainzId, CancellationToken cancellationToken)
  181. {
  182. var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
  183. var fileInfo = _fileSystem.GetFileSystemInfo(jsonPath);
  184. if (fileInfo.Exists)
  185. {
  186. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 7)
  187. {
  188. return _cachedTask;
  189. }
  190. }
  191. return DownloadArtistJson(musicBrainzId, cancellationToken);
  192. }
  193. /// <summary>
  194. /// Downloads the artist data.
  195. /// </summary>
  196. /// <param name="musicBrainzId">The music brainz id.</param>
  197. /// <param name="cancellationToken">The cancellation token.</param>
  198. /// <returns>Task{System.Boolean}.</returns>
  199. internal async Task DownloadArtistJson(string musicBrainzId, CancellationToken cancellationToken)
  200. {
  201. cancellationToken.ThrowIfCancellationRequested();
  202. var url = string.Format(FanArtBaseUrl, ApiKey, musicBrainzId);
  203. var clientKey = FanartSeriesProvider.Current.GetFanartOptions().UserApiKey;
  204. if (!string.IsNullOrWhiteSpace(clientKey))
  205. {
  206. url += "&client_key=" + clientKey;
  207. }
  208. var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
  209. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(jsonPath));
  210. try
  211. {
  212. using (var httpResponse = await _httpClient.SendAsync(new HttpRequestOptions
  213. {
  214. Url = url,
  215. CancellationToken = cancellationToken,
  216. BufferContent = true
  217. }, "GET").ConfigureAwait(false))
  218. {
  219. using (var response = httpResponse.Content)
  220. {
  221. using (var saveFileStream = _fileSystem.GetFileStream(jsonPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  222. {
  223. await response.CopyToAsync(saveFileStream).ConfigureAwait(false);
  224. }
  225. }
  226. }
  227. }
  228. catch (HttpException ex)
  229. {
  230. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  231. {
  232. _jsonSerializer.SerializeToFile(new FanartArtistResponse(), jsonPath);
  233. }
  234. else
  235. {
  236. throw;
  237. }
  238. }
  239. }
  240. /// <summary>
  241. /// Gets the artist data path.
  242. /// </summary>
  243. /// <param name="appPaths">The application paths.</param>
  244. /// <param name="musicBrainzArtistId">The music brainz artist identifier.</param>
  245. /// <returns>System.String.</returns>
  246. private static string GetArtistDataPath(IApplicationPaths appPaths, string musicBrainzArtistId)
  247. {
  248. var dataPath = Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
  249. return dataPath;
  250. }
  251. /// <summary>
  252. /// Gets the artist data path.
  253. /// </summary>
  254. /// <param name="appPaths">The application paths.</param>
  255. /// <returns>System.String.</returns>
  256. internal static string GetArtistDataPath(IApplicationPaths appPaths)
  257. {
  258. var dataPath = Path.Combine(appPaths.CachePath, "fanart-music");
  259. return dataPath;
  260. }
  261. internal static string GetArtistJsonPath(IApplicationPaths appPaths, string musicBrainzArtistId)
  262. {
  263. var dataPath = GetArtistDataPath(appPaths, musicBrainzArtistId);
  264. return Path.Combine(dataPath, "fanart.json");
  265. }
  266. public class FanartArtistImage
  267. {
  268. public string id { get; set; }
  269. public string url { get; set; }
  270. public string likes { get; set; }
  271. public string disc { get; set; }
  272. public string size { get; set; }
  273. public string lang { get; set; }
  274. }
  275. public class Album
  276. {
  277. public string release_group_id { get; set; }
  278. public List<FanartArtistImage> cdart { get; set; }
  279. public List<FanartArtistImage> albumcover { get; set; }
  280. }
  281. public class FanartArtistResponse
  282. {
  283. public string name { get; set; }
  284. public string mbid_id { get; set; }
  285. public List<FanartArtistImage> artistthumb { get; set; }
  286. public List<FanartArtistImage> artistbackground { get; set; }
  287. public List<FanartArtistImage> hdmusiclogo { get; set; }
  288. public List<FanartArtistImage> musicbanner { get; set; }
  289. public List<FanartArtistImage> musiclogo { get; set; }
  290. public List<FanartArtistImage> musicarts { get; set; }
  291. public List<FanartArtistImage> hdmusicarts { get; set; }
  292. public List<Album> albums { get; set; }
  293. }
  294. }
  295. }