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
|
// 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');
|
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();
|
await fetchSchema();
|
||||||
|
|
|
||||||
|
|
@ -8,16 +8,24 @@ import { APIModel } from '../APIModel';
|
||||||
import type { paths } from '../schemas/OpenLibrary';
|
import type { paths } from '../schemas/OpenLibrary';
|
||||||
|
|
||||||
interface SearchResponse {
|
interface SearchResponse {
|
||||||
cover_i: number;
|
editions: {
|
||||||
has_fulltext: boolean;
|
docs: {
|
||||||
edition_count: number;
|
key?: string;
|
||||||
title: string;
|
title?: string;
|
||||||
author_name: string[];
|
cover_i?: number;
|
||||||
first_publish_year: number;
|
isbn?: string[];
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
cover_i?: number;
|
||||||
|
has_fulltext?: boolean;
|
||||||
|
edition_count?: number;
|
||||||
|
title?: string;
|
||||||
|
author_name?: string[];
|
||||||
|
first_publish_year?: number;
|
||||||
key: string;
|
key: string;
|
||||||
|
description?: string;
|
||||||
|
|
||||||
number_of_pages_median?: number;
|
number_of_pages_median?: number;
|
||||||
cover_edition_key?: string;
|
|
||||||
isbn?: string[];
|
isbn?: string[];
|
||||||
ratings_average?: number;
|
ratings_average?: number;
|
||||||
}
|
}
|
||||||
|
|
@ -85,8 +93,8 @@ export class OpenLibraryAPI extends APIModel {
|
||||||
const response = await client.GET('/search.json', {
|
const response = await client.GET('/search.json', {
|
||||||
params: {
|
params: {
|
||||||
query: {
|
query: {
|
||||||
q: `key:${id}`,
|
q: `${id}`,
|
||||||
fields: 'key,title,author_name,number_of_pages_median,first_publish_year,isbn,ratings_score,first_sentence,title_suggest,rating*,cover_edition_key',
|
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,
|
fetch: obsidianFetch,
|
||||||
|
|
@ -98,31 +106,45 @@ export class OpenLibraryAPI extends APIModel {
|
||||||
|
|
||||||
const data = response.data as {
|
const data = response.data as {
|
||||||
docs: SearchResponse[];
|
docs: SearchResponse[];
|
||||||
|
q?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO: maybe description.
|
|
||||||
|
|
||||||
// console.debug(data);
|
|
||||||
const result = data.docs[0];
|
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 pages = Number(result.number_of_pages_median);
|
||||||
const isbn = Number((result.isbn ?? []).find((el: string) => el.length <= 10));
|
const isbn = Number((isbnArr ?? []).find((el: string) => el.length <= 10));
|
||||||
const isbn13 = Number((result.isbn ?? []).find((el: string) => el.length == 13));
|
const isbn13 = Number((isbnArr ?? []).find((el: string) => el.length == 13));
|
||||||
|
|
||||||
return new BookModel({
|
return new BookModel({
|
||||||
title: result.title,
|
title: title,
|
||||||
year: result.first_publish_year?.toString() ?? 'unknown',
|
year: result.first_publish_year?.toString() ?? 'unknown',
|
||||||
dataSource: this.apiName,
|
dataSource: this.apiName,
|
||||||
url: `https://openlibrary.org` + result.key,
|
url: `https://openlibrary.org` + key,
|
||||||
id: result.key,
|
id: key,
|
||||||
isbn: Number.isNaN(isbn) ? undefined : isbn,
|
isbn: Number.isNaN(isbn) ? undefined : isbn,
|
||||||
isbn13: Number.isNaN(isbn13) ? undefined : isbn13,
|
isbn13: Number.isNaN(isbn13) ? undefined : isbn13,
|
||||||
englishTitle: result.title,
|
englishTitle: title,
|
||||||
|
|
||||||
author: result.author_name?.join(', '),
|
author: result.author_name?.join(', '),
|
||||||
|
plot: result.description ?? undefined,
|
||||||
pages: Number.isNaN(pages) ? undefined : pages,
|
pages: Number.isNaN(pages) ? undefined : pages,
|
||||||
onlineRating: result.ratings_average,
|
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,
|
released: true,
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,51 +1,10 @@
|
||||||
import { Notice, renderResults } from 'obsidian';
|
import createClient from 'openapi-fetch';
|
||||||
import type MediaDbPlugin from '../../main';
|
import type MediaDbPlugin from '../../main';
|
||||||
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
||||||
import { MovieModel } from '../../models/MovieModel';
|
import { MovieModel } from '../../models/MovieModel';
|
||||||
import { MediaType } from '../../utils/MediaType';
|
import { MediaType } from '../../utils/MediaType';
|
||||||
import { APIModel } from '../APIModel';
|
import { APIModel } from '../APIModel';
|
||||||
|
import type { paths } from '../schemas/TMDB';
|
||||||
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 }[];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export class TMDBMovieAPI extends APIModel {
|
export class TMDBMovieAPI extends APIModel {
|
||||||
plugin: MediaDbPlugin;
|
plugin: MediaDbPlugin;
|
||||||
|
|
@ -54,43 +13,64 @@ export class TMDBMovieAPI extends APIModel {
|
||||||
|
|
||||||
constructor(plugin: MediaDbPlugin) {
|
constructor(plugin: MediaDbPlugin) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.apiName = 'TMDBMovieAPI';
|
this.apiName = 'TMDBMovieAPI';
|
||||||
this.apiDescription = 'A community built Movie DB.';
|
this.apiDescription = 'A community built Movie DB.';
|
||||||
this.apiUrl = 'https://www.themoviedb.org/';
|
this.apiUrl = 'https://www.themoviedb.org/';
|
||||||
this.types = [MediaType.Movie];
|
this.types = [MediaType.Movie];
|
||||||
this.typeMappings = new Map();
|
this.typeMappings = new Map<string, string>();
|
||||||
this.typeMappings.set('movie', 'movie');
|
this.typeMappings.set('movie', 'movie');
|
||||||
}
|
}
|
||||||
|
|
||||||
async searchByTitle(title: string): Promise<MediaTypeModel[]> {
|
async searchByTitle(title: string): Promise<MediaTypeModel[]> {
|
||||||
console.log(`MDB | api "${this.apiName}" queried by Title`);
|
console.log(`MDB | api "${this.apiName}" queried by Title`);
|
||||||
|
|
||||||
if (!this.plugin.settings.TMDBKey) {
|
if (!this.plugin.settings.TMDBKey) {
|
||||||
throw new Error(`MDB | API key for ${this.apiName} missing.`);
|
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 client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||||
const searchResp = await fetch(searchUrl);
|
const response = await client.GET('/3/search/movie', {
|
||||||
if (searchResp.status === 401) {
|
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.`);
|
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||||
}
|
}
|
||||||
|
if (response.response.status !== 200) {
|
||||||
if (searchResp.status !== 200) {
|
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||||
throw Error(`MDB | Received status code ${searchResp.status} from ${this.apiName}.`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchData = (await searchResp.json()) as TMDBSearchMovieResponse;
|
const data = response.data;
|
||||||
if (!searchData.results || searchData.total_results === 0) {
|
|
||||||
|
if (!data) {
|
||||||
|
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.total_results === 0 || !data.results) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// console.debug(data.results);
|
||||||
|
|
||||||
const ret: MediaTypeModel[] = [];
|
const ret: MediaTypeModel[] = [];
|
||||||
for (const result of searchData.results) {
|
|
||||||
|
for (const result of data.results) {
|
||||||
ret.push(
|
ret.push(
|
||||||
new MovieModel({
|
new MovieModel({
|
||||||
type: 'movie',
|
type: 'movie',
|
||||||
title: result.original_title ?? '',
|
title: result.original_title,
|
||||||
englishTitle: result.title ?? '',
|
englishTitle: result.title,
|
||||||
year: result.release_date ? new Date(result.release_date).getFullYear().toString() : 'unknown',
|
year: result.release_date ? new Date(result.release_date).getFullYear().toString() : 'unknown',
|
||||||
dataSource: this.apiName,
|
dataSource: this.apiName,
|
||||||
id: result.id.toString(),
|
id: result.id.toString(),
|
||||||
|
|
@ -101,44 +81,69 @@ export class TMDBMovieAPI extends APIModel {
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getById(id: string): Promise<MovieModel> {
|
async getById(id: string): Promise<MediaTypeModel> {
|
||||||
console.log(`MDB | api "${this.apiName}" queried by ID`);
|
console.log(`MDB | api "${this.apiName}" queried by ID`);
|
||||||
|
|
||||||
if (!this.plugin.settings.TMDBKey) {
|
if (!this.plugin.settings.TMDBKey) {
|
||||||
throw Error(`MDB | API key for ${this.apiName} missing.`);
|
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 client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||||
const fetchData = await fetch(searchUrl);
|
const response = await client.GET('/3/movie/{movie_id}', {
|
||||||
if (fetchData.status === 401) {
|
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.`);
|
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||||
}
|
}
|
||||||
|
if (response.response.status !== 200) {
|
||||||
if (fetchData.status !== 200) {
|
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||||
throw Error(`MDB | Received status code ${fetchData.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({
|
return new MovieModel({
|
||||||
type: 'movie',
|
type: 'movie',
|
||||||
title: result.title ?? '',
|
title: result.title,
|
||||||
englishTitle: result.title ?? '',
|
englishTitle: result.title,
|
||||||
year: result.release_date ? new Date(result.release_date).getFullYear().toString() : 'unknown',
|
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,
|
dataSource: this.apiName,
|
||||||
url: `https://www.themoviedb.org/movie/${result.id}`,
|
url: `https://www.themoviedb.org/movie/${result.id}`,
|
||||||
id: result.id.toString(),
|
id: result.id.toString(),
|
||||||
|
|
||||||
plot: result.overview ?? '',
|
plot: result.overview ?? '',
|
||||||
genres: result.genres?.map((g: any) => g.name) ?? [],
|
genres: result.genres?.map((g: any) => g.name) ?? [],
|
||||||
writer: result.credits?.crew?.filter((c: any) => c.job === 'Screenplay').map((c: any) => c.name) ?? [],
|
// TMDB's spec allows for 'append_to_response' but doesn't seem to account for it in the type
|
||||||
director: result.credits?.crew?.filter((c: any) => c.job === 'Director').map((c: any) => c.name) ?? [],
|
// @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) ?? [],
|
studio: result.production_companies?.map((s: any) => s.name) ?? [],
|
||||||
|
|
||||||
duration: result.runtime?.toString() ?? 'unknown',
|
duration: result.runtime?.toString() ?? 'unknown',
|
||||||
onlineRating: result.vote_average ?? 0,
|
onlineRating: result.vote_average,
|
||||||
actors: result.credits?.cast?.map((c: any) => c.name).slice(0, 5) ?? [],
|
// @ts-ignore
|
||||||
image: result.poster_path ? `https://image.tmdb.org/t/p/w780${result.poster_path}` : '',
|
actors: result.credits.cast.map((c: any) => c.name).slice(0, 5) ?? [],
|
||||||
released: ['Released'].includes(result.status ?? ''),
|
image: `https://image.tmdb.org/t/p/w780${result.poster_path}`,
|
||||||
|
|
||||||
|
released: ['Released'].includes(result.status!),
|
||||||
streamingServices: [],
|
streamingServices: [],
|
||||||
|
|
||||||
userData: {
|
userData: {
|
||||||
watched: false,
|
watched: false,
|
||||||
lastWatched: '',
|
lastWatched: '',
|
||||||
|
|
@ -148,6 +153,6 @@ export class TMDBMovieAPI extends APIModel {
|
||||||
}
|
}
|
||||||
|
|
||||||
getDisabledMediaTypes(): MediaType[] {
|
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 MediaDbPlugin from '../../main';
|
||||||
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
||||||
import { MediaType } from '../../utils/MediaType';
|
import { MediaType } from '../../utils/MediaType';
|
||||||
import { APIModel } from '../APIModel';
|
import { APIModel } from '../APIModel';
|
||||||
import { SeasonModel } from '../../models/SeasonModel';
|
import { SeasonModel } from '../../models/SeasonModel';
|
||||||
|
import type { paths } from '../schemas/TMDB';
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class TMDBSeasonAPI extends APIModel {
|
export class TMDBSeasonAPI extends APIModel {
|
||||||
plugin: MediaDbPlugin;
|
plugin: MediaDbPlugin;
|
||||||
|
|
@ -68,6 +13,7 @@ export class TMDBSeasonAPI extends APIModel {
|
||||||
|
|
||||||
constructor(plugin: MediaDbPlugin) {
|
constructor(plugin: MediaDbPlugin) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.apiName = 'TMDBSeasonAPI';
|
this.apiName = 'TMDBSeasonAPI';
|
||||||
this.apiDescription = 'A community built Series DB (seasons).';
|
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.`);
|
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 client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||||
const searchResp = await fetch(searchUrl);
|
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.`);
|
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;
|
const searchData = searchResponse.data;
|
||||||
if (!searchData.results || searchData.total_results === 0) {
|
|
||||||
|
if (!searchData?.results || searchData.total_results === 0) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -107,22 +66,31 @@ export class TMDBSeasonAPI extends APIModel {
|
||||||
// Fetch series details to get the total number of seasons
|
// Fetch series details to get the total number of seasons
|
||||||
let totalSeasons = 0;
|
let totalSeasons = 0;
|
||||||
try {
|
try {
|
||||||
const detailsUrl = `https://api.themoviedb.org/3/tv/${encodeURIComponent(result.id)}?api_key=${this.plugin.settings.TMDBKey}`;
|
const detailsResponse = await client.GET('/3/tv/{series_id}', {
|
||||||
const detailsResp = await fetch(detailsUrl);
|
headers: {
|
||||||
if (detailsResp.status === 200) {
|
Authorization: `Bearer ${this.plugin.settings.TMDBKey}`,
|
||||||
const detailsData = (await detailsResp.json()) as TMDBSeriesDetails;
|
},
|
||||||
|
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)) {
|
if (Array.isArray(detailsData.seasons)) {
|
||||||
totalSeasons = detailsData.seasons.length;
|
totalSeasons = detailsData.seasons.length;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|
||||||
ret.push(
|
ret.push(
|
||||||
new SeasonModel({
|
new SeasonModel({
|
||||||
title: `${result.name ?? result.original_name ?? ''}`,
|
title: `${result.name ?? result.original_name ?? ''}`,
|
||||||
englishTitle: 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',
|
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
||||||
dataSource: this.apiName,
|
dataSource: this.apiName,
|
||||||
id: result.id.toString(),
|
id: result.id?.toString() ?? '',
|
||||||
seasonTitle: result.name ?? result.original_name ?? '',
|
seasonTitle: result.name ?? result.original_name ?? '',
|
||||||
seasonNumber: totalSeasons,
|
seasonNumber: totalSeasons,
|
||||||
}),
|
}),
|
||||||
|
|
@ -132,26 +100,41 @@ export class TMDBSeasonAPI extends APIModel {
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Fetch all seasons for a given series
|
// Fetch all seasons for a given series
|
||||||
async getSeasonsForSeries(tvId: string): Promise<SeasonModel[]> {
|
async getSeasonsForSeries(tvId: string): Promise<SeasonModel[]> {
|
||||||
if (!this.plugin.settings.TMDBKey) {
|
if (!this.plugin.settings.TMDBKey) {
|
||||||
throw new Error(`MDB | API key for ${this.apiName} missing.`);
|
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);
|
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||||
if (seriesResp.status === 401) {
|
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.`);
|
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 seriesName = seriesData?.name ?? '';
|
||||||
|
|
||||||
const ret: SeasonModel[] = [];
|
const ret: SeasonModel[] = [];
|
||||||
|
|
||||||
if (Array.isArray(seriesData?.seasons)) {
|
if (Array.isArray(seriesData?.seasons)) {
|
||||||
for (const season of seriesData.seasons) {
|
for (const season of seriesData.seasons) {
|
||||||
const seasonNumber = season.season_number ?? 0;
|
const seasonNumber = season.season_number ?? 0;
|
||||||
const titleText = `${seriesName} - Season ${seasonNumber}`;
|
const titleText = `${seriesName} - Season ${seasonNumber}`;
|
||||||
|
|
||||||
ret.push(
|
ret.push(
|
||||||
new SeasonModel({
|
new SeasonModel({
|
||||||
title: titleText,
|
title: titleText,
|
||||||
|
|
@ -165,6 +148,7 @@ export class TMDBSeasonAPI extends APIModel {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -178,38 +162,69 @@ export class TMDBSeasonAPI extends APIModel {
|
||||||
// Expect season ids like "12345/season/2"
|
// Expect season ids like "12345/season/2"
|
||||||
const m = /^(\d+)\/season\/(\d+)$/.exec(id);
|
const m = /^(\d+)\/season\/(\d+)$/.exec(id);
|
||||||
if (!m) {
|
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 tvId = m[1];
|
||||||
const seasonNumber = m[2];
|
const seasonNumber = m[2];
|
||||||
|
|
||||||
const seasonUrl = `https://api.themoviedb.org/3/tv/${encodeURIComponent(tvId)}/season/${encodeURIComponent(seasonNumber)}?api_key=${this.plugin.settings.TMDBKey}`;
|
const client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||||
const seasonResp = await fetch(seasonUrl);
|
|
||||||
|
|
||||||
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.`);
|
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
|
// 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 seriesResponse = await client.GET('/3/tv/{series_id}', {
|
||||||
const seriesResp = await fetch(seriesUrl);
|
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.`);
|
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 ?? '';
|
|
||||||
|
|
||||||
|
if (!seriesData) {
|
||||||
|
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const seriesName = seriesData?.name ?? '';
|
||||||
const airDate = seasonData.air_date ?? '';
|
const airDate = seasonData.air_date ?? '';
|
||||||
const titleText = `${seriesName} - Season ${seasonData.season_number}`;
|
const titleText = `${seriesName} - Season ${seasonData.season_number}`;
|
||||||
|
|
||||||
|
|
@ -229,16 +244,17 @@ export class TMDBSeasonAPI extends APIModel {
|
||||||
id: `${tvId}/season/${seasonData.season_number}`,
|
id: `${tvId}/season/${seasonData.season_number}`,
|
||||||
seasonTitle: seasonData.name ?? titleText,
|
seasonTitle: seasonData.name ?? titleText,
|
||||||
seasonNumber: seasonData.season_number ?? Number(seasonNumber),
|
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',
|
airedFrom: this.plugin.dateFormatter.format(airDate, this.apiDateFormat) ?? 'unknown',
|
||||||
airedTo: airedTo,
|
airedTo: airedTo,
|
||||||
plot: seasonData.overview ?? '',
|
plot: seasonData.overview ?? '',
|
||||||
image: seasonData.poster_path ? `https://image.tmdb.org/t/p/w780${seasonData.poster_path}` : '',
|
image: seasonData.poster_path ? `https://image.tmdb.org/t/p/w780${seasonData.poster_path}` : '',
|
||||||
genres: seriesData.genres?.map((g: any) => g.name) ?? [],
|
genres: seriesData.genres?.map(g => g.name ?? '').filter(name => name !== '') ?? [],
|
||||||
writer: seriesData.created_by?.map((c: any) => c.name) ?? [],
|
writer: seriesData.created_by?.map(c => c.name ?? '').filter(name => name !== '') ?? [],
|
||||||
studio: seriesData.production_companies?.map((s: any) => s.name) ?? [],
|
studio: seriesData.production_companies?.map(s => s.name ?? '').filter(name => name !== '') ?? [],
|
||||||
duration: seriesData.episode_run_time?.[0]?.toString() ?? '',
|
duration: seriesData.episode_run_time?.[0]?.toString() ?? '',
|
||||||
onlineRating: seasonData.vote_average ?? 0,
|
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) ?? [],
|
actors: seriesData.credits?.cast?.map((c: any) => c.name).slice(0, 5) ?? [],
|
||||||
released: ['Returning Series', 'Cancelled', 'Ended'].includes(seriesData.status ?? ''),
|
released: ['Returning Series', 'Cancelled', 'Ended'].includes(seriesData.status ?? ''),
|
||||||
streamingServices: [],
|
streamingServices: [],
|
||||||
|
|
@ -247,7 +263,6 @@ export class TMDBSeasonAPI extends APIModel {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Settings didn’t define TMDBSeasonAPIdisabledMediaTypes yet; return an empty list for now
|
|
||||||
getDisabledMediaTypes(): MediaType[] {
|
getDisabledMediaTypes(): MediaType[] {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,53 +1,10 @@
|
||||||
import { Notice, renderResults } from 'obsidian';
|
import createClient from 'openapi-fetch';
|
||||||
import type MediaDbPlugin from '../../main';
|
import type MediaDbPlugin from '../../main';
|
||||||
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
import type { MediaTypeModel } from '../../models/MediaTypeModel';
|
||||||
import { SeriesModel } from '../../models/SeriesModel';
|
import { SeriesModel } from '../../models/SeriesModel';
|
||||||
import { MediaType } from '../../utils/MediaType';
|
import { MediaType } from '../../utils/MediaType';
|
||||||
import { APIModel } from '../APIModel';
|
import { APIModel } from '../APIModel';
|
||||||
|
import type { paths } from '../schemas/TMDB';
|
||||||
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 }[];
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export class TMDBSeriesAPI extends APIModel {
|
export class TMDBSeriesAPI extends APIModel {
|
||||||
plugin: MediaDbPlugin;
|
plugin: MediaDbPlugin;
|
||||||
|
|
@ -56,43 +13,64 @@ export class TMDBSeriesAPI extends APIModel {
|
||||||
|
|
||||||
constructor(plugin: MediaDbPlugin) {
|
constructor(plugin: MediaDbPlugin) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
this.plugin = plugin;
|
this.plugin = plugin;
|
||||||
this.apiName = 'TMDBSeriesAPI';
|
this.apiName = 'TMDBSeriesAPI';
|
||||||
this.apiDescription = 'A community built Series DB.';
|
this.apiDescription = 'A community built Series DB.';
|
||||||
this.apiUrl = 'https://www.themoviedb.org/';
|
this.apiUrl = 'https://www.themoviedb.org/';
|
||||||
this.types = [MediaType.Series];
|
this.types = [MediaType.Series];
|
||||||
this.typeMappings = new Map();
|
this.typeMappings = new Map<string, string>();
|
||||||
this.typeMappings.set('tv', 'series');
|
this.typeMappings.set('tv', 'series');
|
||||||
}
|
}
|
||||||
|
|
||||||
async searchByTitle(title: string): Promise<MediaTypeModel[]> {
|
async searchByTitle(title: string): Promise<MediaTypeModel[]> {
|
||||||
console.log(`MDB | api "${this.apiName}" queried by Title`);
|
console.log(`MDB | api "${this.apiName}" queried by Title`);
|
||||||
|
|
||||||
if (!this.plugin.settings.TMDBKey) {
|
if (!this.plugin.settings.TMDBKey) {
|
||||||
throw new Error(`MDB | API key for ${this.apiName} missing.`);
|
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 client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||||
const searchResp = await fetch(searchUrl);
|
const response = await client.GET('/3/search/tv', {
|
||||||
if (searchResp.status === 401) {
|
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.`);
|
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||||
}
|
}
|
||||||
|
if (response.response.status !== 200) {
|
||||||
if (searchResp.status !== 200) {
|
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||||
throw Error(`MDB | Received status code ${searchResp.status} from ${this.apiName}.`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchData = (await searchResp.json()) as TMDBSearchTVResponse;
|
const data = response.data;
|
||||||
if (!searchData.results || searchData.total_results === 0) {
|
|
||||||
|
if (!data) {
|
||||||
|
throw Error(`MDB | No data received from ${this.apiName}.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.total_results === 0 || !data.results) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// console.debug(data.results);
|
||||||
|
|
||||||
const ret: MediaTypeModel[] = [];
|
const ret: MediaTypeModel[] = [];
|
||||||
for (const result of searchData.results) {
|
|
||||||
|
for (const result of data.results) {
|
||||||
ret.push(
|
ret.push(
|
||||||
new SeriesModel({
|
new SeriesModel({
|
||||||
type: 'series',
|
type: 'series',
|
||||||
title: result.original_name ?? '',
|
title: result.original_name,
|
||||||
englishTitle: result.name ?? '',
|
englishTitle: result.name,
|
||||||
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
||||||
dataSource: this.apiName,
|
dataSource: this.apiName,
|
||||||
id: result.id.toString(),
|
id: result.id.toString(),
|
||||||
|
|
@ -103,46 +81,68 @@ export class TMDBSeriesAPI extends APIModel {
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getById(id: string): Promise<SeriesModel> {
|
async getById(id: string): Promise<MediaTypeModel> {
|
||||||
console.log(`MDB | api "${this.apiName}" queried by ID`);
|
console.log(`MDB | api "${this.apiName}" queried by ID`);
|
||||||
|
|
||||||
if (!this.plugin.settings.TMDBKey) {
|
if (!this.plugin.settings.TMDBKey) {
|
||||||
throw Error(`MDB | API key for ${this.apiName} missing.`);
|
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 client = createClient<paths>({ baseUrl: 'https://api.themoviedb.org' });
|
||||||
const fetchData = await fetch(searchUrl);
|
const response = await client.GET('/3/tv/{series_id}', {
|
||||||
if (fetchData.status === 401) {
|
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.`);
|
throw Error(`MDB | Authentication for ${this.apiName} failed. Check the API key.`);
|
||||||
}
|
}
|
||||||
|
if (response.response.status !== 200) {
|
||||||
if (fetchData.status !== 200) {
|
throw Error(`MDB | Received status code ${response.response.status} from ${this.apiName}.`);
|
||||||
throw Error(`MDB | Received status code ${fetchData.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({
|
return new SeriesModel({
|
||||||
type: 'series',
|
type: 'series',
|
||||||
title: result.original_name ?? '',
|
title: result.original_name,
|
||||||
englishTitle: result.name ?? '',
|
englishTitle: result.name,
|
||||||
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
year: result.first_air_date ? new Date(result.first_air_date).getFullYear().toString() : 'unknown',
|
||||||
dataSource: this.apiName,
|
dataSource: this.apiName,
|
||||||
url: `https://www.themoviedb.org/tv/${result.id}`,
|
url: `https://www.themoviedb.org/tv/${result.id}`,
|
||||||
id: result.id.toString(),
|
id: result.id.toString(),
|
||||||
|
|
||||||
plot: result.overview ?? '',
|
plot: result.overview ?? '',
|
||||||
genres: result.genres?.map((g: any) => g.name) ?? [],
|
genres: result.genres?.map((g: any) => g.name) ?? [],
|
||||||
writer: result.created_by?.map((c: any) => c.name) ?? [],
|
writer: result.created_by?.map((c: any) => c.name) ?? [],
|
||||||
studio: result.production_companies?.map((s: any) => s.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',
|
duration: result.episode_run_time?.[0]?.toString() ?? 'unknown',
|
||||||
onlineRating: result.vote_average ?? 0,
|
onlineRating: result.vote_average,
|
||||||
actors: result.credits?.cast?.map((c: any) => c.name).slice(0, 5) ?? [],
|
// TMDB's spec allows for 'append_to_response' but doesn't seem to account for it in the type
|
||||||
image: result.poster_path ? `https://image.tmdb.org/t/p/w780${result.poster_path}` : '',
|
// @ts-ignore
|
||||||
released: ['Returning Series', 'Cancelled', 'Ended'].includes(result.status ?? ''),
|
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: [],
|
streamingServices: [],
|
||||||
airing: ['Returning Series'].includes(result.status ?? ''),
|
airing: ['Returning Series'].includes(result.status!),
|
||||||
airedFrom: this.plugin.dateFormatter.format(result.first_air_date ?? '', this.apiDateFormat) ?? 'unknown',
|
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'),
|
airedTo: ['Returning Series'].includes(result.status!) ? 'unknown' : (this.plugin.dateFormatter.format(result.last_air_date, this.apiDateFormat) ?? 'unknown'),
|
||||||
|
|
||||||
userData: {
|
userData: {
|
||||||
watched: false,
|
watched: false,
|
||||||
lastWatched: '',
|
lastWatched: '',
|
||||||
|
|
@ -152,6 +152,6 @@ export class TMDBSeriesAPI extends APIModel {
|
||||||
}
|
}
|
||||||
|
|
||||||
getDisabledMediaTypes(): MediaType[] {
|
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