index.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 ipcSend = (channel: string, ...arg: any) => {
  42. return ipcRenderer.send(channel, ...arg);
  43. };
  44. const saveFileToDisk = async ({
  45. file,
  46. sync,
  47. }: {
  48. file: File;
  49. sync?: boolean;
  50. }): Promise<string> => {
  51. const arrayBuffer = await file.arrayBuffer();
  52. const saveDir = ipcRenderer.sendSync("getDataPath", "userData");
  53. const savePath = path.join(saveDir, file.name);
  54. if (!fs.existsSync(saveDir)) {
  55. fs.mkdirSync(saveDir, { recursive: true });
  56. }
  57. if (sync) {
  58. await fs.promises.writeFile(savePath, Buffer.from(arrayBuffer));
  59. } else {
  60. fs.promises.writeFile(savePath, Buffer.from(arrayBuffer));
  61. }
  62. return savePath;
  63. };
  64. const Api: IElectronAPI = {
  65. getDataPath,
  66. getVersion: () => process.version,
  67. getPlatform,
  68. getSystemVersion: process.getSystemVersion,
  69. subscribe,
  70. subscribeOnce,
  71. unsubscribeAll,
  72. ipcInvoke,
  73. ipcSendSync,
  74. ipcSend,
  75. saveFileToDisk,
  76. };
  77. contextBridge.exposeInMainWorld("electronAPI", Api);