generated from obsidianmd/obsidian-sample-plugin
-
Couldn't load subscription status.
- Fork 38
Add the VNDB API as a Game source for visual novels
#165
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
Senyksia
wants to merge
12
commits into
mProjectsCode:master
Choose a base branch
from
Senyksia:feat/vndb
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 7 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
5e5407f
Implement VNDB API integration
Senyksia 9960a1e
Add SFW support for VNDB
Senyksia 2c99314
Add VNDB documentation
Senyksia 57bb7c4
Relax SFW filtering for VNDB
Senyksia 98619fb
Merge branch 'master' into feat/vndb
Senyksia 86f003b
Merge branch 'master' into feat/vndb
Senyksia 0e51e1b
Fix unhandled null in VN release date
Senyksia b6b4955
Document and format VNDB query methods
Senyksia d746786
style(VNDB): Satisfy ESLint ordering and typing
Senyksia 03e5b9d
style(VNDB): Type JSON response fields as enums
Senyksia 37c1ac5
fix(VNDB): Remove `GameModel` type cast
Senyksia 3b21043
style(VNDB): Privatise query methods
Senyksia 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,218 @@ | ||
| import { APIModel } from '../APIModel'; | ||
| import { MediaTypeModel } from '../../models/MediaTypeModel'; | ||
| import MediaDbPlugin from '../../main'; | ||
| import { GameModel } from '../../models/GameModel'; | ||
| import { requestUrl } from 'obsidian'; | ||
| import { MediaType } from '../../utils/MediaType'; | ||
|
|
||
| /** | ||
| * A partial `POST /vn` response payload; desired fields should be listed in the request body. | ||
| */ | ||
| interface VNJSONResponse { | ||
| more: boolean; | ||
| results: [ | ||
| { | ||
| id: string; | ||
| title: string; | ||
| titles: [ | ||
| { | ||
| title: string; | ||
| lang: string; | ||
| }, | ||
| ]; | ||
| devstatus: 0 | 1 | 2; // Released | In-development | Cancelled | ||
| released: string | 'TBA' | null; | ||
| image: { | ||
| url: string; | ||
| sexual: number; | ||
| } | null; | ||
| rating: number | null; | ||
| tags: [ | ||
| { | ||
| id: string; | ||
| name: string; | ||
| category: 'cont' | 'ero' | 'tech'; | ||
| rating: number; | ||
| spoiler: 0 | 1 | 2; // None | Minor | Major | ||
| }, | ||
| ]; | ||
| developers: [ | ||
| { | ||
| id: string; | ||
| name: string; | ||
| }, | ||
| ]; | ||
| }, | ||
| ]; | ||
| } | ||
|
|
||
| /** | ||
| * A partial `POST /release` response payload; desired fields should be listed in the request body. | ||
| */ | ||
| interface ReleaseJSONResponse { | ||
| more: boolean; | ||
| results: [ | ||
| { | ||
| id: string; | ||
| producers: [ | ||
| { | ||
| id: string; | ||
| name: string; | ||
| developer: boolean; | ||
| publisher: boolean; | ||
| }, | ||
| ]; | ||
| }, | ||
| ]; | ||
| } | ||
|
|
||
| export class VNDBAPI extends APIModel { | ||
| plugin: MediaDbPlugin; | ||
| apiDateFormat: string = 'YYYY-MM-DD'; // Can also return YYYY-MM or YYYY | ||
|
|
||
| constructor(plugin: MediaDbPlugin) { | ||
| super(); | ||
|
|
||
| this.plugin = plugin; | ||
| this.apiName = 'VNDB API'; | ||
| this.apiDescription = 'A free API for visual novels.'; | ||
| this.apiUrl = 'https://api.vndb.org/kana'; | ||
| this.types = [MediaType.Game]; | ||
| } | ||
|
|
||
| postVNQuery = (body: string): Promise<VNJSONResponse> => this.postQuery('/vn', body); | ||
| postReleaseQuery = (body: string): Promise<ReleaseJSONResponse> => this.postQuery('/release', body); | ||
| async postQuery(endpoint: string, body: string): Promise<any> { | ||
| const fetchData = await requestUrl({ | ||
| url: `${this.apiUrl}${endpoint}`, | ||
| method: 'POST', | ||
| contentType: 'application/json', | ||
| body: body, | ||
| throw: false, | ||
| }); | ||
|
|
||
| if (fetchData.status !== 200) { | ||
| switch (fetchData.status) { | ||
| case 400: | ||
| throw Error(`MDB | Invalid request body or query [${fetchData.text}].`); | ||
| case 404: | ||
| throw Error(`MDB | Invalid API path or HTTP method.`); | ||
| case 429: | ||
| throw Error(`MDB | Throttled.`); | ||
| case 500: | ||
| throw Error(`MDB | VNDB server error.`); | ||
| case 502: | ||
| throw Error(`MDB | VNDB server is down.`); | ||
| default: | ||
| throw Error(`MDB | Received status code ${fetchData.status} from ${this.apiName}.`); | ||
| } | ||
| } | ||
|
|
||
| return fetchData.json; | ||
| } | ||
|
|
||
| async searchByTitle(title: string): Promise<MediaTypeModel[]> { | ||
| console.log(`MDB | api "${this.apiName}" queried by Title`); | ||
|
|
||
| /* SFW Filter: has ANY official&&complete&&standalone&&SFW release | ||
| OR has NO official&&standalone&&NSFW release | ||
| OR has the `In-game Sexual Content Toggle` (g2708) tag */ | ||
| // prettier-ignore | ||
| const vnData = await this.postVNQuery(`{ | ||
| "filters": ["and" ${!this.plugin.settings.sfwFilter ? `` : | ||
| `, ["or" | ||
| , ["release", "=", ["and" | ||
| , ["official", "=", "1"] | ||
| , ["rtype", "=", "complete"] | ||
| , ["patch", "!=", "1"] | ||
| , ["has_ero", "!=", "1"] | ||
| ]] | ||
| , ["release", "!=", ["and" | ||
| , ["official", "=", "1"] | ||
| , ["patch", "!=", "1"] | ||
| , ["has_ero", "=", "1"] | ||
| ]] | ||
| , ["tag", "=", "g2708"] | ||
| ]`} | ||
| , ["search", "=", "${title}"] | ||
| ], | ||
| "fields": "title, titles{title, lang}, released", | ||
| "sort": "searchrank", | ||
| "results": 20 | ||
| }`); | ||
|
|
||
| const ret: MediaTypeModel[] = []; | ||
| for (const vn of vnData.results) { | ||
| ret.push( | ||
| new GameModel({ | ||
| type: MediaType.Game, | ||
| title: vn.title, | ||
| englishTitle: vn.titles.find(t => t.lang === 'en')?.title ?? vn.title, | ||
| year: vn.released && vn.released !== 'TBA' ? new Date(vn.released).getFullYear().toString() : 'TBA', | ||
| dataSource: this.apiName, | ||
| id: vn.id, | ||
| } as GameModel), | ||
Senyksia marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| ); | ||
| } | ||
|
|
||
| return ret; | ||
| } | ||
|
|
||
| async getById(id: string): Promise<MediaTypeModel> { | ||
| console.log(`MDB | api "${this.apiName}" queried by ID`); | ||
|
|
||
| const vnData = await this.postVNQuery(`{ | ||
| "filters": ["id", "=", "${id}"], | ||
| "fields": "title, titles{title, lang}, devstatus, released, image{url, sexual}, rating, tags{name, category, rating, spoiler}, developers{name}" | ||
| }`); | ||
|
|
||
| if (vnData.results.length !== 1) throw Error(`MDB | Expected 1 result from query, got ${vnData.results.length}.`); | ||
| const vn = vnData.results[0]; | ||
| const releasedIsDate = vn.released !== null && vn.released !== 'TBA'; | ||
| vn.released ??= 'Unknown'; | ||
|
|
||
| const releaseData = await this.postReleaseQuery(`{ | ||
| "filters": ["and" | ||
| , ["vn", "=" | ||
| , ["id", "=", "${id}"] | ||
| ] | ||
| , ["official", "=", 1] | ||
| ], | ||
| "fields": "producers.name, producers.publisher, producers.developer", | ||
| "results": 100 | ||
| }`); | ||
|
|
||
| return new GameModel({ | ||
| type: MediaType.Game, | ||
| title: vn.title, | ||
| englishTitle: vn.titles.find(t => t.lang === 'en')?.title ?? vn.title, | ||
| year: releasedIsDate ? new Date(vn.released).getFullYear().toString() : vn.released, | ||
| dataSource: this.apiName, | ||
| url: `https://vndb.org/${vn.id}`, | ||
| id: vn.id, | ||
|
|
||
| developers: vn.developers.map(d => d.name), | ||
| publishers: releaseData.results | ||
| .flatMap(r => r.producers) | ||
| .filter(p => p.publisher) | ||
| .sort((p1, p2) => Number(p2.developer) - Number(p1.developer)) // Place developer-publishers first in publisher list | ||
| .map(p => p.name) | ||
| .unique(), | ||
| genres: vn.tags | ||
| .filter(t => t.category === 'cont' && t.spoiler === 0 && t.rating >= 2) | ||
| .sort((t1, t2) => t2.rating - t1.rating) | ||
| .map(t => t.name), | ||
| onlineRating: vn.rating ?? NaN, | ||
| // TODO: Ideally we should simply flag a sensitive image, then let the user handle it non-destructively | ||
| image: this.plugin.settings.sfwFilter && (vn.image?.sexual ?? 0) > 0.5 ? 'NSFW' : vn.image?.url, | ||
|
|
||
| released: vn.devstatus === 0, | ||
| releaseDate: releasedIsDate ? this.plugin.dateFormatter.format(vn.released, this.apiDateFormat) : vn.released, | ||
|
|
||
| userData: { | ||
| played: false, | ||
| personalRating: 0, | ||
| }, | ||
| } as GameModel); | ||
Senyksia marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
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.