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.Common.IO;
  21. using MediaBrowser.Controller.IO;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.Net;
  24. using MediaBrowser.Model.Serialization;
  25. namespace MediaBrowser.Providers.Music
  26. {
  27. public class FanartArtistProvider : IRemoteImageProvider, IHasOrder
  28. {
  29. internal readonly SemaphoreSlim FanArtResourcePool = new SemaphoreSlim(3, 3);
  30. internal const string ApiKey = "5c6b04c68e904cfed1e6cbc9a9e683d4";
  31. private const string FanArtBaseUrl = "https://webservice.fanart.tv/v3.1/music/{1}?api_key={0}";
  32. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  33. private readonly IServerConfigurationManager _config;
  34. private readonly IHttpClient _httpClient;
  35. private readonly IFileSystem _fileSystem;
  36. private readonly IJsonSerializer _jsonSerializer;
  37. internal static FanartArtistProvider Current;
  38. public FanartArtistProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer jsonSerializer)
  39. {
  40. _config = config;
  41. _httpClient = httpClient;
  42. _fileSystem = fileSystem;
  43. _jsonSerializer = jsonSerializer;
  44. Current = this;
  45. }
  46. public string Name
  47. {
  48. get { return ProviderName; }
  49. }
  50. public static string ProviderName
  51. {
  52. get { return "FanArt"; }
  53. }
  54. public bool Supports(IHasImages item)
  55. {
  56. return item is MusicArtist;
  57. }
  58. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  59. {
  60. return new List<ImageType>
  61. {
  62. ImageType.Primary,
  63. ImageType.Logo,
  64. ImageType.Art,
  65. ImageType.Banner,
  66. ImageType.Backdrop
  67. };
  68. }
  69. public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken)
  70. {
  71. var artist = (MusicArtist)item;
  72. var list = new List<RemoteImageInfo>();
  73. var artistMusicBrainzId = artist.GetProviderId(MetadataProviders.MusicBrainzArtist);
  74. if (!String.IsNullOrEmpty(artistMusicBrainzId))
  75. {
  76. await EnsureArtistJson(artistMusicBrainzId, cancellationToken).ConfigureAwait(false);
  77. var artistJsonPath = GetArtistJsonPath(_config.CommonApplicationPaths, artistMusicBrainzId);
  78. try
  79. {
  80. AddImages(list, artistJsonPath, cancellationToken);
  81. }
  82. catch (FileNotFoundException)
  83. {
  84. }
  85. catch (IOException)
  86. {
  87. }
  88. }
  89. var language = item.GetPreferredMetadataLanguage();
  90. var isLanguageEn = String.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
  91. // Sort first by width to prioritize HD versions
  92. return list.OrderByDescending(i => i.Width ?? 0)
  93. .ThenByDescending(i =>
  94. {
  95. if (String.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
  96. {
  97. return 3;
  98. }
  99. if (!isLanguageEn)
  100. {
  101. if (String.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
  102. {
  103. return 2;
  104. }
  105. }
  106. if (String.IsNullOrEmpty(i.Language))
  107. {
  108. return isLanguageEn ? 3 : 2;
  109. }
  110. return 0;
  111. })
  112. .ThenByDescending(i => i.CommunityRating ?? 0)
  113. .ThenByDescending(i => i.VoteCount ?? 0);
  114. }
  115. /// <summary>
  116. /// Adds the images.
  117. /// </summary>
  118. /// <param name="list">The list.</param>
  119. /// <param name="path">The path.</param>
  120. /// <param name="cancellationToken">The cancellation token.</param>
  121. private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
  122. {
  123. var obj = _jsonSerializer.DeserializeFromFile<FanartArtistResponse>(path);
  124. PopulateImages(list, obj.artistbackground, ImageType.Backdrop, 1920, 1080);
  125. PopulateImages(list, obj.artistthumb, ImageType.Primary, 500, 281);
  126. PopulateImages(list, obj.hdmusiclogo, ImageType.Logo, 800, 310);
  127. PopulateImages(list, obj.musicbanner, ImageType.Banner, 1000, 185);
  128. PopulateImages(list, obj.musiclogo, ImageType.Logo, 400, 155);
  129. PopulateImages(list, obj.hdmusicarts, ImageType.Art, 1000, 562);
  130. PopulateImages(list, obj.musicarts, ImageType.Art, 500, 281);
  131. }
  132. private Regex _regex_http = new Regex("^http://");
  133. private void PopulateImages(List<RemoteImageInfo> list,
  134. List<FanartArtistImage> images,
  135. ImageType type,
  136. int width,
  137. int height)
  138. {
  139. if (images == null)
  140. {
  141. return;
  142. }
  143. list.AddRange(images.Select(i =>
  144. {
  145. var url = i.url;
  146. if (!string.IsNullOrEmpty(url))
  147. {
  148. var likesString = i.likes;
  149. int likes;
  150. var info = new RemoteImageInfo
  151. {
  152. RatingType = RatingType.Likes,
  153. Type = type,
  154. Width = width,
  155. Height = height,
  156. ProviderName = Name,
  157. Url = _regex_http.Replace(url, "https://", 1),
  158. Language = i.lang
  159. };
  160. if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Any, _usCulture, out likes))
  161. {
  162. info.CommunityRating = likes;
  163. }
  164. return info;
  165. }
  166. return null;
  167. }).Where(i => i != null));
  168. }
  169. public int Order
  170. {
  171. get { return 0; }
  172. }
  173. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  174. {
  175. return _httpClient.GetResponse(new HttpRequestOptions
  176. {
  177. CancellationToken = cancellationToken,
  178. Url = url
  179. });
  180. }
  181. private readonly Task _cachedTask = Task.FromResult(true);
  182. internal Task EnsureArtistJson(string musicBrainzId, CancellationToken cancellationToken)
  183. {
  184. var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
  185. var fileInfo = _fileSystem.GetFileSystemInfo(jsonPath);
  186. if (fileInfo.Exists)
  187. {
  188. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 7)
  189. {
  190. return _cachedTask;
  191. }
  192. }
  193. return DownloadArtistJson(musicBrainzId, cancellationToken);
  194. }
  195. /// <summary>
  196. /// Downloads the artist data.
  197. /// </summary>
  198. /// <param name="musicBrainzId">The music brainz id.</param>
  199. /// <param name="cancellationToken">The cancellation token.</param>
  200. /// <returns>Task{System.Boolean}.</returns>
  201. internal async Task DownloadArtistJson(string musicBrainzId, CancellationToken cancellationToken)
  202. {
  203. cancellationToken.ThrowIfCancellationRequested();
  204. var url = string.Format(FanArtBaseUrl, ApiKey, musicBrainzId);
  205. var clientKey = FanartSeriesProvider.Current.GetFanartOptions().UserApiKey;
  206. if (!string.IsNullOrWhiteSpace(clientKey))
  207. {
  208. url += "&client_key=" + clientKey;
  209. }
  210. var jsonPath = GetArtistJsonPath(_config.ApplicationPaths, musicBrainzId);
  211. _fileSystem.CreateDirectory(Path.GetDirectoryName(jsonPath));
  212. try
  213. {
  214. using (var response = await _httpClient.Get(new HttpRequestOptions
  215. {
  216. Url = url,
  217. ResourcePool = FanArtResourcePool,
  218. CancellationToken = cancellationToken,
  219. BufferContent = true
  220. }).ConfigureAwait(false))
  221. {
  222. using (var saveFileStream = _fileSystem.GetFileStream(jsonPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  223. {
  224. await response.CopyToAsync(saveFileStream).ConfigureAwait(false);
  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. }