LastfmAlbumProvider.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.IO;
  2. using System.Net;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.Serialization;
  12. namespace MediaBrowser.Controller.Providers.Music
  13. {
  14. public class LastfmAlbumProvider : LastfmBaseProvider
  15. {
  16. private static readonly Task<string> BlankId = Task.FromResult("0000");
  17. private readonly IProviderManager _providerManager;
  18. public LastfmAlbumProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  19. : base(jsonSerializer, httpClient, logManager, configurationManager)
  20. {
  21. _providerManager = providerManager;
  22. LocalMetaFileName = LastfmHelper.LocalAlbumMetaFileName;
  23. }
  24. protected override Task<string> FindId(BaseItem item, CancellationToken cancellationToken)
  25. {
  26. // We don't fetch by id
  27. return BlankId;
  28. }
  29. protected override async Task FetchLastfmData(BaseItem item, string id, CancellationToken cancellationToken)
  30. {
  31. // Get albu info using artist and album name
  32. var url = RootUrl + string.Format("method=album.getInfo&artist={0}&album={1}&api_key={2}&format=json", UrlEncode(item.Parent.Name), UrlEncode(item.Name), ApiKey);
  33. LastfmGetAlbumResult result = null;
  34. try
  35. {
  36. using (var json = await HttpClient.Get(url, LastfmResourcePool, cancellationToken).ConfigureAwait(false))
  37. {
  38. result = JsonSerializer.DeserializeFromStream<LastfmGetAlbumResult>(json);
  39. }
  40. }
  41. catch (HttpException e)
  42. {
  43. if (e.StatusCode == HttpStatusCode.NotFound)
  44. {
  45. throw new LastfmProviderException(string.Format("Unable to retrieve album info for {0} with artist {1}", item.Name, item.Parent.Name));
  46. }
  47. throw;
  48. }
  49. if (result != null && result.album != null)
  50. {
  51. LastfmHelper.ProcessAlbumData(item, result.album);
  52. //And save locally if indicated
  53. if (ConfigurationManager.Configuration.SaveLocalMeta)
  54. {
  55. var ms = new MemoryStream();
  56. JsonSerializer.SerializeToStream(result.album, ms);
  57. cancellationToken.ThrowIfCancellationRequested();
  58. await _providerManager.SaveToLibraryFilesystem(item, Path.Combine(item.MetaLocation, LocalMetaFileName), ms, cancellationToken).ConfigureAwait(false);
  59. }
  60. }
  61. }
  62. public override bool Supports(BaseItem item)
  63. {
  64. return item is MusicAlbum;
  65. }
  66. }
  67. }