LastfmAlbumProvider.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Providers;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Providers;
  8. using MediaBrowser.Model.Serialization;
  9. using MoreLinq;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Providers.Music
  18. {
  19. public class LastfmAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder
  20. {
  21. private readonly IJsonSerializer _json;
  22. private readonly IHttpClient _httpClient;
  23. private readonly IServerConfigurationManager _config;
  24. private readonly ILogger _logger;
  25. public LastfmAlbumProvider(IHttpClient httpClient, IJsonSerializer json, IServerConfigurationManager config, ILogger logger)
  26. {
  27. _httpClient = httpClient;
  28. _json = json;
  29. _config = config;
  30. _logger = logger;
  31. }
  32. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
  33. {
  34. return new List<RemoteSearchResult>();
  35. }
  36. public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo id, CancellationToken cancellationToken)
  37. {
  38. var result = new MetadataResult<MusicAlbum>();
  39. var lastFmData = await GetAlbumResult(id, cancellationToken).ConfigureAwait(false);
  40. if (lastFmData != null && lastFmData.album != null)
  41. {
  42. result.HasMetadata = true;
  43. result.Item = new MusicAlbum();
  44. ProcessAlbumData(result.Item, lastFmData.album);
  45. }
  46. return result;
  47. }
  48. private async Task<LastfmGetAlbumResult> GetAlbumResult(AlbumInfo item, CancellationToken cancellationToken)
  49. {
  50. // Try album release Id
  51. var id = item.GetReleaseId();
  52. if (!string.IsNullOrEmpty(id))
  53. {
  54. var result = await GetAlbumResult(id, cancellationToken).ConfigureAwait(false);
  55. if (result != null && result.album != null)
  56. {
  57. return result;
  58. }
  59. }
  60. // Try album release group Id
  61. id = item.GetReleaseGroupId();
  62. if (!string.IsNullOrEmpty(id))
  63. {
  64. var result = await GetAlbumResult(id, cancellationToken).ConfigureAwait(false);
  65. if (result != null && result.album != null)
  66. {
  67. return result;
  68. }
  69. }
  70. var albumArtist = item.GetAlbumArtist();
  71. // Get each song, distinct by the combination of AlbumArtist and Album
  72. var songs = item.SongInfos.DistinctBy(i => (i.AlbumArtist ?? string.Empty) + (i.Album ?? string.Empty), StringComparer.OrdinalIgnoreCase).ToList();
  73. foreach (var song in songs.Where(song => !string.IsNullOrEmpty(song.Album) && !string.IsNullOrEmpty(song.AlbumArtist)))
  74. {
  75. var result = await GetAlbumResult(song.AlbumArtist, song.Album, cancellationToken).ConfigureAwait(false);
  76. if (result != null && result.album != null)
  77. {
  78. return result;
  79. }
  80. }
  81. if (string.IsNullOrEmpty(albumArtist))
  82. {
  83. return null;
  84. }
  85. return await GetAlbumResult(albumArtist, item.Name, cancellationToken);
  86. }
  87. private async Task<LastfmGetAlbumResult> GetAlbumResult(string artist, string album, CancellationToken cancellationToken)
  88. {
  89. // Get albu info using artist and album name
  90. var url = LastfmArtistProvider.RootUrl + string.Format("method=album.getInfo&artist={0}&album={1}&api_key={2}&format=json", UrlEncode(artist), UrlEncode(album), LastfmArtistProvider.ApiKey);
  91. using (var json = await _httpClient.Get(new HttpRequestOptions
  92. {
  93. Url = url,
  94. ResourcePool = LastfmArtistProvider.LastfmResourcePool,
  95. CancellationToken = cancellationToken,
  96. EnableHttpCompression = false
  97. }).ConfigureAwait(false))
  98. {
  99. using (var reader = new StreamReader(json))
  100. {
  101. var jsonText = await reader.ReadToEndAsync().ConfigureAwait(false);
  102. // Fix their bad json
  103. jsonText = jsonText.Replace("\"#text\"", "\"url\"");
  104. return _json.DeserializeFromString<LastfmGetAlbumResult>(jsonText);
  105. }
  106. }
  107. }
  108. private async Task<LastfmGetAlbumResult> GetAlbumResult(string musicbraizId, CancellationToken cancellationToken)
  109. {
  110. // Get albu info using artist and album name
  111. var url = LastfmArtistProvider.RootUrl + string.Format("method=album.getInfo&mbid={0}&api_key={1}&format=json", musicbraizId, LastfmArtistProvider.ApiKey);
  112. using (var json = await _httpClient.Get(new HttpRequestOptions
  113. {
  114. Url = url,
  115. ResourcePool = LastfmArtistProvider.LastfmResourcePool,
  116. CancellationToken = cancellationToken,
  117. EnableHttpCompression = false
  118. }).ConfigureAwait(false))
  119. {
  120. return _json.DeserializeFromStream<LastfmGetAlbumResult>(json);
  121. }
  122. }
  123. private void ProcessAlbumData(MusicAlbum item, LastfmAlbum data)
  124. {
  125. var overview = data.wiki != null ? data.wiki.content : null;
  126. if (!item.LockedFields.Contains(MetadataFields.Overview))
  127. {
  128. item.Overview = overview;
  129. }
  130. // Only grab the date here if the album doesn't already have one, since id3 tags are preferred
  131. DateTime release;
  132. if (DateTime.TryParse(data.releasedate, out release))
  133. {
  134. // Lastfm sends back null as sometimes 1901, other times 0
  135. if (release.Year > 1901)
  136. {
  137. if (!item.PremiereDate.HasValue)
  138. {
  139. item.PremiereDate = release;
  140. }
  141. if (!item.ProductionYear.HasValue)
  142. {
  143. item.ProductionYear = release.Year;
  144. }
  145. }
  146. }
  147. string imageSize;
  148. var url = LastfmHelper.GetImageUrl(data, out imageSize);
  149. var musicBrainzId = item.GetProviderId(MetadataProviders.MusicBrainzAlbum) ??
  150. item.GetProviderId(MetadataProviders.MusicBrainzReleaseGroup);
  151. if (!string.IsNullOrEmpty(musicBrainzId) && !string.IsNullOrEmpty(url))
  152. {
  153. LastfmHelper.SaveImageInfo(_config.ApplicationPaths, _logger, musicBrainzId, url, imageSize);
  154. }
  155. }
  156. /// <summary>
  157. /// Encodes an URL.
  158. /// </summary>
  159. /// <param name="name">The name.</param>
  160. /// <returns>System.String.</returns>
  161. private string UrlEncode(string name)
  162. {
  163. return WebUtility.UrlEncode(name);
  164. }
  165. public string Name
  166. {
  167. get { return "last.fm"; }
  168. }
  169. public int Order
  170. {
  171. get
  172. {
  173. // After fanart & audiodb
  174. return 2;
  175. }
  176. }
  177. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  178. {
  179. throw new NotImplementedException();
  180. }
  181. }
  182. #region Result Objects
  183. public class LastfmStats
  184. {
  185. public string listeners { get; set; }
  186. public string playcount { get; set; }
  187. }
  188. public class LastfmTag
  189. {
  190. public string name { get; set; }
  191. public string url { get; set; }
  192. }
  193. public class LastfmTags
  194. {
  195. public List<LastfmTag> tag { get; set; }
  196. }
  197. public class LastfmFormationInfo
  198. {
  199. public string yearfrom { get; set; }
  200. public string yearto { get; set; }
  201. }
  202. public class LastFmBio
  203. {
  204. public string published { get; set; }
  205. public string summary { get; set; }
  206. public string content { get; set; }
  207. public string placeformed { get; set; }
  208. public string yearformed { get; set; }
  209. public List<LastfmFormationInfo> formationlist { get; set; }
  210. }
  211. public class LastFmImage
  212. {
  213. public string url { get; set; }
  214. public string size { get; set; }
  215. }
  216. public class LastfmArtist : IHasLastFmImages
  217. {
  218. public string name { get; set; }
  219. public string mbid { get; set; }
  220. public string url { get; set; }
  221. public string streamable { get; set; }
  222. public string ontour { get; set; }
  223. public LastfmStats stats { get; set; }
  224. public List<LastfmArtist> similar { get; set; }
  225. public LastfmTags tags { get; set; }
  226. public LastFmBio bio { get; set; }
  227. public List<LastFmImage> image { get; set; }
  228. }
  229. public class LastfmAlbum : IHasLastFmImages
  230. {
  231. public string name { get; set; }
  232. public string artist { get; set; }
  233. public string id { get; set; }
  234. public string mbid { get; set; }
  235. public string releasedate { get; set; }
  236. public int listeners { get; set; }
  237. public int playcount { get; set; }
  238. public LastfmTags toptags { get; set; }
  239. public LastFmBio wiki { get; set; }
  240. public List<LastFmImage> image { get; set; }
  241. }
  242. public interface IHasLastFmImages
  243. {
  244. List<LastFmImage> image { get; set; }
  245. }
  246. public class LastfmGetAlbumResult
  247. {
  248. public LastfmAlbum album { get; set; }
  249. }
  250. public class LastfmGetArtistResult
  251. {
  252. public LastfmArtist artist { get; set; }
  253. }
  254. public class Artistmatches
  255. {
  256. public List<LastfmArtist> artist { get; set; }
  257. }
  258. public class LastfmArtistSearchResult
  259. {
  260. public Artistmatches artistmatches { get; set; }
  261. }
  262. public class LastfmArtistSearchResults
  263. {
  264. public LastfmArtistSearchResult results { get; set; }
  265. }
  266. #endregion
  267. }