From 2bad5a11841a10bb41db0114e30984e0cf3e53d6 Mon Sep 17 00:00:00 2001 From: kangfenmao Date: Mon, 9 Sep 2024 16:15:49 +0800 Subject: [PATCH] feat: add file class --- src/main/file.ts | 80 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 src/main/file.ts diff --git a/src/main/file.ts b/src/main/file.ts new file mode 100644 index 00000000..3d42490b --- /dev/null +++ b/src/main/file.ts @@ -0,0 +1,80 @@ +import { app, dialog } from 'electron' +import * as fs from 'fs' +import * as path from 'path' +import { v4 as uuidv4 } from 'uuid' + +interface FileMetadata { + id: string + name: string + path: string + createdAt: Date + size: number +} + +export class File { + private storageDir: string + + constructor() { + this.storageDir = path.join(app.getPath('userData'), 'Data', 'Files') + this.initStorageDir() + } + + private initStorageDir(): void { + if (!fs.existsSync(this.storageDir)) { + fs.mkdirSync(this.storageDir, { recursive: true }) + } + } + + async selectFile(): Promise { + const result = await dialog.showOpenDialog({ + properties: ['openFile'] + }) + + if (result.canceled || result.filePaths.length === 0) { + return null + } + + const filePath = result.filePaths[0] + const stats = fs.statSync(filePath) + + return { + id: uuidv4(), + name: path.basename(filePath), + path: filePath, + createdAt: stats.birthtime, + size: stats.size + } + } + + async uploadFile(filePath: string): Promise { + const id = uuidv4() + const name = path.basename(filePath) + const destPath = path.join(this.storageDir, id) + + await fs.promises.copyFile(filePath, destPath) + const stats = await fs.promises.stat(destPath) + + return { + id, + name, + path: destPath, + createdAt: stats.birthtime, + size: stats.size + } + } + + async deleteFile(fileId: string): Promise { + const filePath = path.join(this.storageDir, fileId) + await fs.promises.unlink(filePath) + } + + async batchUploadFiles(filePaths: string[]): Promise { + const uploadPromises = filePaths.map((filePath) => this.uploadFile(filePath)) + return Promise.all(uploadPromises) + } + + async batchDeleteFiles(fileIds: string[]): Promise { + const deletePromises = fileIds.map((fileId) => this.deleteFile(fileId)) + await Promise.all(deletePromises) + } +}