-
Notifications
You must be signed in to change notification settings - Fork 3
/
Utils.ts
50 lines (43 loc) · 1.77 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
import { App, TFile, TFolder, normalizePath } from 'obsidian';
export async function saveFile(app: App, audioBlob: Blob, fileName: string, path: string): Promise<TFile> {
try {
const normalizedPath = normalizePath(path);
const filePath = `${normalizedPath}/${fileName}`;
await ensureDirectoryExists(app, normalizedPath);
const arrayBuffer = await audioBlob.arrayBuffer();
const uint8Array = new Uint8Array(arrayBuffer);
const file = await app.vault.createBinary(filePath, uint8Array);
if (!file) {
throw new Error('File creation failed and returned null');
}
return file;
} catch (error) {
console.error('Error saving audio file:', error);
throw error;
}
}
async function ensureDirectoryExists(app: App, folderPath: string) {
const parts = folderPath.split('/');
let currentPath = '';
for (const part of parts) {
currentPath = currentPath ? `${currentPath}/${part}` : part;
try {
const folder = app.vault.getAbstractFileByPath(currentPath);
if (!folder) {
await app.vault.createFolder(currentPath);
} else if (folder instanceof TFolder) {
console.log(`Folder already exists: ${currentPath}`);
} else {
throw new Error(`${currentPath} is not a folder`);
}
} catch (error) {
if (error.message.includes('Folder already exists')) {
// Folder already exists, continue to the next part
console.log(`Handled existing folder: ${currentPath}`);
} else {
console.error(`Error ensuring directory exists: ${error.message}`);
throw error;
}
}
}
}