-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathimages-storage.ts
More file actions
108 lines (81 loc) · 2.85 KB
/
images-storage.ts
File metadata and controls
108 lines (81 loc) · 2.85 KB
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
import type { App, TFile } from 'obsidian';
import { normalizePath, Notice } from 'obsidian';
import type { EnsureImagesNotices } from './types';
import {
fetchImageData,
getImageExtension,
getImageExtensionFromMimeType,
hashArrayBuffer,
} from './image-utils';
import { encodePathForMarkdown } from './text-utils';
import { ensureFolder } from './vault-utils';
async function downloadImages(app: App, imageUrls: string[], imageFolderPath: string) {
const urlToPath = new Map<string, string>();
const hashToName = new Map<string, string>();
let failed = false;
for (const url of imageUrls) {
try {
const imageResponse = await fetchImageData(url);
if (!imageResponse) {
failed = true;
continue;
}
const hash = await hashArrayBuffer(imageResponse.data);
let fileName = hashToName.get(hash);
if (!fileName) {
const extension =
getImageExtensionFromMimeType(imageResponse.mimeType) ||
getImageExtension(url) ||
'jpg';
fileName = `${hash}.${extension}`;
hashToName.set(hash, fileName);
}
const targetPath = normalizePath(`${imageFolderPath}/${fileName}`);
if (!app.vault.getAbstractFileByPath(targetPath)) {
await app.vault.adapter.writeBinary(targetPath, imageResponse.data);
}
urlToPath.set(url, encodePathForMarkdown(`${imageFolderPath}/${fileName}`));
} catch (error) {
console.error(`Failed to download ${url}`, error);
failed = true;
}
}
if (failed) {
throw new Error('Some images failed to download.');
}
return urlToPath;
}
export async function ensureImages(
app: App,
file: TFile,
imageUrls: string[],
imagesFolderPath: string,
notices: EnsureImagesNotices,
) {
if (imageUrls.length === 0) return true;
try {
await ensureFolder(app, imagesFolderPath);
} catch (error) {
console.error('Failed to create image folder', error);
new Notice(notices.folderFailureNotice);
return false;
}
try {
const urlToPath = await downloadImages(app, imageUrls, imagesFolderPath);
if (urlToPath.size > 0) {
const content = await app.vault.read(file);
let updated = content;
for (const [url, path] of urlToPath.entries()) {
updated = updated.split(url).join(path);
}
if (updated !== content) {
await app.vault.modify(file, updated);
}
}
} catch (error) {
console.error('Failed to download images', error);
new Notice(notices.downloadFailureNotice);
return false;
}
return true;
}