Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Phantom 2023-09-27 21:17:56 -05:00
commit 67825ae135
19 changed files with 1535 additions and 5272 deletions

View file

@ -107,6 +107,7 @@ Now you select the result you want and the plugin will cast it's magic and creat
- games
- music releases
- wiki articles
- books
### Currently supported APIs:
@ -117,6 +118,8 @@ Now you select the result you want and the plugin will cast it's magic and creat
| [MusicBrainz](https://musicbrainz.org/) | MusicBrainz is an API that offers information about music releases. | music releases | No | 50 per second | No |
| [Wikipedia](https://en.wikipedia.org/wiki/Main_Page) | The Wikipedia API allows access to all Wikipedia articles. | wiki articles | No | None | No |
| [Steam](https://store.steampowered.com/) | The Steam API offers information on all steam games. | games | No | 10000 per day | No |
| [Open Library](https://openlibrary.org) | The OpenLibrary API offers metadata for books | books | No | Cover access is rate-limited when not using CoverID or OLID by max 100 requests/IP every 5 minutes. This plugin uses OLID so there shouldn't be a rate limit. | No |
#### Notes
@ -146,6 +149,11 @@ Now you select the result you want and the plugin will cast it's magic and creat
- [Steam](https://store.steampowered.com/)
- you can find this ID in the URL
- e.g. for "Factorio" the URL looks like this `https://store.steampowered.com/app/427520/Factorio/` so the ID is `427520`
- [Open Library](https://openlibrary.org)
- The ID you need is the "work" ID and not the "book" ID, it needs to start with `/works/`. You can find this ID in the URL
- e.g. for "Fantastic Mr. Fox" the URL looks like this `https://openlibrary.org/works/OL45804W` so the ID is `/works/OL45804W`
- This URL is located near the top of the page above the title, see `An edition of Fantastic Mr Fox (1970) `
### Problems, unexpected behavior or improvement suggestions?

View file

@ -47,7 +47,7 @@ esbuild
],
format: 'cjs',
watch: !prod,
target: 'es2016',
target: 'es2018',
logLevel: 'info',
sourcemap: prod ? false : 'inline',
treeShaking: true,

6424
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -16,26 +16,23 @@
"devDependencies": {
"@popperjs/core": "^2.11.5",
"@tsconfig/svelte": "^3.0.0",
"@types/jest": "^28.1.3",
"@types/node": "^16.11.6",
"@typescript-eslint/eslint-plugin": "^5.2.0",
"@typescript-eslint/parser": "^5.2.0",
"builtin-modules": "^3.2.0",
"esbuild": "0.13.12",
"@types/jest": "^29.5.3",
"@types/node": "^18.16.20",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"builtin-modules": "^3.3.0",
"esbuild": "^0.14.47",
"esbuild-svelte": "^0.7.1",
"eslint-plugin-only-warn": "^1.0.3",
"jest": "^28.1.2",
"jest": "^29.6.1",
"jest-fetch-mock": "^3.0.3",
"obsidian": "latest",
"svelte": "^3.50.1",
"svelte": "^3.53.1",
"svelte-preprocess": "^4.10.7",
"ts-jest": "^28.0.5",
"tslib": "2.3.1",
"typescript": "4.4.4",
"ts-jest": "^29.1.1",
"tslib": "2.4.0",
"typescript": "^4.9.5",
"prettier": "2.7.1"
},
"dependencies": {
"ts-node": "^10.8.1",
"yarn": "^1.22.19"
}
"dependencies": {}
}

View file

@ -8,6 +8,7 @@ import { MediaType } from '../../utils/MediaType';
export class MALAPI extends APIModel {
plugin: MediaDbPlugin;
typeMappings: Map<string, string>;
apiDateFormat: string = 'YYYY-MM-DDTHH:mm:ssZ'; // ISO
constructor(plugin: MediaDbPlugin) {
super();
@ -115,7 +116,7 @@ export class MALAPI extends APIModel {
image: result.images?.jpg?.image_url ?? '',
released: true,
premiere: new Date(result.aired?.from).toLocaleDateString() ?? 'unknown',
premiere: this.plugin.dateFormatter.format(result.aired?.from, this.apiDateFormat) ?? 'unknown',
streamingServices: result.streaming?.map((x: any) => x.name) ?? [],
userData: {
@ -146,7 +147,7 @@ export class MALAPI extends APIModel {
image: result.images?.jpg?.image_url ?? '',
released: true,
premiere: new Date(result.aired?.from).toLocaleDateString() ?? 'unknown',
premiere: this.plugin.dateFormatter.format(result.aired?.from, this.apiDateFormat) ?? 'unknown',
streamingServices: result.streaming?.map((x: any) => x.name) ?? [],
userData: {
@ -176,8 +177,8 @@ export class MALAPI extends APIModel {
image: result.images?.jpg?.image_url ?? '',
released: true,
airedFrom: new Date(result.aired?.from).toLocaleDateString() ?? 'unknown',
airedTo: new Date(result.aired?.to).toLocaleDateString() ?? 'unknown',
airedFrom: this.plugin.dateFormatter.format(result.aired?.from, this.apiDateFormat) ?? 'unknown',
airedTo: this.plugin.dateFormatter.format(result.aired?.to, this.apiDateFormat) ?? 'unknown',
airing: result.airing,
userData: {

View file

@ -9,6 +9,7 @@ import { MediaType } from '../../utils/MediaType';
export class OMDbAPI extends APIModel {
plugin: MediaDbPlugin;
typeMappings: Map<string, string>;
apiDateFormat: string = 'DD MMM YYYY';
constructor(plugin: MediaDbPlugin) {
super();
@ -142,7 +143,7 @@ export class OMDbAPI extends APIModel {
released: true,
streamingServices: [],
premiere: new Date(result.Released).toLocaleDateString() ?? 'unknown',
premiere: this.plugin.dateFormatter.format(result.Released, this.apiDateFormat) ?? 'unknown',
userData: {
watched: false,
@ -173,7 +174,7 @@ export class OMDbAPI extends APIModel {
released: true,
streamingServices: [],
airing: false,
airedFrom: new Date(result.Released).toLocaleDateString() ?? 'unknown',
airedFrom: this.plugin.dateFormatter.format(result.Released, this.apiDateFormat) ?? 'unknown',
airedTo: 'unknown',
userData: {
@ -199,7 +200,7 @@ export class OMDbAPI extends APIModel {
image: result.Poster ?? '',
released: true,
releaseDate: new Date(result.Released).toLocaleDateString() ?? 'unknown',
releaseDate: this.plugin.dateFormatter.format(result.Released, this.apiDateFormat) ?? 'unknown',
userData: {
played: false,

View file

@ -0,0 +1,90 @@
import { APIModel } from '../APIModel';
import { MediaTypeModel } from '../../models/MediaTypeModel';
import MediaDbPlugin from '../../main';
import { BookModel } from 'src/models/BookModel';
import { MediaType } from '../../utils/MediaType';
export class OpenLibraryAPI extends APIModel {
plugin: MediaDbPlugin;
constructor(plugin: MediaDbPlugin) {
super();
this.plugin = plugin;
this.apiName = 'OpenLibraryAPI';
this.apiDescription = 'A free API for books';
this.apiUrl = 'https://openlibrary.org/';
this.types = [MediaType.Book];
}
async searchByTitle(title: string): Promise<MediaTypeModel[]> {
console.log(`MDB | api "${this.apiName}" queried by Title`);
const searchUrl = `https://openlibrary.org/search.json?title=${encodeURIComponent(title)}`;
const fetchData = await fetch(searchUrl);
console.debug(fetchData);
if (fetchData.status !== 200) {
throw Error(`MDB | Received status code ${fetchData.status} from an API.`);
}
const data = await fetchData.json();
console.debug(data);
const ret: MediaTypeModel[] = [];
for (const result of data.docs) {
ret.push(
new BookModel({
title: result.title,
englishTitle: result.title_english ?? result.title,
year: result.first_publish_year,
dataSource: this.apiName,
id: result.key,
} as BookModel)
);
}
return ret;
}
async getById(id: string): Promise<MediaTypeModel> {
console.log(`MDB | api "${this.apiName}" queried by ID`);
const searchUrl = `https://openlibrary.org/search.json?q=key:${encodeURIComponent(id)}`;
const fetchData = await fetch(searchUrl);
console.debug(fetchData);
if (fetchData.status !== 200) {
throw Error(`MDB | Received status code ${fetchData.status} from an API.`);
}
const data = await fetchData.json();
console.debug(data);
const result = data.docs[0];
const model = new BookModel({
title: result.title,
year: result.first_publish_year,
dataSource: this.apiName,
url: `https://openlibrary.org` + result.key,
id: result.key,
englishTitle: result.title_english ?? result.title,
author: result.author_name ?? 'unknown',
pages: result.number_of_pages_median ?? 'unknown',
onlineRating: Number.parseFloat(Number(result.ratings_average ?? 0).toFixed(2)),
image: `https://covers.openlibrary.org/b/OLID/` + result.cover_edition_key + `-L.jpg` ?? '',
released: true,
userData: {
read: false,
lastRead: '',
personalRating: 0,
},
} as BookModel);
return model;
}
}

View file

@ -8,6 +8,7 @@ import { MediaType } from '../../utils/MediaType';
export class SteamAPI extends APIModel {
plugin: MediaDbPlugin;
typeMappings: Map<string, string>;
apiDateFormat: string = 'DD MMM, YYYY';
constructor(plugin: MediaDbPlugin) {
super();
@ -109,7 +110,7 @@ export class SteamAPI extends APIModel {
image: result.header_image ?? '',
released: !result.release_date?.comming_soon,
releaseDate: new Date(result.release_date?.date).toLocaleDateString() ?? 'unknown',
releaseDate: this.plugin.dateFormatter.format(result.release_date?.date, this.apiDateFormat) ?? 'unknown',
userData: {
played: false,

View file

@ -6,6 +6,7 @@ import { MediaType } from '../../utils/MediaType';
export class WikipediaAPI extends APIModel {
plugin: MediaDbPlugin;
apiDateFormat: string = 'YYYY-MM-DDTHH:mm:ssZ'; // ISO
constructor(plugin: MediaDbPlugin) {
super();
@ -72,7 +73,7 @@ export class WikipediaAPI extends APIModel {
id: result.pageid,
wikiUrl: result.fullurl,
lastUpdated: new Date(result.touched).toLocaleDateString() ?? 'unknown',
lastUpdated: this.plugin.dateFormatter.format(result.touched, this.apiDateFormat),
length: result.length,
userData: {},

View file

@ -11,11 +11,13 @@ import { MusicBrainzAPI } from './api/apis/MusicBrainzAPI';
import { MEDIA_TYPES, MediaTypeManager } from './utils/MediaTypeManager';
import { SteamAPI } from './api/apis/SteamAPI';
import { BoardGameGeekAPI } from './api/apis/BoardGameGeekAPI';
import { OpenLibraryAPI } from './api/apis/OpenLibraryAPI';
import { PropertyMapper } from './settings/PropertyMapper';
import { YAMLConverter } from './utils/YAMLConverter';
import { MediaDbFolderImportModal } from './modals/MediaDbFolderImportModal';
import { PropertyMapping, PropertyMappingModel } from './settings/PropertyMapping';
import { ModalHelper, ModalResultCode, SearchModalOptions } from './utils/ModalHelper';
import { DateFormatter } from './utils/DateFormatter';
export default class MediaDbPlugin extends Plugin {
settings: MediaDbPluginSettings;
@ -23,6 +25,7 @@ export default class MediaDbPlugin extends Plugin {
mediaTypeManager: MediaTypeManager;
modelPropertyMapper: PropertyMapper;
modalHelper: ModalHelper;
dateFormatter: DateFormatter;
frontMatterRexExpPattern: string = '^(---)\\n[\\s\\S]*?\\n---';
@ -36,11 +39,13 @@ export default class MediaDbPlugin extends Plugin {
this.apiManager.registerAPI(new MusicBrainzAPI(this));
this.apiManager.registerAPI(new SteamAPI(this));
this.apiManager.registerAPI(new BoardGameGeekAPI(this));
this.apiManager.registerAPI(new OpenLibraryAPI(this));
// this.apiManager.registerAPI(new LocGovAPI(this)); // TODO: parse data
this.mediaTypeManager = new MediaTypeManager();
this.modelPropertyMapper = new PropertyMapper(this);
this.modalHelper = new ModalHelper(this);
this.dateFormatter = new DateFormatter();
await this.loadSettings();
// register the settings tab
@ -48,6 +53,7 @@ export default class MediaDbPlugin extends Plugin {
this.mediaTypeManager.updateTemplates(this.settings);
this.mediaTypeManager.updateFolders(this.settings);
this.dateFormatter.setFormat(this.settings.customDateFormat);
// add icon to the left ribbon
const ribbonIconEl = this.addRibbonIcon('database', 'Add new Media DB entry', () => this.createEntryWithAdvancedSearchModal());
@ -565,6 +571,7 @@ export default class MediaDbPlugin extends Plugin {
async saveSettings(): Promise<void> {
this.mediaTypeManager.updateTemplates(this.settings);
this.mediaTypeManager.updateFolders(this.settings);
this.dateFormatter.setFormat(this.settings.customDateFormat);
await this.saveData(this.settings);
}

View file

@ -1,4 +1,4 @@
import {ButtonComponent, Component, MarkdownRenderer, Modal, Setting} from 'obsidian';
import { ButtonComponent, Component, MarkdownRenderer, Modal, Setting } from 'obsidian';
import MediaDbPlugin from 'src/main';
import { MediaTypeModel } from 'src/models/MediaTypeModel';
import { PREVIEW_MODAL_DEFAULT_OPTIONS, PreviewModalData, PreviewModalOptions } from '../utils/ModalHelper';
@ -51,13 +51,13 @@ export class MediaDbPreviewModal extends Modal {
for (const result of this.elements) {
previewWrapper.createEl('h3', { text: result.englishTitle });
const fileDiv = previewWrapper.createDiv({ cls: 'media-db-plugin-preview'});
const fileDiv = previewWrapper.createDiv({ cls: 'media-db-plugin-preview' });
let fileContent = await this.plugin.generateMediaDbNoteContents(result, this.createNoteOptions);
fileContent = `\n${fileContent}\n`;
try {
await MarkdownRenderer.renderMarkdown(fileContent, fileDiv, "", this.markdownComponent);
await MarkdownRenderer.renderMarkdown(fileContent, fileDiv, '', this.markdownComponent);
} catch (e) {
console.warn(`mdb | error during rendering of preview`, e);
}

56
src/models/BookModel.ts Normal file
View file

@ -0,0 +1,56 @@
import { MediaTypeModel } from './MediaTypeModel';
import { mediaDbTag, migrateObject } from '../utils/Utils';
import { MediaType } from '../utils/MediaType';
export class BookModel extends MediaTypeModel {
author: string;
pages: number;
image: string;
onlineRating: number;
english_title: string;
released: boolean;
userData: {
read: boolean;
lastRead: string;
personalRating: number;
};
constructor(obj: any = {}) {
super();
this.author = undefined;
this.pages = undefined;
this.image = undefined;
this.onlineRating = undefined;
this.released = undefined;
this.userData = {
read: undefined,
lastRead: undefined,
personalRating: undefined,
};
migrateObject(this, obj, this);
if (!obj.hasOwnProperty('userData')) {
migrateObject(this.userData, obj, this.userData);
}
this.type = this.getMediaType();
}
getTags(): string[] {
return [mediaDbTag, 'book'];
}
getMediaType(): MediaType {
return MediaType.Book;
}
getSummary(): string {
return this.englishTitle + ' (' + this.year + ')';
}
}

View file

@ -7,12 +7,14 @@ import PropertyMappingModelsComponent from './PropertyMappingModelsComponent.sve
import { PropertyMapping, PropertyMappingModel, PropertyMappingOption } from './PropertyMapping';
import { MEDIA_TYPES } from '../utils/MediaTypeManager';
import { MediaTypeModel } from '../models/MediaTypeModel';
import { fragWithHTML } from '../utils/Utils';
export interface MediaDbPluginSettings {
OMDbKey: string;
sfwFilter: boolean;
useCustomYamlStringifier: boolean;
templates: boolean;
customDateFormat: string;
movieTemplate: string;
seriesTemplate: string;
@ -21,6 +23,7 @@ export interface MediaDbPluginSettings {
wikiTemplate: string;
musicReleaseTemplate: string;
boardgameTemplate: string;
bookTemplate: string;
movieFileNameTemplate: string;
seriesFileNameTemplate: string;
@ -29,6 +32,7 @@ export interface MediaDbPluginSettings {
wikiFileNameTemplate: string;
musicReleaseFileNameTemplate: string;
boardgameFileNameTemplate: string;
bookFileNameTemplate: string;
moviePropertyConversionRules: string;
seriesPropertyConversionRules: string;
@ -37,6 +41,7 @@ export interface MediaDbPluginSettings {
wikiPropertyConversionRules: string;
musicReleasePropertyConversionRules: string;
boardgamePropertyConversionRules: string;
bookPropertyConversionRules: string;
movieFolder: string;
seriesFolder: string;
@ -45,6 +50,7 @@ export interface MediaDbPluginSettings {
wikiFolder: string;
musicReleaseFolder: string;
boardgameFolder: string;
bookFolder: string;
propertyMappingModels: PropertyMappingModel[];
}
@ -54,6 +60,7 @@ const DEFAULT_SETTINGS: MediaDbPluginSettings = {
sfwFilter: true,
useCustomYamlStringifier: true,
templates: true,
customDateFormat: 'L',
movieTemplate: '',
seriesTemplate: '',
@ -62,6 +69,7 @@ const DEFAULT_SETTINGS: MediaDbPluginSettings = {
wikiTemplate: '',
musicReleaseTemplate: '',
boardgameTemplate: '',
bookTemplate: '',
movieFileNameTemplate: '{{ title }} ({{ year }})',
seriesFileNameTemplate: '{{ title }} ({{ year }})',
@ -70,6 +78,7 @@ const DEFAULT_SETTINGS: MediaDbPluginSettings = {
wikiFileNameTemplate: '{{ title }}',
musicReleaseFileNameTemplate: '{{ title }} (by {{ ENUM:artists }} - {{ year }})',
boardgameFileNameTemplate: '{{ title }} ({{ year }})',
bookFileNameTemplate: '{{ title }} ({{ year }})',
moviePropertyConversionRules: '',
seriesPropertyConversionRules: '',
@ -78,6 +87,7 @@ const DEFAULT_SETTINGS: MediaDbPluginSettings = {
wikiPropertyConversionRules: '',
musicReleasePropertyConversionRules: '',
boardgamePropertyConversionRules: '',
bookPropertyConversionRules: '',
movieFolder: 'Media DB/movies',
seriesFolder: 'Media DB/series',
@ -86,6 +96,7 @@ const DEFAULT_SETTINGS: MediaDbPluginSettings = {
wikiFolder: 'Media DB/wiki',
musicReleaseFolder: 'Media DB/music',
boardgameFolder: 'Media DB/boardgames',
bookFolder: 'Media DB/books',
propertyMappingModels: [],
};
@ -173,11 +184,33 @@ export class MediaDbSettingTab extends PluginSettingTab {
});
});
new Setting(containerEl)
.setName('Date format')
.setDesc(
fragWithHTML(
"Your custom date format. Use <em>'YYYY-MM-DD'</em> for example.<br>" +
"For more syntax, refer to <a href='https://momentjs.com/docs/#/displaying/format/'>format reference</a>.<br>" +
"Your current syntax looks like this: <b><a id='media-db-dateformat-preview' style='pointer-events: none; cursor: default; text-decoration: none;'>" +
this.plugin.dateFormatter.getPreview() +
'</a></b>'
)
)
.addText(cb => {
cb.setPlaceholder(DEFAULT_SETTINGS.customDateFormat)
.setValue(this.plugin.settings.customDateFormat === DEFAULT_SETTINGS.customDateFormat ? '' : this.plugin.settings.customDateFormat)
.onChange(data => {
const newDateFormat = data ? data : DEFAULT_SETTINGS.customDateFormat;
this.plugin.settings.customDateFormat = newDateFormat;
document.getElementById('media-db-dateformat-preview').textContent = this.plugin.dateFormatter.getPreview(newDateFormat); // update preview
this.plugin.saveSettings();
});
});
containerEl.createEl('h3', { text: 'New File Location' });
// region new file location
new Setting(containerEl)
.setName('Movie Folder')
.setDesc('Where newly imported movies should be places.')
.setDesc('Where newly imported movies should be placed.')
.addSearch(cb => {
new FolderSuggest(this.app, cb.inputEl);
cb.setPlaceholder(DEFAULT_SETTINGS.movieFolder)
@ -190,7 +223,7 @@ export class MediaDbSettingTab extends PluginSettingTab {
new Setting(containerEl)
.setName('Series Folder')
.setDesc('Where newly imported series should be places.')
.setDesc('Where newly imported series should be placed.')
.addSearch(cb => {
new FolderSuggest(this.app, cb.inputEl);
cb.setPlaceholder(DEFAULT_SETTINGS.seriesFolder)
@ -216,7 +249,7 @@ export class MediaDbSettingTab extends PluginSettingTab {
new Setting(containerEl)
.setName('Game Folder')
.setDesc('Where newly imported games should be places.')
.setDesc('Where newly imported games should be placed.')
.addSearch(cb => {
new FolderSuggest(this.app, cb.inputEl);
cb.setPlaceholder(DEFAULT_SETTINGS.gameFolder)
@ -229,7 +262,7 @@ export class MediaDbSettingTab extends PluginSettingTab {
new Setting(containerEl)
.setName('Wiki Folder')
.setDesc('Where newly imported wiki articles should be places.')
.setDesc('Where newly imported wiki articles should be placed.')
.addSearch(cb => {
new FolderSuggest(this.app, cb.inputEl);
cb.setPlaceholder(DEFAULT_SETTINGS.wikiFolder)
@ -242,7 +275,7 @@ export class MediaDbSettingTab extends PluginSettingTab {
new Setting(containerEl)
.setName('Music Folder')
.setDesc('Where newly imported music should be places.')
.setDesc('Where newly imported music should be placed.')
.addSearch(cb => {
new FolderSuggest(this.app, cb.inputEl);
cb.setPlaceholder(DEFAULT_SETTINGS.musicReleaseFolder)
@ -257,7 +290,7 @@ export class MediaDbSettingTab extends PluginSettingTab {
.setName('Board Game Folder')
.setDesc('Where newly imported board games should be places.')
.addSearch(cb => {
new FileSuggest(this.app, cb.inputEl);
new FolderSuggest(this.app, cb.inputEl);
cb.setPlaceholder(DEFAULT_SETTINGS.boardgameFolder)
.setValue(this.plugin.settings.boardgameFolder)
.onChange(data => {
@ -265,6 +298,18 @@ export class MediaDbSettingTab extends PluginSettingTab {
this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('Book Folder')
.setDesc('Where newly imported books should be placed.')
.addSearch(cb => {
new FolderSuggest(this.app, cb.inputEl);
cb.setPlaceholder(DEFAULT_SETTINGS.bookFolder)
.setValue(this.plugin.settings.bookFolder)
.onChange(data => {
this.plugin.settings.bookFolder = data;
this.plugin.saveSettings();
});
});
// endregion
containerEl.createEl('h3', { text: 'Template Settings' });
@ -359,6 +404,19 @@ export class MediaDbSettingTab extends PluginSettingTab {
this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('Book template')
.setDesc('Template file to be used when creating a new note for a book.')
.addSearch(cb => {
new FileSuggest(this.app, cb.inputEl);
cb.setPlaceholder('Example: bookTemplate.md')
.setValue(this.plugin.settings.bookTemplate)
.onChange(data => {
this.plugin.settings.bookTemplate = data;
this.plugin.saveSettings();
});
});
// endregion
containerEl.createEl('h3', { text: 'File Name Settings' });
@ -446,6 +504,18 @@ export class MediaDbSettingTab extends PluginSettingTab {
this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('Book file name template')
.setDesc('Template for the file name used when creating a new note for a book.')
.addText(cb => {
cb.setPlaceholder(`Example: ${DEFAULT_SETTINGS.bookFileNameTemplate}`)
.setValue(this.plugin.settings.bookFileNameTemplate)
.onChange(data => {
this.plugin.settings.bookFileNameTemplate = data;
this.plugin.saveSettings();
});
});
// endregion
// region Property Mappings

View file

@ -0,0 +1,67 @@
import { moment } from 'obsidian';
export class DateFormatter {
toFormat: string;
locale: string;
constructor() {
this.toFormat = 'YYYY-MM-DD';
// get locale of this machine (e.g. en, en-gb, de, fr, etc.)
this.locale = new Intl.DateTimeFormat().resolvedOptions().locale;
}
setFormat(format: string): void {
this.toFormat = format;
}
getPreview(format?: string): string {
const today = moment();
if (!format) {
format = this.toFormat;
}
return today.locale(this.locale).format(format);
}
/**
* Tries to format a given date string with the currently set date format.
* You can set a date format by calling `setFormat()`.
*
* @param dateString the date string to be formatted
* @param dateFormat the current format of `dateString`. When this is `null` and the actual format of the
* given date string is not `C2822` or `ISO` format, this function will try to guess the format by using the native `Date` module.
* @param locale the locale of `dateString`. This is needed when `dateString` includes a month or day name and its locale format differs
* from the locale of this machine.
* @returns formatted date string or null if `dateString` is not a valid date
*/
format(dateString: string, dateFormat?: string, locale: string = 'en'): string | null {
if (!dateString) {
return null;
}
let date: moment.Moment;
if (!dateFormat) {
// reading date formats other then C2822 or ISO with moment is deprecated
// see https://momentjs.com/docs/#/parsing/string/
if (this.hasMomentFormat(dateString)) {
// expect C2822 or ISO format
date = moment(dateString);
} else {
// try to read date string with native Date
date = moment(new Date(dateString));
}
} else {
date = moment(dateString, dateFormat, locale);
}
// format date (if it is valid)
return date.isValid() ? date.locale(this.locale).format(this.toFormat) : null;
}
private hasMomentFormat(dateString: string): boolean {
const date = moment(dateString, true); // strict mode
return date.isValid();
}
}

View file

@ -6,4 +6,5 @@ export enum MediaType {
MusicRelease = 'musicRelease',
Wiki = 'wiki',
BoardGame = 'boardgame',
Book = 'book',
}

View file

@ -10,8 +10,9 @@ import { GameModel } from '../models/GameModel';
import { WikiModel } from '../models/WikiModel';
import { MusicReleaseModel } from '../models/MusicReleaseModel';
import { BoardGameModel } from '../models/BoardGameModel';
import { BookModel } from '../models/BookModel';
export const MEDIA_TYPES: MediaType[] = [MediaType.Movie, MediaType.Series, MediaType.Manga, MediaType.Game, MediaType.Wiki, MediaType.MusicRelease, MediaType.BoardGame];
export const MEDIA_TYPES: MediaType[] = [MediaType.Movie, MediaType.Series, MediaType.Manga, MediaType.Game, MediaType.Wiki, MediaType.MusicRelease, MediaType.BoardGame, MediaType.Book];
export class MediaTypeManager {
mediaFileNameTemplateMap: Map<MediaType, string>;
@ -29,6 +30,7 @@ export class MediaTypeManager {
this.mediaFileNameTemplateMap.set(MediaType.Wiki, settings.wikiFileNameTemplate);
this.mediaFileNameTemplateMap.set(MediaType.MusicRelease, settings.musicReleaseFileNameTemplate);
this.mediaFileNameTemplateMap.set(MediaType.BoardGame, settings.boardgameFileNameTemplate);
this.mediaFileNameTemplateMap.set(MediaType.Book, settings.bookFileNameTemplate);
this.mediaTemplateMap = new Map<MediaType, string>();
this.mediaTemplateMap.set(MediaType.Movie, settings.movieTemplate);
@ -38,6 +40,7 @@ export class MediaTypeManager {
this.mediaTemplateMap.set(MediaType.Wiki, settings.wikiTemplate);
this.mediaTemplateMap.set(MediaType.MusicRelease, settings.musicReleaseTemplate);
this.mediaTemplateMap.set(MediaType.BoardGame, settings.boardgameTemplate);
this.mediaTemplateMap.set(MediaType.Book, settings.bookTemplate);
}
updateFolders(settings: MediaDbPluginSettings): void {
@ -49,6 +52,7 @@ export class MediaTypeManager {
this.mediaFolderMap.set(MediaType.Wiki, settings.wikiFolder);
this.mediaFolderMap.set(MediaType.MusicRelease, settings.musicReleaseFolder);
this.mediaFolderMap.set(MediaType.BoardGame, settings.boardgameFolder);
this.mediaFolderMap.set(MediaType.Book, settings.bookFolder);
}
getFileName(mediaTypeModel: MediaTypeModel): string {
@ -117,6 +121,8 @@ export class MediaTypeManager {
return new MusicReleaseModel(obj);
} else if (mediaType === MediaType.BoardGame) {
return new BoardGameModel(obj);
} else if (mediaType === MediaType.Book) {
return new BookModel(obj);
}
return undefined;

View file

@ -135,6 +135,8 @@ export function markdownTable(content: string[][]): string {
return table;
}
export const fragWithHTML = (html: string) => createFragment(frag => (frag.createDiv().innerHTML = html));
export function dateToString(date: Date): string {
return `${date.getMonth() + 1}-${date.getDate()}-${date.getFullYear()}`;
}

View file

@ -19,7 +19,7 @@ export class YAMLConverter {
} else if (typeof value === 'number') {
return value.toString();
} else if (typeof value === 'string') {
return '"' + value.replace("\"", "\\\"") + '"';
return '"' + value.replace('"', '\\"') + '"';
} else if (typeof value === 'object') {
let output = '';

View file

@ -11,9 +11,8 @@
"moduleResolution": "node",
"importHelpers": true,
"isolatedModules": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"lib": ["DOM", "ES5", "ES6", "ES7"]
"lib": ["DOM", "ES5", "ES6", "ES7", "Es2021"]
},
"include": ["**/*.ts"]
}