const { app, BrowserWindow, ipcMain, safeStorage, dialog, Notification, shell } = require('electron') const path = require('node:path') const fs = require('node:fs/promises') const isDev = !app.isPackaged app.setName('Metatron.Drive') app.setAppUserModelId('metatron.drive') function tokenPath() { return path.join(app.getPath('userData'), 'session.bin') } async function createWindow() { const window = new BrowserWindow({ width: 1280, height: 820, minWidth: 980, minHeight: 650, show: false, backgroundColor: '#f6f8fc', title: 'Metatron.Drive', autoHideMenuBar: true, webPreferences: { preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true, }, }) window.once('ready-to-show', () => window.show()) if (isDev) await window.loadURL('http://localhost:5173') else await window.loadFile(path.join(__dirname, '..', 'dist', 'index.html')) } app.whenReady().then(() => { ipcMain.handle('session:read', async () => { try { const encrypted = await fs.readFile(tokenPath()) return safeStorage.isEncryptionAvailable() ? safeStorage.decryptString(encrypted) : encrypted.toString('utf8') } catch { return null } }) ipcMain.handle('session:write', async (_, token) => { const payload = safeStorage.isEncryptionAvailable() ? safeStorage.encryptString(token) : Buffer.from(token, 'utf8') await fs.mkdir(app.getPath('userData'), { recursive: true }) await fs.writeFile(tokenPath(), payload) }) ipcMain.handle('session:clear', async () => { await fs.rm(tokenPath(), { force: true }) }) ipcMain.handle('file:save', async (_, { name, bytes }) => { const result = await dialog.showSaveDialog({ defaultPath: name }) if (result.canceled || !result.filePath) return false await fs.writeFile(result.filePath, Buffer.from(bytes)) return true }) ipcMain.handle('notification:show', (_, { title, body }) => { if (Notification.isSupported()) new Notification({ title, body }).show() }) ipcMain.handle('shell:openExternal', (_, url) => shell.openExternal(url)) createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() })