generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 34
Add TMDB APIs for Movie & Series. Fixes #72 #197
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ZackBoe
wants to merge
2
commits into
mProjectsCode:master
Choose a base branch
from
ZackBoe:tmdb
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,258 @@ | ||
import { Notice, renderResults } from 'obsidian'; | ||
import type MediaDbPlugin from '../../main'; | ||
import type { MediaTypeModel } from '../../models/MediaTypeModel'; | ||
import { MovieModel } from '../../models/MovieModel'; | ||
import { SeriesModel } from '../../models/SeriesModel'; | ||
import { MediaType } from '../../utils/MediaType'; | ||
import { APIModel } from '../APIModel'; | ||
|
||
export class TMDBSeriesAPI extends APIModel { | ||
plugin: MediaDbPlugin; | ||
typeMappings: Map<string, string>; | ||
apiDateFormat: string = 'YYYY-MM-DD'; | ||
|
||
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<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 fetchData = await fetch(searchUrl); | ||
|
||
if (fetchData.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}.`); | ||
} | ||
|
||
const data = await fetchData.json(); | ||
|
||
if (data.total_results === 0) { | ||
if (data.Error === 'Series not found!') { | ||
return []; | ||
} | ||
|
||
throw Error(`MDB | Received error from ${this.apiName}: \n${JSON.stringify(data, undefined, 4)}`); | ||
} | ||
if (!data.results) { | ||
return []; | ||
} | ||
|
||
// console.debug(data.results); | ||
|
||
const ret: MediaTypeModel[] = []; | ||
|
||
for (const result of data.results) { | ||
ret.push( | ||
new SeriesModel({ | ||
type: 'series', | ||
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, | ||
}), | ||
); | ||
} | ||
|
||
return ret; | ||
} | ||
|
||
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) { | ||
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}.`); | ||
} | ||
|
||
const result = await fetchData.json(); | ||
// console.debug(result); | ||
|
||
return new SeriesModel({ | ||
type: 'series', | ||
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, | ||
|
||
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, | ||
duration: result.episode_run_time[0] ?? 'unknown', | ||
onlineRating: result.vote_average, | ||
actors: result.credits.cast.map((c: any) => c.name).slice(0, 5) ?? [], | ||
image: `https://image.tmdb.org/t/p/w780${result.poster_path}`, | ||
|
||
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', | ||
|
||
userData: { | ||
watched: false, | ||
lastWatched: '', | ||
personalRating: 0, | ||
}, | ||
}); | ||
|
||
} | ||
|
||
getDisabledMediaTypes(): MediaType[] { | ||
return this.plugin.settings.TMDBSeriesAPI_disabledMediaTypes as MediaType[]; | ||
} | ||
} | ||
|
||
export class TMDBMovieAPI extends APIModel { | ||
plugin: MediaDbPlugin; | ||
typeMappings: Map<string, string>; | ||
apiDateFormat: string = 'YYYY-MM-DD'; | ||
|
||
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<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 fetchData = await fetch(searchUrl); | ||
|
||
if (fetchData.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}.`); | ||
} | ||
|
||
const data = await fetchData.json(); | ||
|
||
if (data.total_results === 0) { | ||
if (data.Error === 'Movie not found!') { | ||
return []; | ||
} | ||
|
||
throw Error(`MDB | Received error from ${this.apiName}: \n${JSON.stringify(data, undefined, 4)}`); | ||
} | ||
if (!data.results) { | ||
return []; | ||
} | ||
|
||
// console.debug(data.results); | ||
|
||
const ret: MediaTypeModel[] = []; | ||
|
||
for (const result of data.results) { | ||
ret.push( | ||
new MovieModel({ | ||
type: 'movie', | ||
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, | ||
}), | ||
); | ||
} | ||
|
||
return ret; | ||
} | ||
|
||
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) { | ||
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}.`); | ||
} | ||
|
||
const result = await fetchData.json(); | ||
// console.debug(result); | ||
|
||
return new MovieModel({ | ||
type: 'movie', | ||
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', | ||
dataSource: this.apiName, | ||
url: `https://www.themoviedb.org/movie/${result.id}`, | ||
id: result.id, | ||
|
||
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) ?? [], | ||
studio: result.production_companies.map((s: any) => s.name) ?? [], | ||
|
||
duration: result.runtime ?? 'unknown', | ||
onlineRating: result.vote_average, | ||
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: '', | ||
personalRating: 0, | ||
}, | ||
}); | ||
|
||
} | ||
|
||
getDisabledMediaTypes(): MediaType[] { | ||
return this.plugin.settings.TMDBMovieAPI_disabledMediaTypes as MediaType[]; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.