feat(tmdb): show search results with dual auth
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>
This commit is contained in:
1 parent
2a1fcf0588
commit
e260677dab
10 files changed
+161
-42
No files matched your search
@@ -3,7 +3,8 @@ using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@@ -19,6 +20,11 @@ public sealed class TmdbClient
|
||||
/// </summary>
|
||||
public const string HttpClientName = "Tmdb";
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
@@ -42,7 +48,6 @@ public sealed class TmdbClient
|
||||
string mediaType,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var apiKey = RequireApiKey();
|
||||
var path = mediaType switch
|
||||
{
|
||||
"movie" => "search/movie",
|
||||
@@ -50,9 +55,9 @@ public sealed class TmdbClient
|
||||
_ => "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<TmdbSearchResponse>(url, cancellationToken).ConfigureAwait(false);
|
||||
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 [];
|
||||
@@ -78,13 +83,10 @@ public sealed class TmdbClient
|
||||
int tmdbId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var apiKey = RequireApiKey();
|
||||
var client = _httpClientFactory.CreateClient(HttpClientName);
|
||||
|
||||
if (mediaType.Equals("movie", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var movie = await client.GetFromJsonAsync<TmdbMovieDetailResponse>(
|
||||
$"movie/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
|
||||
var movie = await GetAsync<TmdbMovieDetailResponse>(
|
||||
$"movie/{tmdbId}?language=en-US",
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (movie is null)
|
||||
@@ -105,8 +107,8 @@ public sealed class TmdbClient
|
||||
|
||||
if (mediaType.Equals("tv", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var show = await client.GetFromJsonAsync<TmdbTvDetailResponse>(
|
||||
$"tv/{tmdbId}?api_key={Uri.EscapeDataString(apiKey)}",
|
||||
var show = await GetAsync<TmdbTvDetailResponse>(
|
||||
$"tv/{tmdbId}?language=en-US",
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (show is null)
|
||||
@@ -137,15 +139,76 @@ public sealed class TmdbClient
|
||||
throw new ArgumentException("mediaType must be movie or tv.", nameof(mediaType));
|
||||
}
|
||||
|
||||
private static string RequireApiKey()
|
||||
private async Task<T?> GetAsync<T>(string relativeUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
var apiKey = Plugin.Instance?.Configuration.TmdbApiKey?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(apiKey))
|
||||
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.");
|
||||
}
|
||||
|
||||
return apiKey;
|
||||
// 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)
|
||||
@@ -159,7 +222,9 @@ public sealed class TmdbClient
|
||||
return null;
|
||||
}
|
||||
|
||||
var title = type == "movie" ? result.Title : result.Name;
|
||||
var title = type == "movie"
|
||||
? result.Title ?? result.Name
|
||||
: result.Name ?? result.Title;
|
||||
if (string.IsNullOrWhiteSpace(title))
|
||||
{
|
||||
return null;
|
||||
@@ -187,4 +252,6 @@ public sealed class TmdbClient
|
||||
? year
|
||||
: null;
|
||||
}
|
||||
|
||||
private readonly record struct TmdbCredential(string Value, bool UseBearer);
|
||||
}
|
||||
Reference in new issue
Block a user