jellyfin/MediaBrowser.Providers/Plugins/TheTvdb/TvdbSeriesProvider.cs

444 lines
18 KiB
C#
Raw Normal View History

using System;
2013-09-15 12:33:23 -07:00
using System.Collections.Generic;
using System.Linq;
2013-02-20 18:33:05 -07:00
using System.Text;
using System.Text.RegularExpressions;
2013-02-20 18:33:05 -07:00
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
2016-10-27 00:58:33 -07:00
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Providers;
using Microsoft.Extensions.Logging;
2019-01-29 15:09:48 -07:00
using TvDbSharper;
using TvDbSharper.Dto;
using Series = MediaBrowser.Controller.Entities.TV.Series;
2013-02-20 18:33:05 -07:00
namespace MediaBrowser.Providers.Plugins.TheTvdb
2013-02-20 18:33:05 -07:00
{
2016-05-26 10:18:58 -07:00
public class TvdbSeriesProvider : IRemoteMetadataProvider<Series, SeriesInfo>, IHasOrder
2013-02-20 18:33:05 -07:00
{
internal static TvdbSeriesProvider Current { get; private set; }
2014-02-03 13:51:28 -07:00
private readonly IHttpClient _httpClient;
private readonly ILogger _logger;
2014-11-16 15:46:01 -07:00
private readonly ILibraryManager _libraryManager;
2016-10-27 00:58:33 -07:00
private readonly ILocalizationManager _localizationManager;
private readonly TvdbClientManager _tvdbClientManager;
public TvdbSeriesProvider(IHttpClient httpClient, ILogger<TvdbSeriesProvider> logger, ILibraryManager libraryManager, ILocalizationManager localizationManager, TvdbClientManager tvdbClientManager)
2013-02-24 17:13:45 -07:00
{
2014-02-03 13:51:28 -07:00
_httpClient = httpClient;
_logger = logger;
2014-11-16 15:46:01 -07:00
_libraryManager = libraryManager;
2016-10-27 00:58:33 -07:00
_localizationManager = localizationManager;
2013-03-03 22:43:06 -07:00
Current = this;
_tvdbClientManager = tvdbClientManager;
2013-03-03 22:43:06 -07:00
}
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
{
2015-10-20 22:09:50 -07:00
if (IsValidSeries(searchInfo.ProviderIds))
2014-03-02 08:42:21 -07:00
{
2015-10-20 22:09:50 -07:00
var metadata = await GetMetadata(searchInfo, cancellationToken).ConfigureAwait(false);
2014-08-18 18:42:53 -07:00
2015-10-20 22:09:50 -07:00
if (metadata.HasMetadata)
2014-08-18 18:42:53 -07:00
{
2015-10-20 22:09:50 -07:00
return new List<RemoteSearchResult>
{
new RemoteSearchResult
{
Name = metadata.Item.Name,
PremiereDate = metadata.Item.PremiereDate,
ProductionYear = metadata.Item.ProductionYear,
ProviderIds = metadata.Item.ProviderIds,
SearchProviderName = Name
}
};
}
2014-08-18 18:42:53 -07:00
}
2015-10-20 22:09:50 -07:00
return await FindSeries(searchInfo.Name, searchInfo.Year, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
}
2014-02-06 20:10:13 -07:00
public async Task<MetadataResult<Series>> GetMetadata(SeriesInfo itemId, CancellationToken cancellationToken)
2013-02-20 18:33:05 -07:00
{
2019-01-30 13:23:23 -07:00
var result = new MetadataResult<Series>
{
QueriedById = true
};
2015-10-20 22:09:50 -07:00
if (!IsValidSeries(itemId.ProviderIds))
2013-02-20 18:33:05 -07:00
{
result.QueriedById = false;
2015-09-19 14:25:19 -07:00
await Identify(itemId).ConfigureAwait(false);
}
2015-10-20 22:09:50 -07:00
cancellationToken.ThrowIfCancellationRequested();
2015-10-20 22:09:50 -07:00
if (IsValidSeries(itemId.ProviderIds))
{
2014-02-03 13:51:28 -07:00
result.Item = new Series();
result.HasMetadata = true;
2019-02-20 11:35:47 -07:00
await FetchSeriesData(result, itemId.MetadataLanguage, itemId.ProviderIds, cancellationToken)
.ConfigureAwait(false);
2013-02-20 18:33:05 -07:00
}
2014-02-03 13:51:28 -07:00
return result;
2013-02-20 18:33:05 -07:00
}
2019-01-30 13:23:23 -07:00
private async Task FetchSeriesData(MetadataResult<Series> result, string metadataLanguage, Dictionary<string, string> seriesProviderIds, CancellationToken cancellationToken)
2013-02-20 18:33:05 -07:00
{
2015-06-28 18:10:45 -07:00
var series = result.Item;
2020-06-06 12:17:49 -07:00
if (seriesProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out var tvdbId) && !string.IsNullOrEmpty(tvdbId))
2015-11-29 13:01:14 -07:00
{
2020-06-06 12:17:49 -07:00
series.SetProviderId(MetadataProvider.Tvdb, tvdbId);
2015-11-29 13:01:14 -07:00
}
2013-10-04 08:22:03 -07:00
2020-06-06 12:17:49 -07:00
if (seriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out var imdbId) && !string.IsNullOrEmpty(imdbId))
2015-11-29 13:01:14 -07:00
{
2020-06-06 12:17:49 -07:00
series.SetProviderId(MetadataProvider.Imdb, imdbId);
tvdbId = await GetSeriesByRemoteId(imdbId, MetadataProvider.Imdb.ToString(), metadataLanguage,
2019-02-20 11:35:47 -07:00
cancellationToken).ConfigureAwait(false);
2015-11-29 13:01:14 -07:00
}
2020-06-06 12:17:49 -07:00
if (seriesProviderIds.TryGetValue(MetadataProvider.Zap2It.ToString(), out var zap2It) && !string.IsNullOrEmpty(zap2It))
2018-09-12 10:26:21 -07:00
{
2020-06-06 12:17:49 -07:00
series.SetProviderId(MetadataProvider.Zap2It, zap2It);
tvdbId = await GetSeriesByRemoteId(zap2It, MetadataProvider.Zap2It.ToString(), metadataLanguage,
2019-02-20 11:35:47 -07:00
cancellationToken).ConfigureAwait(false);
2018-09-12 10:26:21 -07:00
}
try
{
var seriesResult =
await _tvdbClientManager
2019-02-20 11:35:47 -07:00
.GetSeriesByIdAsync(Convert.ToInt32(tvdbId), metadataLanguage, cancellationToken)
.ConfigureAwait(false);
2019-02-12 11:50:19 -07:00
MapSeriesToResult(result, seriesResult.Data, metadataLanguage);
}
catch (TvDbServerException e)
{
_logger.LogError(e, "Failed to retrieve series with id {TvdbId}", tvdbId);
return;
}
2013-09-16 10:52:14 -07:00
2014-02-03 13:51:28 -07:00
cancellationToken.ThrowIfCancellationRequested();
2013-10-15 18:44:23 -07:00
2015-07-23 19:48:10 -07:00
result.ResetPeople();
2015-10-20 22:09:50 -07:00
try
{
var actorsResult = await _tvdbClientManager
2019-02-20 11:35:47 -07:00
.GetActorsAsync(Convert.ToInt32(tvdbId), metadataLanguage, cancellationToken).ConfigureAwait(false);
MapActorsToResult(result, actorsResult.Data);
}
catch (TvDbServerException e)
{
_logger.LogError(e, "Failed to retrieve actors for series {TvdbId}", tvdbId);
}
}
2019-01-30 13:23:23 -07:00
private async Task<string> GetSeriesByRemoteId(string id, string idType, string language, CancellationToken cancellationToken)
2015-12-18 09:43:42 -07:00
{
TvDbResponse<SeriesSearchResult[]> result = null;
2019-01-29 15:09:48 -07:00
try
2018-09-12 10:26:21 -07:00
{
2020-06-06 12:17:49 -07:00
if (string.Equals(idType, MetadataProvider.Zap2It.ToString(), StringComparison.OrdinalIgnoreCase))
{
result = await _tvdbClientManager.GetSeriesByZap2ItIdAsync(id, language, cancellationToken)
2019-02-20 11:35:47 -07:00
.ConfigureAwait(false);
}
else
{
result = await _tvdbClientManager.GetSeriesByImdbIdAsync(id, language, cancellationToken)
2019-02-20 11:35:47 -07:00
.ConfigureAwait(false);
}
2018-09-12 10:26:21 -07:00
}
catch (TvDbServerException e)
2018-09-12 10:26:21 -07:00
{
_logger.LogError(e, "Failed to retrieve series with remote id {RemoteId}", id);
2016-10-27 00:58:33 -07:00
}
return result?.Data.First().Id.ToString();
2015-12-18 09:43:42 -07:00
}
2019-12-11 15:48:41 -07:00
/// <summary>
/// Check whether a dictionary of provider IDs includes an entry for a valid TV metadata provider.
/// </summary>
/// <param name="seriesProviderIds">The dictionary to check.</param>
/// <returns>True, if the dictionary contains a valid TV provider ID, otherwise false.</returns>
2015-10-20 22:09:50 -07:00
internal static bool IsValidSeries(Dictionary<string, string> seriesProviderIds)
2014-02-02 22:35:43 -07:00
{
2020-06-06 12:17:49 -07:00
return seriesProviderIds.ContainsKey(MetadataProvider.Tvdb.ToString()) ||
seriesProviderIds.ContainsKey(MetadataProvider.Imdb.ToString()) ||
seriesProviderIds.ContainsKey(MetadataProvider.Zap2It.ToString());
2015-10-20 22:09:50 -07:00
}
2014-02-03 13:51:28 -07:00
/// <summary>
/// Finds the series.
/// </summary>
/// <param name="name">The name.</param>
2015-10-20 22:09:50 -07:00
/// <param name="year">The year.</param>
2015-02-20 11:27:01 -07:00
/// <param name="language">The language.</param>
2014-02-03 13:51:28 -07:00
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.String}.</returns>
2015-10-20 22:09:50 -07:00
private async Task<IEnumerable<RemoteSearchResult>> FindSeries(string name, int? year, string language, CancellationToken cancellationToken)
2014-08-18 18:42:53 -07:00
{
2019-01-29 15:09:48 -07:00
var results = await FindSeriesInternal(name, language, cancellationToken).ConfigureAwait(false);
2014-08-18 18:42:53 -07:00
if (results.Count == 0)
{
2014-11-16 15:46:01 -07:00
var parsedName = _libraryManager.ParseName(name);
var nameWithoutYear = parsedName.Name;
2014-08-18 18:42:53 -07:00
2015-02-20 11:27:01 -07:00
if (!string.IsNullOrWhiteSpace(nameWithoutYear) && !string.Equals(nameWithoutYear, name, StringComparison.OrdinalIgnoreCase))
2014-08-18 18:42:53 -07:00
{
2019-01-29 15:09:48 -07:00
results = await FindSeriesInternal(nameWithoutYear, language, cancellationToken).ConfigureAwait(false);
2014-08-18 18:42:53 -07:00
}
}
2015-10-20 22:09:50 -07:00
return results.Where(i =>
{
if (year.HasValue && i.ProductionYear.HasValue)
{
// Allow one year tolerance
return Math.Abs(year.Value - i.ProductionYear.Value) <= 1;
}
return true;
});
2014-08-18 18:42:53 -07:00
}
private async Task<List<RemoteSearchResult>> FindSeriesInternal(string name, string language, CancellationToken cancellationToken)
2013-10-24 10:49:24 -07:00
{
var comparableName = GetComparableName(name);
2018-09-12 10:26:21 -07:00
var list = new List<Tuple<List<string>, RemoteSearchResult>>();
2019-02-07 13:59:57 -07:00
TvDbResponse<SeriesSearchResult[]> result;
try
{
result = await _tvdbClientManager.GetSeriesByNameAsync(comparableName, language, cancellationToken)
2019-02-20 11:35:47 -07:00
.ConfigureAwait(false);
}
catch (TvDbServerException e)
{
_logger.LogError(e, "No series results found for {Name}", comparableName);
return new List<RemoteSearchResult>();
}
2018-09-12 10:26:21 -07:00
2019-02-07 13:59:57 -07:00
foreach (var seriesSearchResult in result.Data)
2013-10-24 10:49:24 -07:00
{
2019-01-29 15:09:48 -07:00
var tvdbTitles = new List<string>
2017-10-20 09:16:56 -07:00
{
2019-01-29 15:09:48 -07:00
GetComparableName(seriesSearchResult.SeriesName)
};
tvdbTitles.AddRange(seriesSearchResult.Aliases.Select(GetComparableName));
2017-10-20 09:16:56 -07:00
2019-01-29 15:09:48 -07:00
DateTime.TryParse(seriesSearchResult.FirstAired, out var firstAired);
var remoteSearchResult = new RemoteSearchResult
{
Name = tvdbTitles.FirstOrDefault(),
ProductionYear = firstAired.Year,
SearchProviderName = Name,
ImageUrl = TvdbUtils.BannerUrl + seriesSearchResult.Banner
2013-10-10 09:55:07 -07:00
2019-01-29 15:09:48 -07:00
};
try
{
var seriesSesult =
await _tvdbClientManager.GetSeriesByIdAsync(seriesSearchResult.Id, language, cancellationToken)
2019-02-20 11:35:47 -07:00
.ConfigureAwait(false);
2020-06-06 12:17:49 -07:00
remoteSearchResult.SetProviderId(MetadataProvider.Imdb, seriesSesult.Data.ImdbId);
remoteSearchResult.SetProviderId(MetadataProvider.Zap2It, seriesSesult.Data.Zap2itId);
}
catch (TvDbServerException e)
{
_logger.LogError(e, "Unable to retrieve series with id {TvdbId}", seriesSearchResult.Id);
}
2020-06-06 12:17:49 -07:00
remoteSearchResult.SetProviderId(MetadataProvider.Tvdb, seriesSearchResult.Id.ToString());
2019-01-29 15:09:48 -07:00
list.Add(new Tuple<List<string>, RemoteSearchResult>(tvdbTitles, remoteSearchResult));
}
2014-02-03 13:51:28 -07:00
2018-09-12 10:26:21 -07:00
return list
.OrderBy(i => i.Item1.Contains(comparableName, StringComparer.OrdinalIgnoreCase) ? 0 : 1)
.ThenBy(i => list.IndexOf(i))
.Select(i => i.Item2)
.ToList();
}
2013-10-10 09:55:07 -07:00
/// <summary>
/// The remove.
2013-10-10 09:55:07 -07:00
/// </summary>
2014-02-03 13:51:28 -07:00
const string remove = "\"'!`?";
2014-02-03 13:51:28 -07:00
/// <summary>
/// The spacers.
2014-02-03 13:51:28 -07:00
/// </summary>
2019-02-11 11:07:53 -07:00
const string spacers = "/,.:;\\(){}[]+-_=*"; // (there are two types of dashes, short and long)
2014-02-03 13:51:28 -07:00
/// <summary>
/// Gets the name of the comparable.
/// </summary>
/// <param name="name">The name.</param>
2013-10-10 09:55:07 -07:00
/// <returns>System.String.</returns>
2016-10-27 00:58:33 -07:00
private string GetComparableName(string name)
2013-10-10 09:55:07 -07:00
{
2019-01-27 04:03:43 -07:00
name = name.ToLowerInvariant();
2019-08-16 08:31:47 -07:00
name = name.Normalize(NormalizationForm.FormKD);
2014-02-03 13:51:28 -07:00
var sb = new StringBuilder();
foreach (var c in name)
2013-10-10 09:55:07 -07:00
{
2019-02-11 11:07:53 -07:00
if (c >= 0x2B0 && c <= 0x0333)
2013-10-10 09:55:07 -07:00
{
2019-01-07 16:27:46 -07:00
// skip char modifier and diacritics
2014-02-03 13:51:28 -07:00
}
else if (remove.IndexOf(c) > -1)
{
// skip chars we are removing
}
else if (spacers.IndexOf(c) > -1)
{
sb.Append(" ");
}
else if (c == '&')
{
sb.Append(" and ");
}
else
{
sb.Append(c);
2013-10-10 09:55:07 -07:00
}
}
sb.Replace(", the", string.Empty).Replace("the ", " ").Replace(" the ", " ");
return Regex.Replace(sb.ToString().Trim(), @"\s+", " ");
}
2019-02-12 11:50:19 -07:00
private void MapSeriesToResult(MetadataResult<Series> result, TvDbSharper.Dto.Series tvdbSeries, string metadataLanguage)
{
2019-01-30 13:23:23 -07:00
Series series = result.Item;
2020-06-06 12:17:49 -07:00
series.SetProviderId(MetadataProvider.Tvdb, tvdbSeries.Id.ToString());
2019-01-30 13:23:23 -07:00
series.Name = tvdbSeries.SeriesName;
series.Overview = (tvdbSeries.Overview ?? string.Empty).Trim();
result.ResultLanguage = metadataLanguage;
2019-01-30 13:23:23 -07:00
series.AirDays = TVUtils.GetAirDays(tvdbSeries.AirsDayOfWeek);
series.AirTime = tvdbSeries.AirsTime;
series.CommunityRating = (float?)tvdbSeries.SiteRating;
2020-06-06 12:17:49 -07:00
series.SetProviderId(MetadataProvider.Imdb, tvdbSeries.ImdbId);
series.SetProviderId(MetadataProvider.Zap2It, tvdbSeries.Zap2itId);
2019-01-30 13:23:23 -07:00
if (Enum.TryParse(tvdbSeries.Status, true, out SeriesStatus seriesStatus))
2019-01-29 15:09:48 -07:00
{
series.Status = seriesStatus;
}
2019-01-30 13:23:23 -07:00
if (DateTime.TryParse(tvdbSeries.FirstAired, out var date))
{
// dates from tvdb are UTC but without offset or Z
2019-01-29 15:09:48 -07:00
series.PremiereDate = date;
series.ProductionYear = date.Year;
}
2016-10-27 00:58:33 -07:00
if (!string.IsNullOrEmpty(tvdbSeries.Runtime) && double.TryParse(tvdbSeries.Runtime, out double runtime))
{
series.RunTimeTicks = TimeSpan.FromMinutes(runtime).Ticks;
}
2019-01-30 13:23:23 -07:00
foreach (var genre in tvdbSeries.Genre)
2019-01-29 15:09:48 -07:00
{
2019-01-30 13:23:23 -07:00
series.AddGenre(genre);
}
if (!string.IsNullOrEmpty(tvdbSeries.Network))
2019-07-26 23:30:42 -07:00
{
series.AddStudio(tvdbSeries.Network);
}
2019-01-29 15:09:48 -07:00
if (result.Item.Status.HasValue && result.Item.Status.Value == SeriesStatus.Ended)
{
try
{
var episodeSummary = _tvdbClientManager
2019-02-12 11:50:19 -07:00
.GetSeriesEpisodeSummaryAsync(tvdbSeries.Id, metadataLanguage, CancellationToken.None).Result.Data;
var maxSeasonNumber = episodeSummary.AiredSeasons.Select(s => Convert.ToInt32(s)).Max();
var episodeQuery = new EpisodeQuery
{
AiredSeason = maxSeasonNumber
};
var episodesPage =
_tvdbClientManager.GetEpisodesPageAsync(tvdbSeries.Id, episodeQuery, metadataLanguage, CancellationToken.None).Result.Data;
result.Item.EndDate = episodesPage.Select(e =>
{
DateTime.TryParse(e.FirstAired, out var firstAired);
return firstAired;
}).Max();
}
catch (TvDbServerException e)
{
_logger.LogError(e, "Failed to find series end date for series {TvdbId}", tvdbSeries.Id);
}
}
2014-02-03 13:51:28 -07:00
}
2019-01-30 13:23:23 -07:00
private static void MapActorsToResult(MetadataResult<Series> result, IEnumerable<Actor> actors)
{
2019-01-30 13:23:23 -07:00
foreach (Actor actor in actors)
2014-02-03 13:51:28 -07:00
{
2019-01-30 13:23:23 -07:00
var personInfo = new PersonInfo
2018-09-12 10:26:21 -07:00
{
2019-01-30 13:23:23 -07:00
Type = PersonType.Actor,
Name = (actor.Name ?? string.Empty).Trim(),
Role = actor.Role,
ImageUrl = TvdbUtils.BannerUrl + actor.Image,
2019-01-30 13:23:23 -07:00
SortOrder = actor.SortOrder
};
2014-02-03 13:51:28 -07:00
2019-01-30 13:23:23 -07:00
if (!string.IsNullOrWhiteSpace(personInfo.Name))
2013-02-20 18:33:05 -07:00
{
2019-01-30 13:23:23 -07:00
result.AddPerson(personInfo);
2013-02-20 18:33:05 -07:00
}
2014-02-03 13:51:28 -07:00
}
}
public string Name => "TheTVDB";
2014-02-15 09:36:09 -07:00
2015-09-19 14:25:19 -07:00
public async Task Identify(SeriesInfo info)
{
2020-06-06 12:17:49 -07:00
if (!string.IsNullOrWhiteSpace(info.GetProviderId(MetadataProvider.Tvdb)))
2014-08-18 18:42:53 -07:00
{
2015-10-20 22:09:50 -07:00
return;
}
2014-08-18 18:42:53 -07:00
2019-02-20 11:35:47 -07:00
var srch = await FindSeries(info.Name, info.Year, info.MetadataLanguage, CancellationToken.None)
.ConfigureAwait(false);
2014-08-18 18:42:53 -07:00
2015-10-20 22:09:50 -07:00
var entry = srch.FirstOrDefault();
if (entry != null)
{
2020-06-06 12:17:49 -07:00
var id = entry.GetProviderId(MetadataProvider.Tvdb);
info.SetProviderId(MetadataProvider.Tvdb, id);
2014-08-18 18:42:53 -07:00
}
}
public int Order => 0;
public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
{
2014-03-02 08:42:21 -07:00
return _httpClient.GetResponse(new HttpRequestOptions
{
CancellationToken = cancellationToken,
Url = url,
2017-01-05 11:09:12 -07:00
BufferContent = false
2014-03-02 08:42:21 -07:00
});
}
2013-02-20 18:33:05 -07:00
}
2016-04-20 22:13:33 -07:00
}