using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Providers;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Net;
using System.Net;
namespace MediaBrowser.Providers.Music
{
///
/// Class FanArtArtistProvider
///
public class FanArtArtistProvider : FanartBaseProvider
{
///
/// Gets the HTTP client.
///
/// The HTTP client.
protected IHttpClient HttpClient { get; private set; }
///
/// The _provider manager
///
private readonly IProviderManager _providerManager;
internal static FanArtArtistProvider Current;
private readonly IFileSystem _fileSystem;
///
/// Initializes a new instance of the class.
///
/// The HTTP client.
/// The log manager.
/// The configuration manager.
/// The provider manager.
/// httpClient
public FanArtArtistProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager, IFileSystem fileSystem)
: base(logManager, configurationManager)
{
if (httpClient == null)
{
throw new ArgumentNullException("httpClient");
}
HttpClient = httpClient;
_providerManager = providerManager;
_fileSystem = fileSystem;
Current = this;
}
///
/// The fan art base URL
///
protected string FanArtBaseUrl = "http://api.fanart.tv/webservice/artist/{0}/{1}/xml/all/1/1";
public override ItemUpdateType ItemUpdateType
{
get
{
return ItemUpdateType.ImageUpdate;
}
}
///
/// Supportses the specified item.
///
/// The item.
/// true if XXXX, false otherwise
public override bool Supports(BaseItem item)
{
return item is MusicArtist;
}
///
/// Gets a value indicating whether [refresh on version change].
///
/// true if [refresh on version change]; otherwise, false.
protected override bool RefreshOnVersionChange
{
get
{
return true;
}
}
///
/// Gets the provider version.
///
/// The provider version.
protected override string ProviderVersion
{
get
{
return "7";
}
}
public override MetadataProviderPriority Priority
{
get
{
return MetadataProviderPriority.Fourth;
}
}
///
/// Needses the refresh internal.
///
/// The item.
/// The provider info.
/// true if XXXX, false otherwise
protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
{
if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Musicbrainz)))
{
return false;
}
return base.NeedsRefreshInternal(item, providerInfo);
}
protected override bool NeedsRefreshBasedOnCompareDate(BaseItem item, BaseProviderInfo providerInfo)
{
var musicBrainzId = item.GetProviderId(MetadataProviders.Musicbrainz);
if (!string.IsNullOrEmpty(musicBrainzId))
{
// Process images
var artistXmlPath = GetArtistDataPath(ConfigurationManager.CommonApplicationPaths, musicBrainzId);
artistXmlPath = Path.Combine(artistXmlPath, "fanart.xml");
var file = new FileInfo(artistXmlPath);
return !file.Exists || _fileSystem.GetLastWriteTimeUtc(file) > providerInfo.LastRefreshed;
}
return base.NeedsRefreshBasedOnCompareDate(item, providerInfo);
}
///
/// The us culture
///
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
///
/// Gets the artist data path.
///
/// The application paths.
/// The music brainz artist identifier.
/// System.String.
internal static string GetArtistDataPath(IApplicationPaths appPaths, string musicBrainzArtistId)
{
var dataPath = Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
return dataPath;
}
///
/// Gets the artist data path.
///
/// The application paths.
/// System.String.
internal static string GetArtistDataPath(IApplicationPaths appPaths)
{
var dataPath = Path.Combine(appPaths.DataPath, "fanart-music");
return dataPath;
}
///
/// Fetches metadata and returns true or false indicating if any work that requires persistence was done
///
/// The item.
/// if set to true [force].
/// The cancellation token.
/// Task{System.Boolean}.
public override async Task FetchAsync(BaseItem item, bool force, BaseProviderInfo providerInfo, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var musicBrainzId = item.GetProviderId(MetadataProviders.Musicbrainz);
var artistDataPath = GetArtistDataPath(ConfigurationManager.ApplicationPaths, musicBrainzId);
var xmlPath = Path.Combine(artistDataPath, "fanart.xml");
// Only download the xml if it doesn't already exist. The prescan task will take care of getting updates
if (!File.Exists(xmlPath))
{
await DownloadArtistXml(artistDataPath, musicBrainzId, cancellationToken).ConfigureAwait(false);
}
if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Art ||
ConfigurationManager.Configuration.DownloadMusicArtistImages.Backdrops ||
ConfigurationManager.Configuration.DownloadMusicArtistImages.Banner ||
ConfigurationManager.Configuration.DownloadMusicArtistImages.Logo ||
ConfigurationManager.Configuration.DownloadMusicArtistImages.Primary)
{
var images = await _providerManager.GetAvailableRemoteImages(item, cancellationToken, ManualFanartArtistProvider.ProviderName).ConfigureAwait(false);
await FetchFromXml(item, images.ToList(), cancellationToken).ConfigureAwait(false);
}
SetLastRefreshed(item, DateTime.UtcNow, providerInfo);
return true;
}
///
/// Downloads the artist XML.
///
/// The artist path.
/// The music brainz id.
/// The cancellation token.
/// Task{System.Boolean}.
internal async Task DownloadArtistXml(string artistPath, string musicBrainzId, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var url = string.Format(FanArtBaseUrl, ApiKey, musicBrainzId);
var xmlPath = Path.Combine(artistPath, "fanart.xml");
Directory.CreateDirectory(artistPath);
using (var response = await HttpClient.Get(new HttpRequestOptions
{
Url = url,
ResourcePool = FanArtResourcePool,
CancellationToken = cancellationToken
}).ConfigureAwait(false))
{
using (var xmlFileStream = _fileSystem.GetFileStream(xmlPath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
{
await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
}
}
}
///
/// Fetches from XML.
///
/// The item.
/// The images.
/// The cancellation token.
/// Task.
private async Task FetchFromXml(BaseItem item, List images , CancellationToken cancellationToken)
{
if (!item.LockedFields.Contains(MetadataFields.Images))
{
cancellationToken.ThrowIfCancellationRequested();
if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Primary && !item.HasImage(ImageType.Primary))
{
await SaveImage(item, images, ImageType.Primary, cancellationToken).ConfigureAwait(false);
}
cancellationToken.ThrowIfCancellationRequested();
if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Logo && !item.HasImage(ImageType.Logo))
{
await SaveImage(item, images, ImageType.Logo, cancellationToken).ConfigureAwait(false);
}
cancellationToken.ThrowIfCancellationRequested();
if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Art && !item.HasImage(ImageType.Art))
{
await SaveImage(item, images, ImageType.Art, cancellationToken).ConfigureAwait(false);
}
cancellationToken.ThrowIfCancellationRequested();
if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Banner && !item.HasImage(ImageType.Banner))
{
await SaveImage(item, images, ImageType.Banner, cancellationToken).ConfigureAwait(false);
}
}
if (!item.LockedFields.Contains(MetadataFields.Backdrops))
{
cancellationToken.ThrowIfCancellationRequested();
var backdropLimit = ConfigurationManager.Configuration.MusicOptions.MaxBackdrops;
if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Backdrops &&
item.BackdropImagePaths.Count < backdropLimit)
{
foreach (var image in images.Where(i => i.Type == ImageType.Backdrop))
{
await _providerManager.SaveImage(item, image.Url, FanArtResourcePool, ImageType.Backdrop, null, cancellationToken)
.ConfigureAwait(false);
if (item.BackdropImagePaths.Count >= backdropLimit) break;
}
}
}
}
private async Task SaveImage(BaseItem item, List images, ImageType type, CancellationToken cancellationToken)
{
foreach (var image in images.Where(i => i.Type == type))
{
try
{
await _providerManager.SaveImage(item, image.Url, FanArtResourcePool, type, null, cancellationToken).ConfigureAwait(false);
break;
}
catch (HttpException ex)
{
// Sometimes fanart has bad url's in their xml
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
{
continue;
}
break;
}
}
}
}
}