You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
jellyfin/MediaBrowser.Providers/Plugins/TheTvdb/TvdbClientManager.cs

290 lines
11 KiB

#pragma warning disable CS1591
using System;
using System.Collections.Generic;
4 years ago
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
6 years ago
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
6 years ago
using Microsoft.Extensions.Caching.Memory;
using TvDbSharper;
6 years ago
using TvDbSharper.Dto;
namespace MediaBrowser.Providers.Plugins.TheTvdb
{
public class TvdbClientManager
{
5 years ago
private const string DefaultLanguage = "en";
private readonly IMemoryCache _cache;
private readonly TvDbClient _tvDbClient;
private DateTime _tokenCreatedAt;
public TvdbClientManager(IMemoryCache memoryCache)
{
_cache = memoryCache;
_tvDbClient = new TvDbClient();
}
private TvDbClient TvDbClient
{
get
{
if (string.IsNullOrEmpty(_tvDbClient.Authentication.Token))
{
_tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey).GetAwaiter().GetResult();
_tokenCreatedAt = DateTime.Now;
}
// Refresh if necessary
if (_tokenCreatedAt < DateTime.Now.Subtract(TimeSpan.FromHours(20)))
{
try
{
_tvDbClient.Authentication.RefreshTokenAsync().GetAwaiter().GetResult();
}
catch
{
_tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey).GetAwaiter().GetResult();
}
_tokenCreatedAt = DateTime.Now;
}
return _tvDbClient;
}
}
6 years ago
public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByNameAsync(string name, string language,
CancellationToken cancellationToken)
6 years ago
{
var cacheKey = GenerateKey("series", name, language);
return TryGetValue(cacheKey, language, () => TvDbClient.Search.SearchSeriesByNameAsync(name, cancellationToken));
6 years ago
}
public Task<TvDbResponse<Series>> GetSeriesByIdAsync(int tvdbId, string language,
CancellationToken cancellationToken)
6 years ago
{
var cacheKey = GenerateKey("series", tvdbId, language);
return TryGetValue(cacheKey, language, () => TvDbClient.Series.GetAsync(tvdbId, cancellationToken));
}
public Task<TvDbResponse<EpisodeRecord>> GetEpisodesAsync(int episodeTvdbId, string language,
CancellationToken cancellationToken)
{
var cacheKey = GenerateKey("episode", episodeTvdbId, language);
return TryGetValue(cacheKey, language, () => TvDbClient.Episodes.GetAsync(episodeTvdbId, cancellationToken));
}
5 years ago
public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByImdbIdAsync(
string imdbId,
string language,
CancellationToken cancellationToken)
{
var cacheKey = GenerateKey("series", imdbId, language);
return TryGetValue(cacheKey, language, () => TvDbClient.Search.SearchSeriesByImdbIdAsync(imdbId, cancellationToken));
}
5 years ago
public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByZap2ItIdAsync(
string zap2ItId,
string language,
CancellationToken cancellationToken)
{
var cacheKey = GenerateKey("series", zap2ItId, language);
5 years ago
return TryGetValue(cacheKey, language, () => TvDbClient.Search.SearchSeriesByZap2ItIdAsync(zap2ItId, cancellationToken));
}
5 years ago
public Task<TvDbResponse<Actor[]>> GetActorsAsync(
int tvdbId,
string language,
CancellationToken cancellationToken)
{
var cacheKey = GenerateKey("actors", tvdbId, language);
5 years ago
return TryGetValue(cacheKey, language, () => TvDbClient.Series.GetActorsAsync(tvdbId, cancellationToken));
}
5 years ago
public Task<TvDbResponse<Image[]>> GetImagesAsync(
int tvdbId,
ImagesQuery imageQuery,
string language,
CancellationToken cancellationToken)
{
var cacheKey = GenerateKey("images", tvdbId, language, imageQuery);
5 years ago
return TryGetValue(cacheKey, language, () => TvDbClient.Series.GetImagesAsync(tvdbId, imageQuery, cancellationToken));
}
public Task<TvDbResponse<Language[]>> GetLanguagesAsync(CancellationToken cancellationToken)
{
5 years ago
return TryGetValue("languages", null, () => TvDbClient.Languages.GetAllAsync(cancellationToken));
}
5 years ago
public Task<TvDbResponse<EpisodesSummary>> GetSeriesEpisodeSummaryAsync(
int tvdbId,
string language,
CancellationToken cancellationToken)
{
var cacheKey = GenerateKey("seriesepisodesummary", tvdbId, language);
return TryGetValue(cacheKey, language,
() => TvDbClient.Series.GetEpisodesSummaryAsync(tvdbId, cancellationToken));
}
5 years ago
public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(
int tvdbId,
int page,
EpisodeQuery episodeQuery,
string language,
CancellationToken cancellationToken)
{
var cacheKey = GenerateKey(language, tvdbId, episodeQuery);
return TryGetValue(cacheKey, language,
() => TvDbClient.Series.GetEpisodesAsync(tvdbId, page, episodeQuery, cancellationToken));
}
5 years ago
public Task<string> GetEpisodeTvdbId(
EpisodeInfo searchInfo,
string language,
CancellationToken cancellationToken)
{
searchInfo.SeriesProviderIds.TryGetValue(
nameof(MetadataProvider.Tvdb),
out var seriesTvdbId);
var episodeQuery = new EpisodeQuery();
// Prefer SxE over premiere date as it is more robust
if (searchInfo.IndexNumber.HasValue && searchInfo.ParentIndexNumber.HasValue)
{
switch (searchInfo.SeriesDisplayOrder)
{
case "dvd":
episodeQuery.DvdEpisode = searchInfo.IndexNumber.Value;
episodeQuery.DvdSeason = searchInfo.ParentIndexNumber.Value;
break;
case "absolute":
episodeQuery.AbsoluteNumber = searchInfo.IndexNumber.Value;
break;
default:
// aired order
episodeQuery.AiredEpisode = searchInfo.IndexNumber.Value;
episodeQuery.AiredSeason = searchInfo.ParentIndexNumber.Value;
break;
}
}
else if (searchInfo.PremiereDate.HasValue)
{
// tvdb expects yyyy-mm-dd format
4 years ago
episodeQuery.FirstAired = searchInfo.PremiereDate.Value.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
4 years ago
return GetEpisodeTvdbId(Convert.ToInt32(seriesTvdbId, CultureInfo.InvariantCulture), episodeQuery, language, cancellationToken);
}
5 years ago
public async Task<string> GetEpisodeTvdbId(
int seriesTvdbId,
EpisodeQuery episodeQuery,
6 years ago
string language,
CancellationToken cancellationToken)
{
var episodePage =
await GetEpisodesPageAsync(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken)
.ConfigureAwait(false);
4 years ago
return episodePage.Data.FirstOrDefault()?.Id.ToString(CultureInfo.InvariantCulture);
}
5 years ago
public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(
int tvdbId,
EpisodeQuery episodeQuery,
string language,
CancellationToken cancellationToken)
{
return GetEpisodesPageAsync(tvdbId, 1, episodeQuery, language, cancellationToken);
}
public async IAsyncEnumerable<KeyType> GetImageKeyTypesForSeriesAsync(int tvdbId, string language, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var cacheKey = GenerateKey(nameof(TvDbClient.Series.GetImagesSummaryAsync), tvdbId);
var imagesSummary = await TryGetValue(cacheKey, language, () => TvDbClient.Series.GetImagesSummaryAsync(tvdbId, cancellationToken)).ConfigureAwait(false);
if (imagesSummary.Data.Fanart > 0)
{
yield return KeyType.Fanart;
}
if (imagesSummary.Data.Series > 0)
{
yield return KeyType.Series;
}
if (imagesSummary.Data.Poster > 0)
{
yield return KeyType.Poster;
}
}
public async IAsyncEnumerable<KeyType> GetImageKeyTypesForSeasonAsync(int tvdbId, string language, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var cacheKey = GenerateKey(nameof(TvDbClient.Series.GetImagesSummaryAsync), tvdbId);
var imagesSummary = await TryGetValue(cacheKey, language, () => TvDbClient.Series.GetImagesSummaryAsync(tvdbId, cancellationToken)).ConfigureAwait(false);
if (imagesSummary.Data.Season > 0)
{
yield return KeyType.Season;
}
if (imagesSummary.Data.Fanart > 0)
{
yield return KeyType.Fanart;
}
// TODO seasonwide is not supported in TvDbSharper
}
private async Task<T> TryGetValue<T>(string key, string language, Func<Task<T>> resultFactory)
{
if (_cache.TryGetValue(key, out T cachedValue))
6 years ago
{
return cachedValue;
}
4 years ago
_tvDbClient.AcceptedLanguage = TvdbUtils.NormalizeLanguage(language) ?? DefaultLanguage;
var result = await resultFactory.Invoke().ConfigureAwait(false);
_cache.Set(key, result, TimeSpan.FromHours(1));
return result;
6 years ago
}
private static string GenerateKey(params object[] objects)
{
var key = string.Empty;
foreach (var obj in objects)
{
var objType = obj.GetType();
if (objType.IsPrimitive || objType == typeof(string))
{
key += obj + ";";
}
else
{
foreach (PropertyInfo propertyInfo in objType.GetProperties())
{
var currentValue = propertyInfo.GetValue(obj, null);
if (currentValue == null)
{
continue;
}
6 years ago
key += propertyInfo.Name + "=" + currentValue + ";";
}
}
}
return key;
}
}
}