index.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import fs from "fs";
  2. import path from "path";
  3. import os from "os";
  4. import { DataPath, IElectronAPI } from "./../../src/types/globalExpose.d";
  5. import { contextBridge, ipcRenderer, shell } from "electron";
  6. import { isProd } from "../utils";
  7. const getPlatform = () => {
  8. if (process.platform === "darwin") {
  9. return 4;
  10. }
  11. if (process.platform === "win32") {
  12. return 3;
  13. }
  14. return 7;
  15. };
  16. const getDataPath = (key: DataPath) => {
  17. switch (key) {
  18. case "public":
  19. return isProd ? ipcRenderer.sendSync("getDataPath", "public") : "";
  20. default:
  21. return "";
  22. }
  23. };
  24. const subscribe = (channel: string, callback: (...args: any[]) => void) => {
  25. const subscription = (_, ...args) => callback(...args);
  26. ipcRenderer.on(channel, subscription);
  27. return () => ipcRenderer.removeListener(channel, subscription);
  28. };
  29. const subscribeOnce = (channel: string, callback: (...args: any[]) => void) => {
  30. ipcRenderer.once(channel, (_, ...args) => callback(...args));
  31. };
  32. const unsubscribeAll = (channel: string) => {
  33. ipcRenderer.removeAllListeners(channel);
  34. };
  35. const ipcInvoke = (channel: string, ...arg: any) => {
  36. return ipcRenderer.invoke(channel, ...arg);
  37. };
  38. const ipcSendSync = (channel: string, ...arg: any) => {
  39. return ipcRenderer.sendSync(channel, ...arg);
  40. };
  41. const saveFileToDisk = async ({
  42. file,
  43. sync,
  44. }: {
  45. file: File;
  46. sync?: boolean;
  47. }): Promise<string> => {
  48. const arrayBuffer = await file.arrayBuffer();
  49. const saveDir = ipcRenderer.sendSync("getDataPath", "userData");
  50. const savePath = path.join(saveDir, file.name);
  51. if (!fs.existsSync(saveDir)) {
  52. fs.mkdirSync(saveDir, { recursive: true });
  53. }
  54. if (sync) {
  55. await fs.promises.writeFile(savePath, Buffer.from(arrayBuffer));
  56. } else {
  57. fs.promises.writeFile(savePath, Buffer.from(arrayBuffer));
  58. }
  59. return savePath;
  60. };
  61. const Api: IElectronAPI = {
  62. getDataPath,
  63. getVersion: () => process.version,
  64. getPlatform,
  65. getSystemVersion: process.getSystemVersion,
  66. subscribe,
  67. subscribeOnce,
  68. unsubscribeAll,
  69. ipcInvoke,
  70. ipcSendSync,
  71. saveFileToDisk,
  72. };
  73. contextBridge.exposeInMainWorld("electronAPI", Api);