forked from niekcandaele/obsidian-local-images
-
Notifications
You must be signed in to change notification settings - Fork 42
/
utils.ts
69 lines (58 loc) · 1.87 KB
/
utils.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
import path from "path";
import got from "got";
import { fromBuffer } from "file-type";
import isSvg from "is-svg";
import filenamify from "filenamify";
import { DIRTY_IMAGE_TAG, FORBIDDEN_SYMBOLS_FILENAME_PATTERN } from "./config";
/*
https://stackoverflow.com/a/48032528/1020973
It will be better to do it type-correct.
*/
export async function replaceAsync(str: any, regex: any, asyncFn: any) {
const promises: Promise<any>[] = [];
str.replace(regex, (match: string, ...args: any) => {
const promise = asyncFn(match, ...args);
promises.push(promise);
});
const data = await Promise.all(promises);
return str.replace(regex, () => data.shift());
}
export function isUrl(link: string) {
try {
return Boolean(new URL(link));
} catch (_) {
return false;
}
}
export async function downloadImage(url: string): Promise<ArrayBuffer> {
const res = await got(url, { responseType: "buffer" });
return res.body;
}
export async function fileExtByContent(content: ArrayBuffer) {
const fileExt = (await fromBuffer(content))?.ext;
// if XML, probably it is SVG
if (fileExt == "xml") {
const buffer = Buffer.from(content);
if (isSvg(buffer)) return "svg";
}
return fileExt;
}
function recreateImageTag(match: string, anchor: string, link: string) {
return `![${anchor}](${link})`;
}
export function cleanContent(content: string) {
const cleanedContent = content.replace(DIRTY_IMAGE_TAG, recreateImageTag);
return cleanedContent;
}
export function cleanFileName(name: string) {
const cleanedName = filenamify(name).replace(
FORBIDDEN_SYMBOLS_FILENAME_PATTERN,
"_"
);
return cleanedName;
}
export function pathJoin(dir: string, subpath: string): string {
const result = path.join(dir, subpath);
// it seems that obsidian do not understand paths with backslashes in Windows, so turn them into forward slashes
return result.replace(/\\/g, "/");
}