Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

4.1 KB
Raw Blame
// Open Settings File and Reload Settings (menu.mjs): This computer's config.json, opened in the app the system picks for
// it, and read again by the running server (server/routes/config-reload.ts). Nothing here writes the file or shows
// what is in it: it may hold keys.
import path from "node:path";

export const CONFIG_RELOAD_PATH = "/api/config/reload";

/** This computer's own page is on screen: not My Cloud, a team's Cloud, another server or the screen shown while one
 * wakes, and not this app opened as a remote client of another computer. */
export function localPageShown({ remoteAccess, pageUrl, localOrigin, homePath }) {
  if (remoteAccess || !pageUrl) return false;
  try {
    const page = new URL(pageUrl);
    return page.origin === localOrigin && page.pathname !== homePath;
  } catch {
    return false;
  }
}

/**
 * @param {object} deps
 * @param {() => boolean} deps.here  This computer's own server is the place on screen; the file of a Cloud or another
 *   server is not on this computer.
 * @param {() => string} deps.dataDir  The data folder of the server running here now (a profile's own when one runs).
 * @param {(route: string, init?: RequestInit) => Promise<Response>} deps.request  The app's own request to that server.
 * @param {{ openPath(file: string): Promise<string>, showItemInFolder(file: string): void }} deps.shell
 * @param {{ showMessageBox(options: object): Promise<unknown> }} deps.dialog
 * @param {{ existsSync(file: string): boolean }} deps.fs
 * @param {(key: string, params?: Record<string, string | number>) => string} deps.t
 * @param {(line: string) => void} [deps.log]
 */
export function createSettingsFile({ here, dataDir, request, shell, dialog, fs, t, log = () => {} }) {
  const file = () => path.join(dataDir(), "config.json");
  const tell = (type, message, detail) => dialog.showMessageBox({ type, message, ...(detail ? { detail } : {}) });
  const notHere = () => tell("info", t("native.dialog.settingsFile.notHere"), t("native.dialog.settingsFile.notHereDetail"));
  const missing = () => tell("info", t("native.dialog.settingsFile.missing"), t("native.dialog.settingsFile.missingDetail"));

  async function open() {
    if (!here()) return notHere();
    const target = file();
    // Never created here: a file that is not there yet is said so.
    if (!fs.existsSync(target)) return missing();
    const failed = await shell.openPath(target).catch((error) => String(error?.message ?? error) || "failed");
    if (!failed) return;
    log(`settings file: no app opened it (${failed}); showing it in its folder`);
    shell.showItemInFolder(target);
  }

  async function reload() {
    if (!here()) return notHere();
    let said = null;
    try {
      const res = await request(CONFIG_RELOAD_PATH, { method: "POST", signal: AbortSignal.timeout(15_000) });
      said = await res.json().catch(() => null);
    } catch (error) {
      log(`settings reload: ${error?.message ?? error}`);
    }
    if (said?.ok === true) {
      const applied = Array.isArray(said.applied) ? said.applied : [], restart = Array.isArray(said.restart) ? said.restart : [];
      const lines = [
        ...(applied.length ? [t("native.dialog.settingsReload.applied", { sections: applied.join(", ") })] : []),
        ...(restart.length ? [t("native.dialog.settingsReload.restart", { sections: restart.join(", ") })] : []),
      ];
      return tell("info", t("native.dialog.settingsReload.done"), lines.length ? lines.join("\n\n") : t("native.dialog.settingsReload.unchanged"));
    }
    if (said?.ok === false && said.code === "missing") return missing();
    const why = typeof said?.error === "string" ? said.error : t("native.dialog.settingsReload.notRunning");
    return tell("warning", t("native.dialog.settingsReload.failed"), `${why}\n\n${t("native.dialog.settingsReload.keptLast")}`);
  }

  let shown = null;
  return {
    open,
    reload,
    /** Whether the menu items are on; the menu is built with this. */
    available: () => (shown = here()),
    /** After the window moved to another page: true when the menu needs building again. */
    flipped: () => here() !== shown,
  };
}