Merged changes from Zackboe
* Using types from open api schema * Changed api key to api read access token
This commit is contained in:
parent
471c24d34e
commit
e8154bd381
6 changed files with 23141 additions and 264 deletions
|
|
@ -12,6 +12,9 @@ async function fetchSchema() {
|
|||
|
||||
// https://github.com/internetarchive/openlibrary-api/blob/main/swagger.yaml
|
||||
await $('bun openapi-typescript ./src/api/schemas/OpenLibrary.json -o ./src/api/schemas/OpenLibrary.ts');
|
||||
|
||||
// https://developer.themoviedb.org/openapi
|
||||
await $('bun openapi-typescript https://developer.themoviedb.org/openapi/tmdb-api.json -o ./src/api/schemas/TMDB.ts');
|
||||
}
|
||||
|
||||
await fetchSchema();
|
||||
|
|
|
|||
|
|
@ -8,16 +8,24 @@ import { APIModel } from '../APIModel';
|
|||
import type { paths } from '../schemas/OpenLibrary';
|
||||
|
||||
interface SearchResponse {
|
||||
cover_i: number;
|
||||
has_fulltext: boolean;
|
||||
edition_count: number;
|
||||
title: string;
|
||||
author_name: string[];
|
||||
first_publish_year: number;
|
||||
editions: {
|
||||
docs: {
|
||||
key?: string;
|
||||
title?: string;
|
||||
cover_i?: number;
|
||||
isbn?: string[];
|
||||
}[];
|
||||
};
|
||||
cover_i?: number;
|
||||
has_fulltext?: boolean;
|
||||
edition_count?: number;
|
||||
title?: string;
|
||||
author_name?: string[];
|
||||
first_publish_year?: number;
|
||||
key: string;
|
||||
description?: string;
|
||||
|
||||
number_of_pages_median?: number;
|
||||
cover_edition_key?: string;
|
||||
isbn?: string[];
|
||||
ratings_average?: number;
|
||||
}
|
||||
|
|
@ -85,8 +93,8 @@ export class OpenLibraryAPI extends APIModel {
|
|||
const response = await client.GET('/search.json', {
|
||||
params: {
|
||||
query: {
|
||||
q: `key:${id}`,
|
||||
fields: 'key,title,author_name,number_of_pages_median,first_publish_year,isbn,ratings_score,first_sentence,title_suggest,rating*,cover_edition_key',
|
||||
q: `${id}`,
|
||||
fields: 'key,title,author_name,number_of_pages_median,first_publish_year,isbn,ratings_score,first_sentence,title_suggest,rating*,cover*,editions,description',
|
||||
},
|
||||
},
|
||||
fetch: obsidianFetch,
|
||||
|
|
@ -98,31 +106,45 @@ export class OpenLibraryAPI extends APIModel {
|
|||
|
||||
const data = response.data as {
|
||||
docs: SearchResponse[];
|
||||
q?: string;
|
||||
};
|
||||
|
||||
// TODO: maybe description.
|
||||
|
||||
// console.debug(data);
|
||||
const result = data.docs[0];
|
||||
|
||||
let key = result.key;
|
||||
let title = result.title;
|
||||
let cover_i = result.cover_i;
|
||||
let isbnArr = result.isbn;
|
||||
|
||||
// Check if the query is for /isbn/ or /books/ and extract from editions.docs if present
|
||||
const q = data.q ?? '';
|
||||
if ((q.includes('/isbn/') || q.includes('/books/')) && result.editions && Array.isArray(result.editions.docs) && result.editions.docs.length > 0) {
|
||||
const edition = result.editions.docs[0];
|
||||
key = edition.key ?? key;
|
||||
title = edition.title ?? title;
|
||||
cover_i = edition.cover_i ?? cover_i;
|
||||
isbnArr = edition.isbn ?? isbnArr;
|
||||
}
|
||||
|
||||
const pages = Number(result.number_of_pages_median);
|
||||
const isbn = Number((result.isbn ?? []).find((el: string) => el.length <= 10));
|
||||
const isbn13 = Number((result.isbn ?? []).find((el: string) => el.length == 13));
|
||||
const isbn = Number((isbnArr ?? []).find((el: string) => el.length <= 10));
|
||||
const isbn13 = Number((isbnArr ?? []).find((el: string) => el.length == 13));
|
||||
|
||||
return new BookModel({
|
||||
title: result.title,
|
||||
title: title,
|
||||
year: result.first_publish_year?.toString() ?? 'unknown',
|
||||
dataSource: this.apiName,
|
||||
url: `https://openlibrary.org` + result.key,
|
||||
id: result.key,
|
||||
url: `https://openlibrary.org` + key,
|
||||
id: key,
|
||||
isbn: Number.isNaN(isbn) ? undefined : isbn,
|
||||
isbn13: Number.isNaN(isbn13) ? undefined : isbn13,
|
||||
englishTitle: result.title,
|
||||
englishTitle: title,
|
||||
|
||||
author: result.author_name?.join(', '),
|
||||
plot: result.description ?? undefined,
|
||||
pages: Number.isNaN(pages) ? undefined : pages,
|
||||
onlineRating: result.ratings_average,
|
||||
image: result.cover_edition_key ? `https://covers.openlibrary.org/b/OLID/` + result.cover_edition_key + `-L.jpg` : undefined,
|
||||
image: cover_i ? `https://covers.openlibrary.org/b/id/` + cover_i + `-L.jpg` : undefined,
|
||||
|
||||
released: true,
|
||||
|
||||
|
|
|
|||
|
|
@ -1,51 +1,10 @@
|
|||
import { Notice, renderResults } from 'obsidian';
|
||||
import createClient from 'openapi-fetch';
|
||||
import type MediaDbPlugin from '../../main';
|
||||
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
||||
import { MovieModel } from '../../models/MovieModel';
|
||||
import { MediaType } from '../../utils/MediaType';
|
||||
import { APIModel } from '../APIModel';
|
||||
|
||||
interface TMDBSearchMovieResult {
|
||||
id: number;
|
||||
original_language?: string;
|
||||
original_title?: string;
|
||||
overview?: string;
|
||||
popularity?: number;
|
||||
poster_path?: string;
|
||||
release_date?: string;
|
||||
title?: string;
|
||||
video?: boolean;
|
||||
vote_average?: number;
|
||||
vote_count?: number;
|
||||
adult?: boolean;
|
||||
backdrop_path?: string;
|
||||
genre_ids?: number[];
|
||||
}
|
||||
|
||||
interface TMDBSearchMovieResponse {
|
||||
page: number;
|
||||
results: TMDBSearchMovieResult[];
|
||||
total_results: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
interface TMDBMovieDetails {
|
||||
id: number;
|
||||
title?: string;
|
||||
original_title?: string;
|
||||
release_date?: string;
|
||||
overview?: string;
|
||||
genres?: { id: number; name: string }[];
|
||||
production_companies?: { id: number; name: string }[];
|
||||
runtime?: number;
|
||||
status?: string;
|
||||
vote_average?: number;
|
||||
poster_path?: string;
|
||||
credits?: {
|
||||
cast?: { name: string }[];
|
||||
crew?: { name: string; job: string }[];
|
||||
};
|
||||
}
|
||||
import type { paths } from '../schemas/TMDB';
|
||||
|
||||
export class TMDBMovieAPI extends APIModel {
|
||||
plugin: MediaDbPlugin;
|
||||
|
|
@ -54,43 +13,64 @@ export class TMDBMovieAPI extends APIModel {
|
|||
|
||||
constructor(plugin: MediaDbPlugin) {
|
||||
super();
|
||||
|
||||
this.plugin = plugin;
|
||||
this.apiName = 'TMDBMovieAPI';
|
||||
this.apiDescription = 'A community built Movie DB.';
|
||||
this.apiUrl = 'https://www.themoviedb.org/';
|
||||
this.types = [MediaType.Movie];
|
||||
this.typeMappings = new Map();
|
||||
this.typeMappings = new Map<string, string>();
|
||||
this.typeMappings.set('movie', 'movie');
|
||||
}
|
||||
|
||||
async searchByTitle(title: string): Promise<MediaTypeModel[]> {
|
||||
console.log(`MDB | api "${this.apiName}" queried by Title`);
|
||||
|
||||
if (!this.plugin.settings.TMDBKey) {
|
||||
throw new Error(`MDB | API key for ${this.apiName} missing.`);
|
||||
}
|
||||
|
||||
const searchUrl = `https://api.themoviedb.org/3/search/movie?api_key=${this.plugin.settings.TMDBKey}&query=${encodeURIComponent(title)}&include_adult=${this.plugin.settings.sfwFilter ? 'false' : 'true'}`;
|
||||
const searchResp = await fetch(searchUrl);
|
||||
if (searchResp.status === 401) {
|
||||
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||
const response = await client.GET('/3/search/movie', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
query: {
|
||||
query: encodeURIComponent(title),
|
||||
include_adult: this.plugin.settings.sfwFilter ? false : true,
|
||||
},
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (response.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
|
||||
if (searchResp.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${searchResp.status} from ${this.apiName}.`);
|
||||
if (response.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const searchData = (await searchResp.json()) as TMDBSearchMovieResponse;
|
||||
if (!searchData.results || searchData.total_results === 0) {
|
||||
const data = response.data;
|
||||
|
||||
if (!data) {
|
||||
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
if (data.total_results === 0 || !data.results) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// console.debug(data.results);
|
||||
|
||||
const ret: MediaTypeModel[] = [];
|
||||
for (const result of searchData.results) {
|
||||
|
||||
for (const result of data.results) {
|
||||
ret.push(
|
||||
new MovieModel({
|
||||
type: 'movie',
|
||||
title: result.original_title ?? '',
|
||||
englishTitle: result.title ?? '',
|
||||
title: result.original_title,
|
||||
englishTitle: result.title,
|
||||
year: result.release_date ? new Date(result.release_date).getFullYear().toString() : 'unknown',
|
||||
dataSource: this.apiName,
|
||||
id: result.id.toString(),
|
||||
|
|
@ -101,44 +81,69 @@ export class TMDBMovieAPI extends APIModel {
|
|||
return ret;
|
||||
}
|
||||
|
||||
async getById(id: string): Promise<MovieModel> {
|
||||
async getById(id: string): Promise<MediaTypeModel> {
|
||||
console.log(`MDB | api "${this.apiName}" queried by ID`);
|
||||
|
||||
if (!this.plugin.settings.TMDBKey) {
|
||||
throw Error(`MDB | API key for ${this.apiName} missing.`);
|
||||
}
|
||||
|
||||
const searchUrl = `https://api.themoviedb.org/3/movie/${encodeURIComponent(id)}?api_key=${this.plugin.settings.TMDBKey}&append_to_response=credits`;
|
||||
const fetchData = await fetch(searchUrl);
|
||||
if (fetchData.status === 401) {
|
||||
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||
const response = await client.GET('/3/movie/{movie_id}', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
path: { movie_id: parseInt(id) },
|
||||
query: {
|
||||
append_to_response: 'credits',
|
||||
},
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (response.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
|
||||
if (fetchData.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${fetchData.status} from ${this.apiName}.`);
|
||||
if (response.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const result = (await fetchData.json()) as TMDBMovieDetails;
|
||||
const result = response.data;
|
||||
|
||||
if (!result) {
|
||||
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||
}
|
||||
// console.debug(result);
|
||||
|
||||
return new MovieModel({
|
||||
type: 'movie',
|
||||
title: result.title ?? '',
|
||||
englishTitle: result.title ?? '',
|
||||
title: result.title,
|
||||
englishTitle: result.title,
|
||||
year: result.release_date ? new Date(result.release_date).getFullYear().toString() : 'unknown',
|
||||
premiere: this.plugin.dateFormatter.format(result.release_date ?? '', this.apiDateFormat) ?? 'unknown',
|
||||
premiere: this.plugin.dateFormatter.format(result.release_date, this.apiDateFormat) ?? 'unknown',
|
||||
dataSource: this.apiName,
|
||||
url: `https://www.themoviedb.org/movie/${result.id}`,
|
||||
id: result.id.toString(),
|
||||
|
||||
plot: result.overview ?? '',
|
||||
genres: result.genres?.map((g: any) => g.name) ?? [],
|
||||
writer: result.credits?.crew?.filter((c: any) => c.job === 'Screenplay').map((c: any) => c.name) ?? [],
|
||||
director: result.credits?.crew?.filter((c: any) => c.job === 'Director').map((c: any) => c.name) ?? [],
|
||||
// TMDB's spec allows for 'append_to_response' but doesn't seem to account for it in the type
|
||||
// @ts-ignore
|
||||
writer: result.credits.crew?.filter((c: any) => c.job === 'Screenplay').map((c: any) => c.name) ?? [],
|
||||
// @ts-ignore
|
||||
director: result.credits.crew?.filter((c: any) => c.job === 'Director').map((c: any) => c.name) ?? [],
|
||||
studio: result.production_companies?.map((s: any) => s.name) ?? [],
|
||||
|
||||
duration: result.runtime?.toString() ?? 'unknown',
|
||||
onlineRating: result.vote_average ?? 0,
|
||||
actors: result.credits?.cast?.map((c: any) => c.name).slice(0, 5) ?? [],
|
||||
image: result.poster_path ? `https://image.tmdb.org/t/p/w780${result.poster_path}` : '',
|
||||
released: ['Released'].includes(result.status ?? ''),
|
||||
onlineRating: result.vote_average,
|
||||
// @ts-ignore
|
||||
actors: result.credits.cast.map((c: any) => c.name).slice(0, 5) ?? [],
|
||||
image: `https://image.tmdb.org/t/p/w780${result.poster_path}`,
|
||||
|
||||
released: ['Released'].includes(result.status!),
|
||||
streamingServices: [],
|
||||
|
||||
userData: {
|
||||
watched: false,
|
||||
lastWatched: '',
|
||||
|
|
@ -148,6 +153,6 @@ export class TMDBMovieAPI extends APIModel {
|
|||
}
|
||||
|
||||
getDisabledMediaTypes(): MediaType[] {
|
||||
return this.plugin.settings.TMDBMovieAPI_disabledMediaTypes as MediaType[];
|
||||
return this.plugin.settings.TMDBMovieAPI_disabledMediaTypes;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,65 +1,10 @@
|
|||
import { Notice, renderResults } from 'obsidian';
|
||||
import createClient from 'openapi-fetch';
|
||||
import type MediaDbPlugin from '../../main';
|
||||
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
||||
import { MediaType } from '../../utils/MediaType';
|
||||
import { APIModel } from '../APIModel';
|
||||
import { SeasonModel } from '../../models/SeasonModel';
|
||||
|
||||
interface TMDBSearchTVResult {
|
||||
id: number;
|
||||
name?: string;
|
||||
original_name?: string;
|
||||
first_air_date?: string;
|
||||
}
|
||||
|
||||
interface TMDBSearchTVResponse {
|
||||
page: number;
|
||||
results: TMDBSearchTVResult[];
|
||||
total_results: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
interface TMDBSeason {
|
||||
season_number: number;
|
||||
name?: string;
|
||||
air_date?: string;
|
||||
episodes?: TMDBEpisode[];
|
||||
overview?: string;
|
||||
poster_path?: string;
|
||||
vote_average?: number;
|
||||
}
|
||||
|
||||
interface TMDBEpisode {
|
||||
air_date?: string;
|
||||
episode_number?: number;
|
||||
name?: string;
|
||||
overview?: string;
|
||||
}
|
||||
|
||||
interface TMDBSeriesDetails {
|
||||
id: number;
|
||||
name?: string;
|
||||
seasons?: TMDBSeason[];
|
||||
genres?: { id: number; name: string }[];
|
||||
created_by?: { id: number; name: string }[];
|
||||
production_companies?: { id: number; name: string }[];
|
||||
episode_run_time?: number[];
|
||||
status?: string;
|
||||
credits?: {
|
||||
cast?: { name: string }[];
|
||||
};
|
||||
}
|
||||
|
||||
interface TMDBSeasonDetails {
|
||||
id: number;
|
||||
season_number: number;
|
||||
name?: string;
|
||||
air_date?: string;
|
||||
episodes?: TMDBEpisode[];
|
||||
overview?: string;
|
||||
poster_path?: string;
|
||||
vote_average?: number;
|
||||
}
|
||||
import type { paths } from '../schemas/TMDB';
|
||||
|
||||
export class TMDBSeasonAPI extends APIModel {
|
||||
plugin: MediaDbPlugin;
|
||||
|
|
@ -68,6 +13,7 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
|
||||
constructor(plugin: MediaDbPlugin) {
|
||||
super();
|
||||
|
||||
this.plugin = plugin;
|
||||
this.apiName = 'TMDBSeasonAPI';
|
||||
this.apiDescription = 'A community built Series DB (seasons).';
|
||||
|
|
@ -84,18 +30,31 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
throw new Error(`MDB | API key for ${this.apiName} missing.`);
|
||||
}
|
||||
|
||||
const searchUrl = `https://api.themoviedb.org/3/search/tv?api_key=${this.plugin.settings.TMDBKey}&query=${encodeURIComponent(title)}&include_adult=${this.plugin.settings.sfwFilter ? 'false' : 'true'}`;
|
||||
const searchResp = await fetch(searchUrl);
|
||||
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||
const searchResponse = await client.GET('/3/search/tv', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
query: {
|
||||
query: encodeURIComponent(title),
|
||||
include_adult: this.plugin.settings.sfwFilter ? false : true,
|
||||
},
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (searchResp.status === 401) {
|
||||
if (searchResponse.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
if (searchResp.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${searchResp.status} from ${this.apiName}.`);
|
||||
|
||||
if (searchResponse.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${searchResponse.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const searchData = (await searchResp.json()) as TMDBSearchTVResponse;
|
||||
if (!searchData.results || searchData.total_results === 0) {
|
||||
const searchData = searchResponse.data;
|
||||
|
||||
if (!searchData?.results || searchData.total_results === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
|
@ -107,22 +66,31 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
// Fetch series details to get the total number of seasons
|
||||
let totalSeasons = 0;
|
||||
try {
|
||||
const detailsUrl = `https://api.themoviedb.org/3/tv/${encodeURIComponent(result.id)}?api_key=${this.plugin.settings.TMDBKey}`;
|
||||
const detailsResp = await fetch(detailsUrl);
|
||||
if (detailsResp.status === 200) {
|
||||
const detailsData = (await detailsResp.json()) as TMDBSeriesDetails;
|
||||
const detailsResponse = await client.GET('/3/tv/{series_id}', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
path: { series_id: result.id ?? 0 },
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (detailsResponse.response.status === 200 && detailsResponse.data) {
|
||||
const detailsData = detailsResponse.data;
|
||||
if (Array.isArray(detailsData.seasons)) {
|
||||
totalSeasons = detailsData.seasons.length;
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
|
||||
ret.push(
|
||||
new SeasonModel({
|
||||
title: `${result.name ?? result.original_name ?? ''}`,
|
||||
englishTitle: result.name ?? result.original_name ?? '',
|
||||
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
||||
dataSource: this.apiName,
|
||||
id: result.id.toString(),
|
||||
id: result.id?.toString() ?? '',
|
||||
seasonTitle: result.name ?? result.original_name ?? '',
|
||||
seasonNumber: totalSeasons,
|
||||
}),
|
||||
|
|
@ -132,26 +100,41 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
return ret;
|
||||
}
|
||||
|
||||
//Fetch all seasons for a given series
|
||||
// Fetch all seasons for a given series
|
||||
async getSeasonsForSeries(tvId: string): Promise<SeasonModel[]> {
|
||||
if (!this.plugin.settings.TMDBKey) {
|
||||
throw new Error(`MDB | API key for ${this.apiName} missing.`);
|
||||
}
|
||||
const seriesUrl = `https://api.themoviedb.org/3/tv/${encodeURIComponent(tvId)}?api_key=${this.plugin.settings.TMDBKey}`;
|
||||
const seriesResp = await fetch(seriesUrl);
|
||||
if (seriesResp.status === 401) {
|
||||
|
||||
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||
const seriesResponse = await client.GET('/3/tv/{series_id}', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
path: { series_id: parseInt(tvId) },
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (seriesResponse.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
if (seriesResp.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${seriesResp.status} from ${this.apiName}.`);
|
||||
|
||||
if (seriesResponse.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${seriesResponse.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
const seriesData = (await seriesResp.json()) as TMDBSeriesDetails;
|
||||
|
||||
const seriesData = seriesResponse.data;
|
||||
const seriesName = seriesData?.name ?? '';
|
||||
|
||||
const ret: SeasonModel[] = [];
|
||||
|
||||
if (Array.isArray(seriesData?.seasons)) {
|
||||
for (const season of seriesData.seasons) {
|
||||
const seasonNumber = season.season_number ?? 0;
|
||||
const titleText = `${seriesName} - Season ${seasonNumber}`;
|
||||
|
||||
ret.push(
|
||||
new SeasonModel({
|
||||
title: titleText,
|
||||
|
|
@ -165,6 +148,7 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
);
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
|
@ -178,38 +162,69 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
// Expect season ids like "12345/season/2"
|
||||
const m = /^(\d+)\/season\/(\d+)$/.exec(id);
|
||||
if (!m) {
|
||||
throw Error(`MDB | Invalid season id "${id}". Expected format "<tvId>/season/<seasonNumber>".`);
|
||||
throw Error(`MDB | Invalid season id "${id}". Expected format "<series_id>/season/<season_number>".`);
|
||||
}
|
||||
|
||||
const tvId = m[1];
|
||||
const seasonNumber = m[2];
|
||||
|
||||
const seasonUrl = `https://api.themoviedb.org/3/tv/${encodeURIComponent(tvId)}/season/${encodeURIComponent(seasonNumber)}?api_key=${this.plugin.settings.TMDBKey}`;
|
||||
const seasonResp = await fetch(seasonUrl);
|
||||
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||
|
||||
if (seasonResp.status === 401) {
|
||||
// Fetch season details
|
||||
const seasonResponse = await client.GET('/3/tv/{series_id}/season/{season_number}', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
path: {
|
||||
series_id: parseInt(tvId),
|
||||
season_number: parseInt(seasonNumber),
|
||||
},
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (seasonResponse.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
if (seasonResp.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${seasonResp.status} from ${this.apiName}.`);
|
||||
|
||||
if (seasonResponse.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${seasonResponse.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const seasonData = (await seasonResp.json()) as TMDBSeasonDetails;
|
||||
|
||||
const seasonData = seasonResponse.data;
|
||||
if (!seasonData) {
|
||||
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||
}
|
||||
// Fetch parent series to build consistent titles and inherit fields
|
||||
const seriesUrl = `https://api.themoviedb.org/3/tv/${encodeURIComponent(tvId)}?api_key=${this.plugin.settings.TMDBKey}&append_to_response=credits`;
|
||||
const seriesResp = await fetch(seriesUrl);
|
||||
const seriesResponse = await client.GET('/3/tv/{series_id}', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
path: { series_id: parseInt(tvId) },
|
||||
query: {
|
||||
append_to_response: 'credits',
|
||||
},
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (seriesResp.status === 401) {
|
||||
if (seriesResponse.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
if (seriesResp.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${seriesResp.status} from ${this.apiName}.`);
|
||||
|
||||
if (seriesResponse.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${seriesResponse.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const seriesData = (await seriesResp.json()) as TMDBSeriesDetails;
|
||||
const seriesName = seriesData?.name ?? '';
|
||||
const seriesData = seriesResponse.data;
|
||||
|
||||
if (!seriesData) {
|
||||
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const seriesName = seriesData?.name ?? '';
|
||||
const airDate = seasonData.air_date ?? '';
|
||||
const titleText = `${seriesName} - Season ${seasonData.season_number}`;
|
||||
|
||||
|
|
@ -229,16 +244,17 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
id: `${tvId}/season/${seasonData.season_number}`,
|
||||
seasonTitle: seasonData.name ?? titleText,
|
||||
seasonNumber: seasonData.season_number ?? Number(seasonNumber),
|
||||
episodes: Array.isArray(seasonData.episodes) ? seasonData.episodes.length : (seasonData.episodes ?? 0),
|
||||
episodes: Array.isArray(seasonData.episodes) ? seasonData.episodes.length : 0,
|
||||
airedFrom: this.plugin.dateFormatter.format(airDate, this.apiDateFormat) ?? 'unknown',
|
||||
airedTo: airedTo,
|
||||
plot: seasonData.overview ?? '',
|
||||
image: seasonData.poster_path ? `https://image.tmdb.org/t/p/w780${seasonData.poster_path}` : '',
|
||||
genres: seriesData.genres?.map((g: any) => g.name) ?? [],
|
||||
writer: seriesData.created_by?.map((c: any) => c.name) ?? [],
|
||||
studio: seriesData.production_companies?.map((s: any) => s.name) ?? [],
|
||||
genres: seriesData.genres?.map(g => g.name ?? '').filter(name => name !== '') ?? [],
|
||||
writer: seriesData.created_by?.map(c => c.name ?? '').filter(name => name !== '') ?? [],
|
||||
studio: seriesData.production_companies?.map(s => s.name ?? '').filter(name => name !== '') ?? [],
|
||||
duration: seriesData.episode_run_time?.[0]?.toString() ?? '',
|
||||
onlineRating: seasonData.vote_average ?? 0,
|
||||
// @ts-ignore - append_to_response credits not reflected in base schema
|
||||
actors: seriesData.credits?.cast?.map((c: any) => c.name).slice(0, 5) ?? [],
|
||||
released: ['Returning Series', 'Cancelled', 'Ended'].includes(seriesData.status ?? ''),
|
||||
streamingServices: [],
|
||||
|
|
@ -247,7 +263,6 @@ export class TMDBSeasonAPI extends APIModel {
|
|||
});
|
||||
}
|
||||
|
||||
// Settings didn’t define TMDBSeasonAPIdisabledMediaTypes yet; return an empty list for now
|
||||
getDisabledMediaTypes(): MediaType[] {
|
||||
return [];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,53 +1,10 @@
|
|||
import { Notice, renderResults } from 'obsidian';
|
||||
import createClient from 'openapi-fetch';
|
||||
import type MediaDbPlugin from '../../main';
|
||||
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
||||
import { SeriesModel } from '../../models/SeriesModel';
|
||||
import { MediaType } from '../../utils/MediaType';
|
||||
import { APIModel } from '../APIModel';
|
||||
|
||||
interface TMDBSearchTVResult {
|
||||
id: number;
|
||||
origin_country?: string[];
|
||||
original_language?: string;
|
||||
original_name?: string;
|
||||
overview?: string;
|
||||
popularity?: number;
|
||||
poster_path?: string;
|
||||
first_air_date?: string;
|
||||
name?: string;
|
||||
vote_average?: number;
|
||||
vote_count?: number;
|
||||
adult?: boolean;
|
||||
backdrop_path?: string;
|
||||
genre_ids?: number[];
|
||||
}
|
||||
|
||||
interface TMDBSearchTVResponse {
|
||||
page: number;
|
||||
results: TMDBSearchTVResult[];
|
||||
total_results: number;
|
||||
total_pages: number;
|
||||
}
|
||||
|
||||
interface TMDBSeriesDetails {
|
||||
id: number;
|
||||
name?: string;
|
||||
original_name?: string;
|
||||
first_air_date?: string;
|
||||
last_air_date?: string;
|
||||
overview?: string;
|
||||
genres?: { id: number; name: string }[];
|
||||
created_by?: { id: number; name: string }[];
|
||||
production_companies?: { id: number; name: string }[];
|
||||
episode_run_time?: number[];
|
||||
number_of_episodes?: number;
|
||||
status?: string;
|
||||
vote_average?: number;
|
||||
poster_path?: string;
|
||||
credits?: {
|
||||
cast?: { name: string }[];
|
||||
};
|
||||
}
|
||||
import type { paths } from '../schemas/TMDB';
|
||||
|
||||
export class TMDBSeriesAPI extends APIModel {
|
||||
plugin: MediaDbPlugin;
|
||||
|
|
@ -56,43 +13,64 @@ export class TMDBSeriesAPI extends APIModel {
|
|||
|
||||
constructor(plugin: MediaDbPlugin) {
|
||||
super();
|
||||
|
||||
this.plugin = plugin;
|
||||
this.apiName = 'TMDBSeriesAPI';
|
||||
this.apiDescription = 'A community built Series DB.';
|
||||
this.apiUrl = 'https://www.themoviedb.org/';
|
||||
this.types = [MediaType.Series];
|
||||
this.typeMappings = new Map();
|
||||
this.typeMappings = new Map<string, string>();
|
||||
this.typeMappings.set('tv', 'series');
|
||||
}
|
||||
|
||||
async searchByTitle(title: string): Promise<MediaTypeModel[]> {
|
||||
console.log(`MDB | api "${this.apiName}" queried by Title`);
|
||||
|
||||
if (!this.plugin.settings.TMDBKey) {
|
||||
throw new Error(`MDB | API key for ${this.apiName} missing.`);
|
||||
}
|
||||
|
||||
const searchUrl = `https://api.themoviedb.org/3/search/tv?api_key=${this.plugin.settings.TMDBKey}&query=${encodeURIComponent(title)}&include_adult=${this.plugin.settings.sfwFilter ? 'false' : 'true'}`;
|
||||
const searchResp = await fetch(searchUrl);
|
||||
if (searchResp.status === 401) {
|
||||
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||
const response = await client.GET('/3/search/tv', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
query: {
|
||||
query: encodeURIComponent(title),
|
||||
include_adult: this.plugin.settings.sfwFilter ? false : true,
|
||||
},
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (response.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
|
||||
if (searchResp.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${searchResp.status} from ${this.apiName}.`);
|
||||
if (response.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const searchData = (await searchResp.json()) as TMDBSearchTVResponse;
|
||||
if (!searchData.results || searchData.total_results === 0) {
|
||||
const data = response.data;
|
||||
|
||||
if (!data) {
|
||||
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
if (data.total_results === 0 || !data.results) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// console.debug(data.results);
|
||||
|
||||
const ret: MediaTypeModel[] = [];
|
||||
for (const result of searchData.results) {
|
||||
|
||||
for (const result of data.results) {
|
||||
ret.push(
|
||||
new SeriesModel({
|
||||
type: 'series',
|
||||
title: result.original_name ?? '',
|
||||
englishTitle: result.name ?? '',
|
||||
title: result.original_name,
|
||||
englishTitle: result.name,
|
||||
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
||||
dataSource: this.apiName,
|
||||
id: result.id.toString(),
|
||||
|
|
@ -103,46 +81,68 @@ export class TMDBSeriesAPI extends APIModel {
|
|||
return ret;
|
||||
}
|
||||
|
||||
async getById(id: string): Promise<SeriesModel> {
|
||||
async getById(id: string): Promise<MediaTypeModel> {
|
||||
console.log(`MDB | api "${this.apiName}" queried by ID`);
|
||||
|
||||
if (!this.plugin.settings.TMDBKey) {
|
||||
throw Error(`MDB | API key for ${this.apiName} missing.`);
|
||||
}
|
||||
|
||||
const searchUrl = `https://api.themoviedb.org/3/tv/${encodeURIComponent(id)}?api_key=${this.plugin.settings.TMDBKey}&append_to_response=credits`;
|
||||
const fetchData = await fetch(searchUrl);
|
||||
if (fetchData.status === 401) {
|
||||
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||
const response = await client.GET('/3/tv/{series_id}', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||
},
|
||||
params: {
|
||||
path: { series_id: parseInt(id) },
|
||||
query: {
|
||||
append_to_response: 'credits',
|
||||
},
|
||||
},
|
||||
fetch: fetch,
|
||||
});
|
||||
|
||||
if (response.response.status === 401) {
|
||||
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||
}
|
||||
|
||||
if (fetchData.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${fetchData.status} from ${this.apiName}.`);
|
||||
if (response.response.status !== 200) {
|
||||
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||
}
|
||||
|
||||
const result = (await fetchData.json()) as TMDBSeriesDetails;
|
||||
const result = response.data;
|
||||
|
||||
if (!result) {
|
||||
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||
}
|
||||
// console.debug(result);
|
||||
|
||||
return new SeriesModel({
|
||||
type: 'series',
|
||||
title: result.original_name ?? '',
|
||||
englishTitle: result.name ?? '',
|
||||
title: result.original_name,
|
||||
englishTitle: result.name,
|
||||
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
||||
dataSource: this.apiName,
|
||||
url: `https://www.themoviedb.org/tv/${result.id}`,
|
||||
id: result.id.toString(),
|
||||
|
||||
plot: result.overview ?? '',
|
||||
genres: result.genres?.map((g: any) => g.name) ?? [],
|
||||
writer: result.created_by?.map((c: any) => c.name) ?? [],
|
||||
studio: result.production_companies?.map((s: any) => s.name) ?? [],
|
||||
episodes: result.number_of_episodes ?? 0,
|
||||
episodes: result.number_of_episodes,
|
||||
duration: result.episode_run_time?.[0]?.toString() ?? 'unknown',
|
||||
onlineRating: result.vote_average ?? 0,
|
||||
actors: result.credits?.cast?.map((c: any) => c.name).slice(0, 5) ?? [],
|
||||
image: result.poster_path ? `https://image.tmdb.org/t/p/w780${result.poster_path}` : '',
|
||||
released: ['Returning Series', 'Cancelled', 'Ended'].includes(result.status ?? ''),
|
||||
onlineRating: result.vote_average,
|
||||
// TMDB's spec allows for 'append_to_response' but doesn't seem to account for it in the type
|
||||
// @ts-ignore
|
||||
actors: result.credits?.cast.map((c: any) => c.name).slice(0, 5) ?? [],
|
||||
image: result.poster_path ? `https://image.tmdb.org/t/p/w780${result.poster_path}` : null,
|
||||
|
||||
released: ['Returning Series', 'Cancelled', 'Ended'].includes(result.status!),
|
||||
streamingServices: [],
|
||||
airing: ['Returning Series'].includes(result.status ?? ''),
|
||||
airedFrom: this.plugin.dateFormatter.format(result.first_air_date ?? '', this.apiDateFormat) ?? 'unknown',
|
||||
airedTo: ['Returning Series'].includes(result.status ?? '') ? 'unknown' : (this.plugin.dateFormatter.format(result.last_air_date ?? '', this.apiDateFormat) ?? 'unknown'),
|
||||
airing: ['Returning Series'].includes(result.status!),
|
||||
airedFrom: this.plugin.dateFormatter.format(result.first_air_date, this.apiDateFormat) ?? 'unknown',
|
||||
airedTo: ['Returning Series'].includes(result.status!) ? 'unknown' : (this.plugin.dateFormatter.format(result.last_air_date, this.apiDateFormat) ?? 'unknown'),
|
||||
|
||||
userData: {
|
||||
watched: false,
|
||||
lastWatched: '',
|
||||
|
|
@ -152,6 +152,6 @@ export class TMDBSeriesAPI extends APIModel {
|
|||
}
|
||||
|
||||
getDisabledMediaTypes(): MediaType[] {
|
||||
return this.plugin.settings.TMDBSeriesAPI_disabledMediaTypes as MediaType[];
|
||||
return this.plugin.settings.TMDBSeriesAPI_disabledMediaTypes;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
22832
src/api/schemas/TMDB.ts
Normal file
22832
src/api/schemas/TMDB.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue