search by id

This commit is contained in:
mProjectsCode 2022-05-11 23:41:55 +02:00
parent 62a4f2ec56
commit 92f3e6bab8
13 changed files with 183 additions and 29 deletions

View file

@ -42,6 +42,16 @@ export class APIManager {
}
}
getApiByName(name: string): APIModel {
for (const api of this.apis) {
if (api.apiName === name) {
return api;
}
}
return null;
}
registerAPI(api: APIModel): void {
this.apis.push(api);
}

View file

@ -1,30 +1,30 @@
import {MediaTypeModel} from '../models/MediaTypeModel';
export abstract class APIModel {
apiName: string;
apiUrl: string;
apiDescription: string;
types: string[];
apiName: string;
apiUrl: string;
apiDescription: string;
types: string[];
/**
* This function should query the api and return a list of matches. The matches should be caped at 20.
*
* @param title the title to query for
*/
abstract searchByTitle(title: string): Promise<MediaTypeModel[]>;
/**
* This function should query the api and return a list of matches. The matches should be caped at 20.
*
* @param title the title to query for
*/
abstract searchByTitle(title: string): Promise<MediaTypeModel[]>;
abstract getById(item: MediaTypeModel): Promise<MediaTypeModel>;
abstract getById(item: MediaTypeModel): Promise<MediaTypeModel>;
hasType(type: string): boolean {
return this.types.contains(type);
}
hasType(type: string): boolean {
return this.types.contains(type);
}
hasTypeOverlap(types: string[]): boolean {
for (const type of types) {
if (this.hasType(type)) {
return true;
}
}
return false;
}
hasTypeOverlap(types: string[]): boolean {
for (const type of types) {
if (this.hasType(type)) {
return true;
}
}
return false;
}
}

View file

@ -77,6 +77,7 @@ export class MALAPI extends APIModel {
title: result.title,
year: result.year ?? result.aired?.prop?.from?.year ?? '',
dataSource: this.apiName,
url: result.url,
id: result.mal_id,
genres: result.genres?.map((x: any) => x.name) ?? [],
@ -100,6 +101,7 @@ export class MALAPI extends APIModel {
title: result.title,
year: result.year ?? result.aired?.prop?.from?.year ?? '',
dataSource: this.apiName,
url: result.url,
id: result.mal_id,
genres: result.genres?.map((x: any) => x.name) ?? [],

View file

@ -32,6 +32,10 @@ export class OMDbAPI extends APIModel {
}
const data = await fetchData.json();
if (data.Response === 'False') {
throw Error(`Received error from ${this.apiName}: ${data.Error}`);
}
if (!data.Search) {
return [];
}
@ -76,14 +80,20 @@ export class OMDbAPI extends APIModel {
}
const result = await fetchData.json();
console.log(result);
if (result.Response === 'False') {
throw Error(`Received error from ${this.apiName}: ${result.Error}`);
}
if (result.Type === 'movie') {
const model = new MovieModel({
type: 'movie',
title: result.Title,
year: result.Year,
dataSource: this.apiName,
url: `https://www.imdb.com/title/${result.imdbID}/`,
id: result.imdbID,
genres: result.Genre?.split(', ') ?? [],
@ -107,6 +117,7 @@ export class OMDbAPI extends APIModel {
title: result.Title,
year: result.Year,
dataSource: this.apiName,
url: `https://www.imdb.com/title/${result.imdbID}/`,
id: result.imdbID,
genres: result.Genre?.split(', ') ?? [],

View file

@ -8,6 +8,7 @@ import {OMDbAPI} from './api/apis/OMDbAPI';
import {MediaDbAdvancedSearchModal} from './modals/MediaDbAdvancedSearchModal';
import {MediaDbSearchResultModal} from './modals/MediaDbSearchResultModal';
import {MALAPI} from './api/apis/MALAPI';
import {MediaDbIdSearchModal} from './modals/MediaDbIdSearchModal';
export default class MediaDbPlugin extends Plugin {
settings: MediaDbPluginSettings;
@ -18,7 +19,7 @@ export default class MediaDbPlugin extends Plugin {
// add icon to the left ribbon
const ribbonIconEl = this.addRibbonIcon('database', 'Add new Media DB entry', (evt: MouseEvent) =>
this.createMediaDbNote(),
this.createMediaDbNote(this.openMediaDbSearchModal.bind(this)),
);
ribbonIconEl.addClass('obsidian-media-db-plugin-ribbon-class');
@ -26,7 +27,13 @@ export default class MediaDbPlugin extends Plugin {
this.addCommand({
id: 'open-media-db-search-modal',
name: 'Add new Media DB entry',
callback: () => this.createMediaDbNote(),
callback: () => this.createMediaDbNote(this.openMediaDbSearchModal.bind(this)),
});
// register command to open id search modal
this.addCommand({
id: 'open-media-db-id-search-modal',
name: 'Add new Media DB entry by id',
callback: () => this.createMediaDbNote(this.openMediaDbIdSearchModal.bind(this)),
});
// register the settings tab
@ -40,9 +47,9 @@ export default class MediaDbPlugin extends Plugin {
this.apiManager.registerAPI(new MALAPI(this));
}
async createMediaDbNote(): Promise<void> {
async createMediaDbNote(modal: () => Promise<MediaTypeModel>): Promise<void> {
try {
let data: MediaTypeModel = await this.openMediaDbSearchModal();
let data: MediaTypeModel = await modal();
console.log('MDB | Creating new note...');
data = await this.apiManager.queryDetailedInfo(data);
@ -91,13 +98,22 @@ export default class MediaDbPlugin extends Plugin {
new MediaDbAdvancedSearchModal(this.app, this.apiManager, (err, results) => {
if (err) return reject(err);
new MediaDbSearchResultModal(this.app, results, (err2, res) => {
if (err) return reject(err2);
if (err2) return reject(err2);
resolve(res);
}).open();
}).open();
}));
}
async openMediaDbIdSearchModal(): Promise<MediaTypeModel> {
return new Promise(((resolve, reject) => {
new MediaDbIdSearchModal(this.app, this.apiManager, (err, res) => {
if (err) return reject(err);
resolve(res);
}).open();
}));
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}

View file

@ -0,0 +1,111 @@
import {App, ButtonComponent, DropdownComponent, Modal, Notice, Setting, TextComponent} from 'obsidian';
import {MediaTypeModel} from '../models/MediaTypeModel';
import {APIManager} from '../api/APIManager';
export class MediaDbIdSearchModal extends Modal {
query: string;
isBusy: boolean;
apiManager: APIManager;
searchBtn: ButtonComponent;
selectedApi: string;
onSubmit: (err: Error, result?: MediaTypeModel) => void;
constructor(app: App, apiManager: APIManager, onSubmit?: (err: Error, result?: MediaTypeModel) => void) {
super(app);
this.apiManager = apiManager;
this.onSubmit = onSubmit;
this.selectedApi = '';
}
submitCallback(event: KeyboardEvent) {
if (event.key === 'Enter') {
this.search();
}
}
async search(): Promise<MediaTypeModel> {
console.log(this.selectedApi);
if (!this.query) {
new Notice('MDB: no Id entered');
return;
}
if (!this.selectedApi) {
new Notice('MDB: No API selected');
return;
}
if (!this.isBusy) {
try {
this.isBusy = true;
this.searchBtn.setDisabled(false);
this.searchBtn.setButtonText('Searching...');
console.log('MDB | query started with id ' + this.query);
const api = this.apiManager.getApiByName(this.selectedApi);
if (!api) {
this.onSubmit(new Error('the selected api does not exist'));
}
const res = await api.getById({id: this.query} as MediaTypeModel); // TODO: fix jank
// console.log(res)
this.onSubmit(null, res);
} catch (e) {
this.onSubmit(e);
} finally {
this.close();
}
}
}
onOpen() {
const {contentEl} = this;
contentEl.createEl('h2', {text: 'Search media db by id'});
const placeholder = 'Search by id';
const searchComponent = new TextComponent(contentEl);
searchComponent.inputEl.style.width = '100%';
searchComponent.setPlaceholder(placeholder);
searchComponent.onChange(value => (this.query = value));
searchComponent.inputEl.addEventListener('keydown', this.submitCallback.bind(this));
contentEl.appendChild(searchComponent.inputEl);
searchComponent.inputEl.focus();
const apiSelectorWrapper = contentEl.createEl('div', {cls: 'media-db-plugin-list-wrapper'});
const apiSelectorTExtWrapper = apiSelectorWrapper.createEl('div', {cls: 'media-db-plugin-list-text-wrapper'});
apiSelectorTExtWrapper.createEl('span', {text: 'API to search', cls: 'media-db-plugin-list-text'});
const apiSelectorComponent = new DropdownComponent(apiSelectorWrapper);
apiSelectorComponent.onChange((value: string) => {
this.selectedApi = value;
});
for (const api of this.apiManager.apis) {
apiSelectorComponent.addOption(api.apiName, api.apiName);
}
apiSelectorWrapper.appendChild(apiSelectorComponent.selectEl);
new Setting(contentEl)
.addButton(btn => btn.setButtonText('Cancel').onClick(() => this.close()))
.addButton(btn => {
return (this.searchBtn = btn
.setButtonText('Ok')
.setCta()
.onClick(() => {
this.search();
}));
});
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}

View file

@ -3,6 +3,7 @@ export abstract class MediaTypeModel {
title: string;
year: string;
dataSource: string;
url: string;
id: string;
abstract toMetaData(): string;

View file

@ -7,6 +7,7 @@ export class MovieModel extends MediaTypeModel {
title: string;
year: string;
dataSource: string;
url: string;
id: string;
genres: string[];

View file

@ -7,6 +7,7 @@ export class SeriesModel extends MediaTypeModel {
title: string;
year: string;
dataSource: string;
url: string;
id: string;
genres: string[];

View file

@ -1,8 +1,8 @@
import {App, PluginSettingTab, Setting} from 'obsidian';
import MediaDbPlugin from '../main';
import {FolderSuggest} from './suggesters/FolderSuggester';
import {FileSuggest} from './suggesters/FileSuggester';
import {FolderSuggest} from './suggesters/FolderSuggest';
import {FileSuggest} from './suggesters/FileSuggest';
export interface MediaDbPluginSettings {

View file

@ -2,6 +2,7 @@
display: flex;
align-content: center;
margin-bottom: 5px;
margin-top: 5px;
}
.media-db-plugin-list-toggle {