generated from tpl/obsidian-sample-plugin
93 lines
2.5 KiB
TypeScript
93 lines
2.5 KiB
TypeScript
import {
|
|
type Editor,
|
|
type MarkdownView,
|
|
type MarkdownFileInfo,
|
|
type App,
|
|
Notice,
|
|
TFile,
|
|
} from "obsidian";
|
|
import { EditorCheckCommand } from "./Command";
|
|
import type { BookTrackerPluginSettings } from "@ui/settings";
|
|
import { RatingModal } from "@ui/modals";
|
|
import type { ReadingLog } from "@utils/ReadingLog";
|
|
import { READ_STATE } from "@src/const";
|
|
import { mkdirRecursive, dirname } from "@utils/fs";
|
|
|
|
export class LogReadingFinishedCommand extends EditorCheckCommand {
|
|
constructor(
|
|
private readonly app: App,
|
|
private readonly readingLog: ReadingLog,
|
|
private readonly settings: BookTrackerPluginSettings
|
|
) {
|
|
super("log-reading-finished", "Log Reading Finished");
|
|
}
|
|
|
|
private getPageCount(file: TFile): number {
|
|
return (
|
|
(this.app.metadataCache.getFileCache(file)?.frontmatter?.[
|
|
this.settings.pageCountProperty
|
|
] as number | undefined) ?? 0
|
|
);
|
|
}
|
|
|
|
protected check(
|
|
_editor: Editor,
|
|
ctx: MarkdownView | MarkdownFileInfo
|
|
): boolean {
|
|
return !(
|
|
ctx.file === null ||
|
|
this.settings.statusProperty === "" ||
|
|
this.settings.endDateProperty === "" ||
|
|
this.settings.ratingProperty === "" ||
|
|
this.settings.pageCountProperty === "" ||
|
|
this.getPageCount(ctx.file) <= 0
|
|
);
|
|
}
|
|
|
|
protected async run(
|
|
_editor: Editor,
|
|
ctx: MarkdownView | MarkdownFileInfo
|
|
): Promise<void> {
|
|
const file = ctx.file!;
|
|
const fileName = file.basename;
|
|
const pageCount = this.getPageCount(file);
|
|
|
|
const ratings = await RatingModal.createAndOpen(
|
|
this.app,
|
|
this.settings.spiceProperty !== ""
|
|
);
|
|
|
|
try {
|
|
await this.readingLog.createEntry(fileName, pageCount, pageCount);
|
|
} catch (error) {
|
|
new Notice(
|
|
`Failed to log reading progress for ${fileName}: ${error}`
|
|
);
|
|
return;
|
|
}
|
|
|
|
// @ts-expect-error Moment is provided by Obsidian
|
|
const endDate = moment().format("YYYY-MM-DD");
|
|
|
|
this.app.fileManager.processFrontMatter(file, (frontMatter) => {
|
|
frontMatter[this.settings.statusProperty] = READ_STATE;
|
|
frontMatter[this.settings.endDateProperty] = endDate;
|
|
frontMatter[this.settings.ratingProperty] = ratings.rating;
|
|
if (this.settings.spiceProperty !== "") {
|
|
frontMatter[this.settings.spiceProperty] = ratings.spice;
|
|
}
|
|
});
|
|
|
|
if (this.settings.organizeReadBooks) {
|
|
// @ts-expect-error Moment is provided by Obsidian
|
|
const datePath = moment().format("YYYY/MMMM");
|
|
const newPath = `${this.settings.readBooksFolder}/${datePath}/${file.name}`;
|
|
|
|
await mkdirRecursive(this.app.vault, dirname(newPath));
|
|
await this.app.vault.rename(file, newPath);
|
|
}
|
|
|
|
new Notice("Reading finished for " + fileName);
|
|
}
|
|
}
|