using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
namespace Jellyfin.Plugin.Request.Tmdb;
///
/// Server-side TMDB API client.
///
public sealed class TmdbClient
{
///
/// Named HTTP client for TMDB.
///
public const string HttpClientName = "Tmdb";
private readonly IHttpClientFactory _httpClientFactory;
///
/// Initializes a new instance of the class.
///
/// HTTP client factory.
public TmdbClient(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
///
/// Searches TMDB for movies or TV shows.
///
/// Search query.
/// movie, tv, or multi.
/// Cancellation token.
/// Search results.
public async Task> SearchAsync(
string query,
string mediaType,
CancellationToken cancellationToken)
{
var apiKey = RequireApiKey();
var path = mediaType switch
{
"movie" => "search/movie",
"tv" => "search/tv",
_ => "search/multi"
};
var url = $"{path}?api_key={Uri.EscapeDataString(apiKey)}&query={Uri.EscapeDataString(query)}&include_adult=false";
var client = _httpClientFactory.CreateClient(HttpClientName);
var response = await client.GetFromJsonAsync(url, cancellationToken).ConfigureAwait(false);
if (response?.Results is null)
{
return [];
}
return response.Results
.Select(result => MapSearchResult(result, mediaType))
.Where(item => item is not null)
.Cast()
.Take(40)
.ToList();
}
///
/// Loads movie or TV details from TMDB.
///
/// movie or tv.
/// TMDB identifier.
/// Cancellation token.
/// Media detail, or null when not found.
public async Task GetDetailsAsync(
string mediaType,
int tmdbId,
CancellationToken cancellationToken)
{
var apiKey = RequireApiKey();
var client = _httpClientFactory.CreateClient(HttpClientName);
if (mediaType.Equals("movie", StringComparison.OrdinalIgnoreCase))
{
var movie = await client.GetFromJsonAsync(
$"movie/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
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 client.GetFromJsonAsync(
$"tv/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
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 static string RequireApiKey()
{
var apiKey = Plugin.Instance?.Configuration.TmdbApiKey?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new InvalidOperationException("TMDB API key is not configured.");
}
return apiKey;
}
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;
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;
}
}