generated from obsidianmd/obsidian-sample-plugin
-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathTemplateEngine.ts
247 lines (211 loc) · 6.67 KB
/
TemplateEngine.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { htmlToMarkdown, Notice } from "obsidian";
import type { Episode } from "src/types/Episode";
import Fuse from "fuse.js";
import { plugin } from "src/store";
import { get } from "svelte/store";
import getUrlExtension from "./utility/getUrlExtension";
interface Tags {
[tag: string]: string | ((...args: unknown[]) => string);
}
type AddTagFn = (
tag: Lowercase<string>,
value: string | ((...args: unknown[]) => string),
) => void;
type ReplacerFn = (template: string) => string;
function useTemplateEngine(): Readonly<[ReplacerFn, AddTagFn]> {
const tags: Tags = {};
function addTag(
tag: Lowercase<string>,
value: string | ((...args: unknown[]) => string),
): void {
tags[tag] = value;
}
function replacer(template: string): string {
return template.replace(
/\{\{(.*?)(:\s*?.+?)?\}\}/g,
(match: string, tagId: string, params: string) => {
const tagValue = tags[tagId.toLowerCase()];
if (tagValue === null || tagValue === undefined) {
const fuse = new Fuse(Object.keys(tags), {
shouldSort: true,
findAllMatches: false,
threshold: 0.4,
isCaseSensitive: false,
});
const similarTag = fuse.search(tagId);
new Notice(
`Tag ${tagId} is invalid.${
similarTag.length > 0
? ` Did you mean ${similarTag[0].item}?`
: ""
}`,
);
return match;
}
if (typeof tagValue === "function") {
if (params) {
// Remove initial colon with splice.
const splitParams = params.slice(1).split(",");
const args = Array.isArray(splitParams) ? splitParams : [params];
return tagValue(...args);
}
return tagValue();
}
return tagValue;
},
);
}
return [replacer, addTag] as const;
}
export function NoteTemplateEngine(template: string, episode: Episode) {
const [replacer, addTag] = useTemplateEngine();
addTag("title", episode.title);
addTag("description", (prependToLines?: string) => {
// reduce multiple new lines
const sanitizeDescription = htmlToMarkdown(episode.description).replace(
/\n{3,}/g,
"\n\n",
);
if (prependToLines) {
return sanitizeDescription
.split("\n")
.map((str) => `${prependToLines}${str}`)
.join("\n");
}
return sanitizeDescription;
});
addTag("content", (prependToLines?: string) => {
if (prependToLines) {
return htmlToMarkdown(episode.content)
.split("\n")
.map((str) => `${prependToLines}${str}`)
.join("\n");
}
return htmlToMarkdown(episode.content);
});
addTag("safetitle", replaceIllegalFileNameCharactersInString(episode.title));
addTag("url", episode.url);
addTag("date", (format?: string) =>
episode.episodeDate
? window.moment(episode.episodeDate).format(format ?? "YYYY-MM-DD")
: "",
);
addTag(
"podcast",
replaceIllegalFileNameCharactersInString(episode.podcastName),
);
addTag("artwork", episode.artworkUrl ?? "");
return replacer(template);
}
export function TimestampTemplateEngine(template: string) {
const [replacer, addTag] = useTemplateEngine();
addTag("time", (format?: string) =>
get(plugin).api.getPodcastTimeFormatted(format ?? "HH:mm:ss"),
);
addTag("linktime", (format?: string) =>
get(plugin).api.getPodcastTimeFormatted(format ?? "HH:mm:ss", true),
);
return replacer(template);
}
export function FilePathTemplateEngine(template: string, episode: Episode) {
const [replacer, addTag] = useTemplateEngine();
addTag("title", (whitespaceReplacement?: string) => {
const legalTitle = replaceIllegalFileNameCharactersInString(episode.title);
if (whitespaceReplacement) {
return legalTitle.replace(/\s+/g, whitespaceReplacement);
}
return legalTitle;
});
addTag("podcast", (whitespaceReplacement?: string) => {
const legalName = replaceIllegalFileNameCharactersInString(
episode.podcastName,
);
if (whitespaceReplacement) {
return legalName.replace(/\s+/g, whitespaceReplacement);
}
return legalName;
});
addTag("date", (format?: string) =>
episode.episodeDate
? window.moment(episode.episodeDate).format(format ?? "YYYY-MM-DD")
: "",
);
return replacer(template);
}
export function DownloadPathTemplateEngine(template: string, episode: Episode) {
// Removing the template extension, as this is added automatically depending on file type.
const templateExtension = getUrlExtension(template);
const templateWithoutExtension = templateExtension
? template.replace(templateExtension, "")
: template;
const [replacer, addTag] = useTemplateEngine();
addTag("title", (whitespaceReplacement?: string) => {
const legalTitle = replaceIllegalFileNameCharactersInString(episode.title);
if (whitespaceReplacement) {
return legalTitle.replace(/\s+/g, whitespaceReplacement);
}
return legalTitle;
});
addTag("podcast", (whitespaceReplacement?: string) => {
const legalName = replaceIllegalFileNameCharactersInString(
episode.podcastName,
);
if (whitespaceReplacement) {
return legalName.replace(/\s+/g, whitespaceReplacement);
}
return legalName;
});
addTag("date", (format?: string) =>
episode.episodeDate
? window.moment(episode.episodeDate).format(format ?? "YYYY-MM-DD")
: "",
);
return replacer(templateWithoutExtension);
}
export function TranscriptTemplateEngine(
template: string,
episode: Episode,
transcription: string,
) {
const [replacer, addTag] = useTemplateEngine();
addTag("title", (whitespaceReplacement?: string) => {
const legalTitle = replaceIllegalFileNameCharactersInString(episode.title);
if (whitespaceReplacement) {
return legalTitle.replace(/\s+/g, whitespaceReplacement);
}
return legalTitle;
});
addTag("podcast", (whitespaceReplacement?: string) => {
const legalName = replaceIllegalFileNameCharactersInString(
episode.podcastName,
);
if (whitespaceReplacement) {
return legalName.replace(/\s+/g, whitespaceReplacement);
}
return legalName;
});
addTag("date", (format?: string) =>
episode.episodeDate
? window.moment(episode.episodeDate).format(format ?? "YYYY-MM-DD")
: "",
);
addTag("transcript", transcription);
addTag("description", (prependToLines?: string) => {
if (prependToLines) {
return htmlToMarkdown(episode.description)
.split("\n")
.map((str) => `${prependToLines}${str}`)
.join("\n");
}
return htmlToMarkdown(episode.description);
});
addTag("url", episode.url);
addTag("artwork", episode.artworkUrl ?? "");
return replacer(template);
}
function replaceIllegalFileNameCharactersInString(string: string) {
return string
.replace(/[\\,#%&{}/*<>$'":@\u2023|\\.\?]/g, "") // Replace illegal file name characters with empty string
.replace(/\n/, " ") // replace newlines with spaces
.replace(" ", " "); // replace multiple spaces with single space to make sure we don't have double spaces in the file name
}