generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcreatePodcastNote.ts
93 lines (73 loc) · 2.1 KB
/
createPodcastNote.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Notice, TFile } from "obsidian";
import { FilePathTemplateEngine, NoteTemplateEngine } from "./TemplateEngine";
import { Episode } from "./types/Episode";
import { get } from "svelte/store";
import { plugin } from "./store";
import addExtension from "./utility/addExtension";
export default async function createPodcastNote(
episode: Episode
): Promise<void> {
const pluginInstance = get(plugin);
const filePath = FilePathTemplateEngine(
pluginInstance.settings.note.path,
episode
);
const filePathDotMd = addExtension(filePath, "md");
const content = NoteTemplateEngine(
pluginInstance.settings.note.template,
episode
);
try {
const file = await createFileIfNotExists(
filePathDotMd,
content,
episode
);
app.workspace.getLeaf().openFile(file);
} catch (error) {
console.error(error);
new Notice(`Failed to create note: "${filePathDotMd}"`);
}
}
export function getPodcastNote(episode: Episode): TFile | null {
const pluginInstance = get(plugin);
const filePath = FilePathTemplateEngine(
pluginInstance.settings.note.path,
episode
);
const filePathDotMd = addExtension(filePath, "md");
const file = app.vault.getAbstractFileByPath(filePathDotMd);
if (!file || !(file instanceof TFile)) {
return null;
}
return file;
}
export function openPodcastNote(epiosode: Episode): void {
const file = getPodcastNote(epiosode);
if (!file) {
new Notice(`Note for "${epiosode.title}" does not exist`);
return;
}
app.workspace.getLeaf().openFile(file);
}
async function createFileIfNotExists(
path: string,
content: string,
episode: Episode,
createFolder = true
): Promise<TFile> {
const file = getPodcastNote(episode);
if (file) {
new Notice(`Note for "${episode.title}" already exists`);
return file;
}
const foldersInPath = path.split("/").slice(0, -1);
for (let i = 0; i < foldersInPath.length; i++) {
const folderPath = foldersInPath.slice(0, i + 1).join("/");
const folder = app.vault.getAbstractFileByPath(folderPath);
if (!folder && createFolder) {
await app.vault.createFolder(folderPath);
}
}
return await app.vault.create(path, content);
}