Vencord/src/ipcMain.ts

48 lines
1.7 KiB
TypeScript
Raw Normal View History

2022-08-31 02:07:16 +00:00
import { app, BrowserWindow, ipcMain, shell } from "electron";
import { mkdirSync, readFileSync, watch } from "fs";
2022-08-31 02:07:16 +00:00
import { open, readFile, writeFile } from "fs/promises";
2022-08-29 16:11:44 +00:00
import { join } from 'path';
2022-08-31 02:07:16 +00:00
import IpcEvents from './utils/IpcEvents';
2022-08-29 16:11:44 +00:00
const DATA_DIR = join(app.getPath("userData"), "..", "Vencord");
const SETTINGS_DIR = join(DATA_DIR, "settings");
const QUICKCSS_PATH = join(SETTINGS_DIR, "quickCss.css");
2022-08-31 02:07:16 +00:00
const SETTINGS_FILE = join(SETTINGS_DIR, "settings.json");
2022-08-29 16:11:44 +00:00
mkdirSync(SETTINGS_DIR, { recursive: true });
2022-08-29 16:11:44 +00:00
function readCss() {
return readFile(QUICKCSS_PATH, "utf-8").catch(() => "");
}
2022-08-31 02:07:16 +00:00
function readSettings() {
try {
return readFileSync(SETTINGS_FILE, "utf-8");
} catch {
return "{}";
}
}
ipcMain.handle(IpcEvents.GET_SETTINGS_DIR, () => SETTINGS_DIR);
ipcMain.handle(IpcEvents.GET_QUICK_CSS, () => readCss());
ipcMain.handle(IpcEvents.OPEN_PATH, (_, path) => shell.openPath(path));
ipcMain.handle(IpcEvents.OPEN_EXTERNAL, (_, url) => shell.openExternal(url));
2022-08-29 16:11:44 +00:00
2022-09-01 19:40:26 +00:00
// .on because we need Settings synchronously (ipcRenderer.sendSync)
ipcMain.on(IpcEvents.GET_SETTINGS, (e) => e.returnValue = readSettings());
// This is required because otherwise calling SET_SETTINGS in quick succession may lead to concurrent writes
let settingsWriteQueue = Promise.resolve();
ipcMain.handle(IpcEvents.SET_SETTINGS, (_, s) => {
settingsWriteQueue = settingsWriteQueue.then(() => writeFile(SETTINGS_FILE, s));
});
2022-08-29 16:11:44 +00:00
export function initIpc(mainWindow: BrowserWindow) {
open(QUICKCSS_PATH, "a+").then(fd => {
fd.close();
watch(QUICKCSS_PATH, async () => {
2022-08-31 02:07:16 +00:00
mainWindow.webContents.postMessage(IpcEvents.QUICK_CSS_UPDATE, await readCss());
2022-08-29 16:11:44 +00:00
});
});
}