jellyfin/MediaBrowser.Providers/Plugins/Tmdb/People/TmdbPersonProvider.cs

275 lines
10 KiB
C#
Raw Normal View History

#pragma warning disable CS1591
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
2020-08-17 12:10:02 -07:00
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Extensions;
2020-08-31 10:05:21 -07:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Net;
using MediaBrowser.Model.Providers;
using MediaBrowser.Model.Serialization;
2020-05-30 23:23:09 -07:00
using MediaBrowser.Providers.Plugins.Tmdb.Models.General;
using MediaBrowser.Providers.Plugins.Tmdb.Models.People;
using MediaBrowser.Providers.Plugins.Tmdb.Models.Search;
using MediaBrowser.Providers.Plugins.Tmdb.Movies;
using Microsoft.Extensions.Logging;
2020-05-30 23:23:09 -07:00
namespace MediaBrowser.Providers.Plugins.Tmdb.People
{
public class TmdbPersonProvider : IRemoteMetadataProvider<Person, PersonLookupInfo>
{
const string DataFileName = "info.json";
2014-02-18 22:21:03 -07:00
2020-08-31 13:20:19 -07:00
private readonly CultureInfo _usCulture = new CultureInfo("en-US");
2014-02-18 22:21:03 -07:00
private readonly IJsonSerializer _jsonSerializer;
private readonly IFileSystem _fileSystem;
private readonly IServerConfigurationManager _configurationManager;
2020-08-17 12:10:02 -07:00
private readonly IHttpClientFactory _httpClientFactory;
2020-06-05 17:15:56 -07:00
private readonly ILogger<TmdbPersonProvider> _logger;
public TmdbPersonProvider(
IFileSystem fileSystem,
IServerConfigurationManager configurationManager,
IJsonSerializer jsonSerializer,
2020-08-17 12:10:02 -07:00
IHttpClientFactory httpClientFactory,
ILogger<TmdbPersonProvider> logger)
{
_fileSystem = fileSystem;
_configurationManager = configurationManager;
_jsonSerializer = jsonSerializer;
2020-08-17 12:10:02 -07:00
_httpClientFactory = httpClientFactory;
2016-01-22 19:32:14 -07:00
_logger = logger;
Current = this;
}
2020-08-31 13:20:19 -07:00
internal static TmdbPersonProvider Current { get; private set; }
public string Name => TmdbUtils.ProviderName;
2014-02-06 20:10:13 -07:00
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
2014-02-18 22:21:03 -07:00
{
2020-06-06 12:17:49 -07:00
var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb);
2014-02-18 22:21:03 -07:00
var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
2014-02-18 22:21:03 -07:00
2018-09-12 10:26:21 -07:00
var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
2014-02-18 22:21:03 -07:00
if (!string.IsNullOrEmpty(tmdbId))
{
await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
2019-08-18 05:44:13 -07:00
var images = (info.Images ?? new PersonImages()).Profiles ?? new List<Profile>();
2014-02-18 22:21:03 -07:00
var result = new RemoteSearchResult
2014-02-18 22:21:03 -07:00
{
2019-08-18 05:44:13 -07:00
Name = info.Name,
2014-02-18 22:21:03 -07:00
2014-03-01 15:34:27 -07:00
SearchProviderName = Name,
2015-12-22 09:38:08 -07:00
2019-08-18 05:44:13 -07:00
ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].File_Path)
2014-02-18 22:21:03 -07:00
};
2020-06-06 12:17:49 -07:00
result.SetProviderId(MetadataProvider.Tmdb, info.Id.ToString(_usCulture));
result.SetProviderId(MetadataProvider.Imdb, info.Imdb_Id);
2014-02-18 22:21:03 -07:00
return new[] { result };
}
2016-01-22 19:32:14 -07:00
if (searchInfo.IsAutomated)
{
2017-09-09 17:24:45 -07:00
// Don't hammer moviedb searching by name
return new List<RemoteSearchResult>();
2016-01-22 19:32:14 -07:00
}
2020-08-31 13:20:19 -07:00
var url = string.Format(
CultureInfo.InvariantCulture,
TmdbUtils.BaseTmdbApiUrl + @"3/search/person?api_key={1}&query={0}",
WebUtility.UrlEncode(searchInfo.Name),
TmdbUtils.ApiKey);
2014-02-18 22:21:03 -07:00
2020-08-17 12:10:02 -07:00
using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
2020-08-17 12:59:29 -07:00
foreach (var header in TmdbUtils.AcceptHeaders)
{
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
}
2020-09-07 04:31:05 -07:00
var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
2020-08-17 12:10:02 -07:00
await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
2014-02-18 22:21:03 -07:00
2020-08-17 12:10:02 -07:00
var result2 = await _jsonSerializer.DeserializeFromStreamAsync<TmdbSearchResult<PersonSearchResult>>(stream).ConfigureAwait(false)
?? new TmdbSearchResult<PersonSearchResult>();
2014-02-18 22:21:03 -07:00
2020-08-17 12:10:02 -07:00
return result2.Results.Select(i => GetSearchResult(i, tmdbImageUrl));
2014-02-18 22:21:03 -07:00
}
private RemoteSearchResult GetSearchResult(PersonSearchResult i, string baseImageUrl)
2014-02-18 22:21:03 -07:00
{
var result = new RemoteSearchResult
2014-02-18 22:21:03 -07:00
{
2014-03-01 15:34:27 -07:00
SearchProviderName = Name,
2015-12-22 09:38:08 -07:00
Name = i.Name,
2014-02-18 22:21:03 -07:00
ImageUrl = string.IsNullOrEmpty(i.Profile_Path) ? null : baseImageUrl + i.Profile_Path
2014-02-18 22:21:03 -07:00
};
2020-06-06 12:17:49 -07:00
result.SetProviderId(MetadataProvider.Tmdb, i.Id.ToString(_usCulture));
2014-02-18 22:21:03 -07:00
return result;
}
2014-02-06 20:10:13 -07:00
public async Task<MetadataResult<Person>> GetMetadata(PersonLookupInfo id, CancellationToken cancellationToken)
{
2020-06-06 12:17:49 -07:00
var tmdbId = id.GetProviderId(MetadataProvider.Tmdb);
// We don't already have an Id, need to fetch it
if (string.IsNullOrEmpty(tmdbId))
{
2014-02-18 22:21:03 -07:00
tmdbId = await GetTmdbId(id, cancellationToken).ConfigureAwait(false);
}
var result = new MetadataResult<Person>();
if (!string.IsNullOrEmpty(tmdbId))
{
2015-12-22 09:38:08 -07:00
try
{
await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
}
catch (HttpException ex)
{
if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
{
return result;
}
throw;
}
var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
var item = new Person();
result.HasMetadata = true;
2017-09-09 17:24:45 -07:00
// Take name from incoming info, don't rename the person
// TODO: This should go in PersonMetadataService, not each person provider
item.Name = id.Name;
2020-06-14 02:11:11 -07:00
// item.HomePageUrl = info.homepage;
2016-10-09 00:18:43 -07:00
2019-08-18 05:44:13 -07:00
if (!string.IsNullOrWhiteSpace(info.Place_Of_Birth))
2016-10-09 00:18:43 -07:00
{
2019-08-18 05:44:13 -07:00
item.ProductionLocations = new string[] { info.Place_Of_Birth };
2016-10-09 00:18:43 -07:00
}
2020-06-15 14:43:52 -07:00
2019-08-18 05:44:13 -07:00
item.Overview = info.Biography;
2019-08-18 05:44:13 -07:00
if (DateTime.TryParseExact(info.Birthday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out var date))
{
item.PremiereDate = date.ToUniversalTime();
}
2019-08-18 05:44:13 -07:00
if (DateTime.TryParseExact(info.Deathday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
{
item.EndDate = date.ToUniversalTime();
}
2020-06-06 12:17:49 -07:00
item.SetProviderId(MetadataProvider.Tmdb, info.Id.ToString(_usCulture));
2019-08-18 05:44:13 -07:00
if (!string.IsNullOrEmpty(info.Imdb_Id))
{
2020-06-06 12:17:49 -07:00
item.SetProviderId(MetadataProvider.Imdb, info.Imdb_Id);
}
2014-01-30 14:23:54 -07:00
result.HasMetadata = true;
result.Item = item;
}
return result;
}
/// <summary>
/// Gets the TMDB id.
/// </summary>
2014-02-18 22:21:03 -07:00
/// <param name="info">The information.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.String}.</returns>
2014-02-18 22:21:03 -07:00
private async Task<string> GetTmdbId(PersonLookupInfo info, CancellationToken cancellationToken)
{
2014-02-18 22:21:03 -07:00
var results = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);
2020-06-06 12:17:49 -07:00
return results.Select(i => i.GetProviderId(MetadataProvider.Tmdb)).FirstOrDefault();
}
internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
{
var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);
var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);
2018-09-12 10:26:21 -07:00
if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
{
return;
}
2020-08-31 13:20:19 -07:00
var url = string.Format(
CultureInfo.InvariantCulture,
TmdbUtils.BaseTmdbApiUrl + @"3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids",
TmdbUtils.ApiKey,
id);
2020-08-17 12:10:02 -07:00
using var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);
2020-08-17 12:59:29 -07:00
foreach (var header in TmdbUtils.AcceptHeaders)
{
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(header));
}
2020-09-07 04:31:05 -07:00
using var response = await TmdbMovieProvider.Current.GetMovieDbResponse(requestMessage, cancellationToken).ConfigureAwait(false);
2020-08-17 12:10:02 -07:00
Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
await using var fs = new FileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
await response.Content.CopyToAsync(fs).ConfigureAwait(false);
}
private static string GetPersonDataPath(IApplicationPaths appPaths, string tmdbId)
{
var letter = tmdbId.GetMD5().ToString().AsSpan().Slice(0, 1);
return Path.Join(GetPersonsDataPath(appPaths), letter, tmdbId);
}
internal static string GetPersonDataFilePath(IApplicationPaths appPaths, string tmdbId)
{
return Path.Combine(GetPersonDataPath(appPaths, tmdbId), DataFileName);
}
private static string GetPersonsDataPath(IApplicationPaths appPaths)
{
return Path.Combine(appPaths.CachePath, "tmdb-people");
}
2020-08-17 12:10:02 -07:00
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
2020-08-31 10:05:21 -07:00
return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
}
}
}