jellyfin-server/MediaBrowser.Providers/TV/FanartSeriesProvider.cs

410 lines
14 KiB
C#
Raw Normal View History

using MediaBrowser.Common.Configuration;
2014-02-03 20:51:28 +00:00
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Providers;
2015-01-18 05:45:10 +00:00
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
2014-10-25 18:32:58 +00:00
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
2014-10-23 04:26:01 +00:00
using MediaBrowser.Model.Serialization;
2014-02-03 20:51:28 +00:00
using MediaBrowser.Providers.Music;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Providers.TV
{
2014-02-03 20:51:28 +00:00
public class FanartSeriesProvider : IRemoteImageProvider, IHasOrder, IHasChangeMonitor
{
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
private readonly IServerConfigurationManager _config;
private readonly IHttpClient _httpClient;
2014-02-03 20:51:28 +00:00
private readonly IFileSystem _fileSystem;
2014-10-23 04:26:01 +00:00
private readonly IJsonSerializer _json;
2014-02-03 20:51:28 +00:00
2014-10-23 04:26:01 +00:00
private const string FanArtBaseUrl = "http://webservice.fanart.tv/v3/tv/{1}?api_key={0}";
// &client_key=52c813aa7b8c8b3bb87f4797532a2f8c
2014-02-03 20:51:28 +00:00
internal static FanartSeriesProvider Current { get; private set; }
2014-10-23 04:26:01 +00:00
public FanartSeriesProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
{
_config = config;
_httpClient = httpClient;
2014-02-03 20:51:28 +00:00
_fileSystem = fileSystem;
2014-10-23 04:26:01 +00:00
_json = json;
2014-02-03 20:51:28 +00:00
Current = this;
}
public string Name
{
get { return ProviderName; }
}
public static string ProviderName
{
get { return "FanArt"; }
}
2013-12-21 18:37:34 +00:00
public bool Supports(IHasImages item)
{
return item is Series;
}
public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
{
return new List<ImageType>
{
ImageType.Primary,
ImageType.Thumb,
ImageType.Art,
ImageType.Logo,
ImageType.Backdrop,
ImageType.Banner
};
}
2014-02-13 05:11:54 +00:00
public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken)
{
var list = new List<RemoteImageInfo>();
var series = (Series)item;
var id = series.GetProviderId(MetadataProviders.Tvdb);
if (!string.IsNullOrEmpty(id))
{
2014-10-25 18:32:58 +00:00
// Bad id entered
try
{
await EnsureSeriesJson(id, cancellationToken).ConfigureAwait(false);
}
catch (HttpException ex)
{
if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
{
throw;
}
}
2014-02-03 20:51:28 +00:00
2014-10-23 04:26:01 +00:00
var path = GetFanartJsonPath(id);
try
{
2014-10-23 04:26:01 +00:00
AddImages(list, path, cancellationToken);
}
catch (FileNotFoundException)
{
// No biggie. Don't blow up
}
2014-12-23 03:58:14 +00:00
catch (DirectoryNotFoundException)
{
// No biggie. Don't blow up
}
}
var language = item.GetPreferredMetadataLanguage();
var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
// Sort first by width to prioritize HD versions
2014-02-03 20:51:28 +00:00
return list.OrderByDescending(i => i.Width ?? 0)
.ThenByDescending(i =>
{
if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
{
return 3;
}
if (!isLanguageEn)
{
if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
{
return 2;
}
}
if (string.IsNullOrEmpty(i.Language))
{
return isLanguageEn ? 3 : 2;
}
return 0;
})
.ThenByDescending(i => i.CommunityRating ?? 0)
2014-02-03 20:51:28 +00:00
.ThenByDescending(i => i.VoteCount ?? 0);
}
2014-10-23 04:26:01 +00:00
private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
{
2014-10-23 04:26:01 +00:00
var root = _json.DeserializeFromFile<RootObject>(path);
2014-10-23 04:26:01 +00:00
AddImages(list, root, cancellationToken);
}
2014-10-23 04:26:01 +00:00
private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken)
{
2014-10-23 04:26:01 +00:00
PopulateImages(list, obj.hdtvlogo, ImageType.Logo, 800, 310);
PopulateImages(list, obj.hdclearart, ImageType.Art, 1000, 562);
PopulateImages(list, obj.clearlogo, ImageType.Logo, 400, 155);
PopulateImages(list, obj.clearart, ImageType.Art, 500, 281);
PopulateImages(list, obj.showbackground, ImageType.Backdrop, 1920, 1080, true);
PopulateImages(list, obj.seasonthumb, ImageType.Thumb, 500, 281);
PopulateImages(list, obj.tvthumb, ImageType.Thumb, 500, 281);
PopulateImages(list, obj.tvbanner, ImageType.Banner, 1000, 185);
PopulateImages(list, obj.tvposter, ImageType.Primary, 1000, 1426);
}
2015-01-18 05:45:10 +00:00
private void PopulateImages(List<RemoteImageInfo> list,
List<Image> images,
ImageType type,
int width,
2014-10-23 04:26:01 +00:00
int height,
bool allowSeasonAll = false)
{
2014-10-23 04:26:01 +00:00
if (images == null)
{
return;
}
2014-10-23 04:26:01 +00:00
list.AddRange(images.Select(i =>
{
2014-10-23 04:26:01 +00:00
var url = i.url;
var season = i.season;
var isSeasonValid = string.IsNullOrEmpty(season) ||
(allowSeasonAll && string.Equals(season, "all", StringComparison.OrdinalIgnoreCase));
2014-10-23 04:26:01 +00:00
if (!string.IsNullOrEmpty(url) && isSeasonValid)
{
2014-10-23 04:26:01 +00:00
var likesString = i.likes;
int likes;
var info = new RemoteImageInfo
{
RatingType = RatingType.Likes,
Type = type,
Width = width,
Height = height,
ProviderName = Name,
Url = url,
Language = i.lang
};
if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Any, _usCulture, out likes))
{
2014-10-23 04:26:01 +00:00
info.CommunityRating = likes;
}
2014-10-23 04:26:01 +00:00
return info;
}
2014-10-23 04:26:01 +00:00
return null;
}).Where(i => i != null));
}
public int Order
{
get { return 1; }
}
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url,
ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
});
}
2014-02-03 20:51:28 +00:00
/// <summary>
/// Gets the series data path.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <param name="seriesId">The series id.</param>
/// <returns>System.String.</returns>
internal static string GetSeriesDataPath(IApplicationPaths appPaths, string seriesId)
{
var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
return seriesDataPath;
}
/// <summary>
/// Gets the series data path.
/// </summary>
/// <param name="appPaths">The app paths.</param>
/// <returns>System.String.</returns>
internal static string GetSeriesDataPath(IApplicationPaths appPaths)
{
var dataPath = Path.Combine(appPaths.CachePath, "fanart-tv");
2014-02-03 20:51:28 +00:00
return dataPath;
}
2014-10-23 04:26:01 +00:00
public string GetFanartJsonPath(string tvdbId)
2014-02-03 20:51:28 +00:00
{
var dataPath = GetSeriesDataPath(_config.ApplicationPaths, tvdbId);
2014-10-23 04:26:01 +00:00
return Path.Combine(dataPath, "fanart.json");
2014-02-03 20:51:28 +00:00
}
private readonly SemaphoreSlim _ensureSemaphore = new SemaphoreSlim(1, 1);
2014-10-23 04:26:01 +00:00
internal async Task EnsureSeriesJson(string tvdbId, CancellationToken cancellationToken)
2014-02-03 20:51:28 +00:00
{
2014-10-23 04:26:01 +00:00
var path = GetFanartJsonPath(tvdbId);
2014-02-03 20:51:28 +00:00
// Only allow one thread in here at a time since every season will be calling this method, possibly concurrently
await _ensureSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
2014-02-03 20:51:28 +00:00
try
2014-02-03 20:51:28 +00:00
{
2014-10-23 04:26:01 +00:00
var fileInfo = _fileSystem.GetFileSystemInfo(path);
if (fileInfo.Exists)
2014-02-03 20:51:28 +00:00
{
2014-10-06 23:58:46 +00:00
if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
{
return;
}
2014-02-03 20:51:28 +00:00
}
2014-10-23 04:26:01 +00:00
await DownloadSeriesJson(tvdbId, cancellationToken).ConfigureAwait(false);
}
finally
{
_ensureSemaphore.Release();
}
2014-02-03 20:51:28 +00:00
}
2015-01-18 05:45:10 +00:00
public FanartOptions GetFanartOptions()
{
return _config.GetConfiguration<FanartOptions>("fanart");
}
2014-02-03 20:51:28 +00:00
/// <summary>
2014-10-23 04:26:01 +00:00
/// Downloads the series json.
2014-02-03 20:51:28 +00:00
/// </summary>
2014-10-23 04:26:01 +00:00
/// <param name="tvdbId">The TVDB identifier.</param>
2014-02-03 20:51:28 +00:00
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
2014-10-23 04:26:01 +00:00
internal async Task DownloadSeriesJson(string tvdbId, CancellationToken cancellationToken)
2014-02-03 20:51:28 +00:00
{
cancellationToken.ThrowIfCancellationRequested();
var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, tvdbId);
2015-01-18 05:45:10 +00:00
var clientKey = GetFanartOptions().UserApiKey;
if (!string.IsNullOrWhiteSpace(clientKey))
{
2015-01-18 05:45:10 +00:00
url += "&client_key=" + clientKey;
}
2015-01-18 05:45:10 +00:00
2014-10-23 04:26:01 +00:00
var path = GetFanartJsonPath(tvdbId);
2014-02-03 20:51:28 +00:00
2014-10-23 04:26:01 +00:00
Directory.CreateDirectory(Path.GetDirectoryName(path));
2014-02-03 20:51:28 +00:00
2014-11-29 02:40:46 +00:00
try
2014-02-03 20:51:28 +00:00
{
2014-11-29 02:40:46 +00:00
using (var response = await _httpClient.Get(new HttpRequestOptions
{
Url = url,
ResourcePool = FanartArtistProvider.Current.FanArtResourcePool,
CancellationToken = cancellationToken
2014-02-03 20:51:28 +00:00
2014-11-29 02:40:46 +00:00
}).ConfigureAwait(false))
{
using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
{
await response.CopyToAsync(fileStream).ConfigureAwait(false);
}
}
}
catch (HttpException exception)
2014-02-03 20:51:28 +00:00
{
2014-11-29 02:40:46 +00:00
if (exception.StatusCode.HasValue && exception.StatusCode.Value == HttpStatusCode.NotFound)
2014-02-03 20:51:28 +00:00
{
2014-11-29 02:40:46 +00:00
// If the user has automatic updates enabled, save a dummy object to prevent repeated download attempts
_json.SerializeToFile(new RootObject(), path);
return;
2014-02-03 20:51:28 +00:00
}
2014-11-29 02:40:46 +00:00
throw;
2014-02-03 20:51:28 +00:00
}
}
2014-02-10 18:39:41 +00:00
public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
2014-02-03 20:51:28 +00:00
{
2015-01-18 05:45:10 +00:00
var options = GetFanartOptions();
if (!options.EnableAutomaticUpdates)
{
return false;
}
2014-02-03 20:51:28 +00:00
var tvdbId = item.GetProviderId(MetadataProviders.Tvdb);
if (!String.IsNullOrEmpty(tvdbId))
{
// Process images
2014-10-23 04:26:01 +00:00
var imagesFilePath = GetFanartJsonPath(tvdbId);
2014-02-03 20:51:28 +00:00
2014-10-23 04:26:01 +00:00
var fileInfo = new FileInfo(imagesFilePath);
2014-02-03 20:51:28 +00:00
return !fileInfo.Exists || _fileSystem.GetLastWriteTimeUtc(fileInfo) > date;
2014-02-03 20:51:28 +00:00
}
return false;
}
2014-10-23 04:26:01 +00:00
public class Image
{
public string id { get; set; }
public string url { get; set; }
public string lang { get; set; }
public string likes { get; set; }
public string season { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string thetvdb_id { get; set; }
public List<Image> clearlogo { get; set; }
public List<Image> hdtvlogo { get; set; }
public List<Image> clearart { get; set; }
public List<Image> showbackground { get; set; }
public List<Image> tvthumb { get; set; }
public List<Image> seasonposter { get; set; }
public List<Image> seasonthumb { get; set; }
public List<Image> hdclearart { get; set; }
public List<Image> tvbanner { get; set; }
public List<Image> characterart { get; set; }
public List<Image> tvposter { get; set; }
public List<Image> seasonbanner { get; set; }
}
}
2015-01-18 05:45:10 +00:00
public class FanartConfigStore : IConfigurationFactory
{
public IEnumerable<ConfigurationStore> GetConfigurations()
{
return new List<ConfigurationStore>
{
new ConfigurationStore
{
Key = "fanart",
ConfigurationType = typeof(FanartOptions)
}
};
}
}
}