Accept TMDB v3 API key or Read Access Token (Bearer), surface TMDB error messages, and display query/result count in the Request UI. Co-authored-by: Cursor <cursoragent@cursor.com>
258 lines
8.5 KiB
C#
258 lines
8.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Globalization;
|
|
using System.Linq;
|
|
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
using System.Text.Json;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Jellyfin.Plugin.Request.Tmdb;
|
|
|
|
/// <summary>
|
|
/// Server-side TMDB API client.
|
|
/// </summary>
|
|
public sealed class TmdbClient
|
|
{
|
|
/// <summary>
|
|
/// Named HTTP client for TMDB.
|
|
/// </summary>
|
|
public const string HttpClientName = "Tmdb";
|
|
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
|
|
private readonly IHttpClientFactory _httpClientFactory;
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="TmdbClient"/> class.
|
|
/// </summary>
|
|
/// <param name="httpClientFactory">HTTP client factory.</param>
|
|
public TmdbClient(IHttpClientFactory httpClientFactory)
|
|
{
|
|
_httpClientFactory = httpClientFactory;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Searches TMDB for movies or TV shows.
|
|
/// </summary>
|
|
/// <param name="query">Search query.</param>
|
|
/// <param name="mediaType">movie, tv, or multi.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Search results.</returns>
|
|
public async Task<IReadOnlyList<TmdbSearchItem>> SearchAsync(
|
|
string query,
|
|
string mediaType,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var path = mediaType switch
|
|
{
|
|
"movie" => "search/movie",
|
|
"tv" => "search/tv",
|
|
_ => "search/multi"
|
|
};
|
|
|
|
var relativeUrl =
|
|
$"{path}?query={Uri.EscapeDataString(query)}&include_adult=false&language=en-US&page=1";
|
|
var response = await GetAsync<TmdbSearchResponse>(relativeUrl, cancellationToken).ConfigureAwait(false);
|
|
if (response?.Results is null)
|
|
{
|
|
return [];
|
|
}
|
|
|
|
return response.Results
|
|
.Select(result => MapSearchResult(result, mediaType))
|
|
.Where(item => item is not null)
|
|
.Cast<TmdbSearchItem>()
|
|
.Take(40)
|
|
.ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Loads movie or TV details from TMDB.
|
|
/// </summary>
|
|
/// <param name="mediaType">movie or tv.</param>
|
|
/// <param name="tmdbId">TMDB identifier.</param>
|
|
/// <param name="cancellationToken">Cancellation token.</param>
|
|
/// <returns>Media detail, or null when not found.</returns>
|
|
public async Task<TmdbMediaDetail?> GetDetailsAsync(
|
|
string mediaType,
|
|
int tmdbId,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
if (mediaType.Equals("movie", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var movie = await GetAsync<TmdbMovieDetailResponse>(
|
|
$"movie/{tmdbId}?language=en-US",
|
|
cancellationToken)
|
|
.ConfigureAwait(false);
|
|
if (movie is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return new TmdbMediaDetail
|
|
{
|
|
TmdbId = movie.Id,
|
|
MediaType = "movie",
|
|
Title = movie.Title ?? string.Empty,
|
|
Overview = movie.Overview,
|
|
Year = ParseYear(movie.ReleaseDate),
|
|
PosterPath = movie.PosterPath
|
|
};
|
|
}
|
|
|
|
if (mediaType.Equals("tv", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var show = await GetAsync<TmdbTvDetailResponse>(
|
|
$"tv/{tmdbId}?language=en-US",
|
|
cancellationToken)
|
|
.ConfigureAwait(false);
|
|
if (show is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return new TmdbMediaDetail
|
|
{
|
|
TmdbId = show.Id,
|
|
MediaType = "tv",
|
|
Title = show.Name ?? string.Empty,
|
|
Overview = show.Overview,
|
|
Year = ParseYear(show.FirstAirDate),
|
|
PosterPath = show.PosterPath,
|
|
Seasons = show.Seasons
|
|
.Where(season => season.SeasonNumber > 0)
|
|
.Select(season => new TmdbSeasonInfo
|
|
{
|
|
SeasonNumber = season.SeasonNumber,
|
|
Name = season.Name ?? $"Season {season.SeasonNumber}",
|
|
EpisodeCount = season.EpisodeCount
|
|
})
|
|
.ToList()
|
|
};
|
|
}
|
|
|
|
throw new ArgumentException("mediaType must be movie or tv.", nameof(mediaType));
|
|
}
|
|
|
|
private async Task<T?> GetAsync<T>(string relativeUrl, CancellationToken cancellationToken)
|
|
{
|
|
var credential = RequireCredential();
|
|
var client = _httpClientFactory.CreateClient(HttpClientName);
|
|
var url = credential.UseBearer
|
|
? relativeUrl
|
|
: AppendQuery(relativeUrl, "api_key", credential.Value);
|
|
|
|
using var request = new HttpRequestMessage(HttpMethod.Get, url);
|
|
if (credential.UseBearer)
|
|
{
|
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", credential.Value);
|
|
}
|
|
|
|
using var response = await client.SendAsync(request, cancellationToken).ConfigureAwait(false);
|
|
var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
throw new HttpRequestException(FormatTmdbError(response.StatusCode, body));
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(body))
|
|
{
|
|
return default;
|
|
}
|
|
|
|
return JsonSerializer.Deserialize<T>(body, JsonOptions);
|
|
}
|
|
|
|
private static string FormatTmdbError(System.Net.HttpStatusCode statusCode, string body)
|
|
{
|
|
try
|
|
{
|
|
using var document = JsonDocument.Parse(body);
|
|
if (document.RootElement.TryGetProperty("status_message", out var message)
|
|
&& message.ValueKind == JsonValueKind.String
|
|
&& !string.IsNullOrWhiteSpace(message.GetString()))
|
|
{
|
|
return $"TMDB {(int)statusCode}: {message.GetString()}";
|
|
}
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
// Fall through to generic message.
|
|
}
|
|
|
|
return string.IsNullOrWhiteSpace(body)
|
|
? $"TMDB request failed with status {(int)statusCode}."
|
|
: $"TMDB {(int)statusCode}: {body}";
|
|
}
|
|
|
|
private static string AppendQuery(string relativeUrl, string key, string value)
|
|
{
|
|
var separator = relativeUrl.Contains('?', StringComparison.Ordinal) ? '&' : '?';
|
|
return $"{relativeUrl}{separator}{key}={Uri.EscapeDataString(value)}";
|
|
}
|
|
|
|
private static TmdbCredential RequireCredential()
|
|
{
|
|
var raw = Plugin.Instance?.Configuration.TmdbApiKey?.Trim() ?? string.Empty;
|
|
if (string.IsNullOrWhiteSpace(raw))
|
|
{
|
|
throw new InvalidOperationException("TMDB API key is not configured.");
|
|
}
|
|
|
|
// TMDB v3 accepts api_key query auth or the API Read Access Token as Bearer.
|
|
// https://developer.themoviedb.org/docs/authentication-application
|
|
var useBearer = raw.StartsWith("eyJ", StringComparison.Ordinal)
|
|
|| (raw.Contains('.', StringComparison.Ordinal) && raw.Length > 40);
|
|
return new TmdbCredential(raw, useBearer);
|
|
}
|
|
|
|
private static TmdbSearchItem? MapSearchResult(TmdbRawResult result, string requestedType)
|
|
{
|
|
var type = requestedType is "movie" or "tv"
|
|
? requestedType
|
|
: result.MediaType?.ToLowerInvariant();
|
|
|
|
if (type is not ("movie" or "tv"))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var title = type == "movie"
|
|
? result.Title ?? result.Name
|
|
: result.Name ?? result.Title;
|
|
if (string.IsNullOrWhiteSpace(title))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return new TmdbSearchItem
|
|
{
|
|
TmdbId = result.Id,
|
|
MediaType = type,
|
|
Title = title,
|
|
Overview = result.Overview,
|
|
Year = ParseYear(type == "movie" ? result.ReleaseDate : result.FirstAirDate),
|
|
PosterPath = result.PosterPath
|
|
};
|
|
}
|
|
|
|
private static int? ParseYear(string? date)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(date) || date.Length < 4)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return int.TryParse(date.AsSpan(0, 4), NumberStyles.None, CultureInfo.InvariantCulture, out var year)
|
|
? year
|
|
: null;
|
|
}
|
|
|
|
private readonly record struct TmdbCredential(string Value, bool UseBearer);
|
|
}
|