Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Prune desktop comments

Manav Rathi3b3e34a434cc
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 512fd7ac3f..8722e97407 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -1,14 +1,3 @@
-/**
- * @file Entry point for the main (Node.js) process of our Electron app.
- *
- * The code in this file is invoked by Electron when our app starts -
- * Conceptually (after all the transpilation etc has happened) this can be
- * thought of `electron main.ts`. We're running in the context of the so called
- * "main" process which runs in a Node.js environment.
- *
- * https://www.electronjs.org/docs/latest/tutorial/process-model#the-main-process
- */
-
import { nativeImage, shell } from "electron/common";
import {
BrowserWindow,
@@ -41,40 +30,16 @@ import { registerStreamProtocol } from "./main/stream";
import { wait } from "./main/utils/common";
import { isDev } from "./main/utils/electron";
-/**
- * The URL where the renderer HTML is being served from.
- */
const rendererURL = "ente://app";
-/**
- * We want to hide our window instead of closing it when the user presses the
- * cross button on the window.
- *
- * > This is because there is 1. a perceptible initial window creation time for
- * > our app, and 2. because the long running processes like export and watch
- * > folders are tied to the lifetime of the window and otherwise won't run in
- * > the background.
- *
- * Intercepting the window close event and using that to instead hide it is
- * easy, however that prevents the actual app quit to stop working (since the
- * window never gets closed).
- *
- * So to achieve our original goal (hide window instead of closing) without
- * disabling expected app quits, we keep a flag, and we turn it on when we're
- * part of the quit sequence. When this flag is on, we bypass the code that
- * prevents the window from being closed.
- */
+// Closing normally hides the window so exports and folder watches keep running.
+// Quit paths set this flag to close it for real.
let shouldAllowWindowClose = false;
export const allowWindowClose = (): void => {
shouldAllowWindowClose = true;
};
-/**
- * The app's entry point.
- *
- * We call this at the end of this file.
- */
const main = () => {
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
@@ -87,13 +52,12 @@ const main = () => {
initLogging();
logStartupBanner();
registerForEnteLinks();
- // The order of the next two calls is important
+
+ // Electron keeps the last privileged-scheme registration. This must follow
+ // next-electron-server's registration so both "ente" and "stream" survive.
setupRendererServer();
registerPrivilegedSchemes();
- /**
- * Handle an open URL request, but ensuring that we have a mainWindow.
- */
const handleOpenEnteURLEnsuringWindow = (url: string) => {
log.info(`Attempting to handle request to open URL: ${url}`);
if (mainWindow) handleEnteLinks(mainWindow, url);
@@ -101,37 +65,25 @@ const main = () => {
};
app.on("second-instance", (_, argv: string[]) => {
- // Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
mainWindow.show();
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
- // On Windows and Linux, this is how we get deeplinks.
- //
- // See: registerForEnteLinks
- //
- // Note that Chromium reserves the right to fudge with the order of the
- // command line arguments, including inserting things in arbitrary
- // places, so we need to go through the args to find the one that is
- // pertinent to us (if any) instead of looking at a fixed position.
+
+ // Chromium may reorder or insert arguments, so the URL has no fixed index.
const url = argv.find((arg) => arg.startsWith("ente://app"));
if (url) handleOpenEnteURLEnsuringWindow(url);
});
- // Emitted once, when Electron has finished initializing.
- //
- // Note that some Electron APIs can only be used after this event occurs.
void app.whenReady().then(() => {
attachProcessHandlers();
void (async () => {
if (isDev) await waitForRendererDevServer();
- // Create window and prepare for the renderer.
mainWindow = createMainWindow();
- // Setup IPC and streams.
const watcher = createWatcher(mainWindow);
attachIPCHandlers();
attachMainWindowIPCHandlers(mainWindow);
@@ -139,7 +91,6 @@ const main = () => {
attachLogoutIPCHandler(watcher);
registerStreamProtocol(mainWindow);
- // Configure the renderer's environment.
const webContents = mainWindow.webContents;
setDownloadPath(webContents);
allowExternalLinks(webContents);
@@ -147,18 +98,14 @@ const main = () => {
allowAllCORSOrigins(webContents);
allowOpenStreetMapRequestIdentification(webContents);
- // Start loading the renderer.
void mainWindow.loadURL(rendererURL);
- // Continue on with the rest of the startup sequence.
Menu.setApplicationMenu(createApplicationMenu(mainWindow));
setupTrayItem(mainWindow);
setupAutoUpdater(mainWindow);
})();
});
- // This is a macOS only event. Show our window when the user activates the
- // app, e.g. by clicking on its dock icon.
app.on("activate", () => mainWindow?.show());
app.on("before-quit", () => {
@@ -166,15 +113,9 @@ const main = () => {
allowWindowClose();
});
- // On macOS, this is how we get deeplinks. See: registerForEnteLinks
app.on("open-url", (_, url) => handleOpenEnteURLEnsuringWindow(url));
};
-/**
- * Log a standard startup banner.
- *
- * This helps us identify app starts and other environment details in the logs.
- */
const logStartupBanner = () => {
const version = isDev ? "dev" : app.getVersion();
log.info(`Starting ente-photos-desktop ${version}`);
@@ -185,49 +126,11 @@ const logStartupBanner = () => {
log.info("Running on", { platform, osRelease, systemVersion });
};
-/**
- * next-electron-server allows up to directly use the output of `next build` in
- * production mode and `next dev` in development mode, whilst keeping the rest
- * of our code the same.
- *
- * It uses protocol handlers to serve files from the "ente://" protocol.
- *
- * - In development this is proxied to http://localhost:3008
- * - In production it serves files from the `/out` directory
- *
- * For more details, see this comparison:
- * https://github.com/HaNdTriX/next-electron-server/issues/5
- */
const setupRendererServer = () => serveNextAt(rendererURL, { port: 3008 });
-/**
- * Register privileged schemes.
- *
- * We have two privileged schemes:
- *
- * 1. "ente", used for serving our web app (@see {@link setupRendererServer}).
- *
- * 2. "stream", used for streaming IPC (@see {@link registerStreamProtocol}).
- *
- * Both of these need some privileges, however, the documentation for Electron's
- * [registerSchemesAsPrivileged](https://www.electronjs.org/docs/latest/api/protocol)
- * says:
- *
- * > This method ... can be called only once.
- *
- * The library we use for the "ente" scheme, next-electron-server, already calls
- * it once when we invoke {@link setupRendererServer}.
- *
- * In practice calling it multiple times just causes the values to be
- * overwritten, and the last call wins. So we don't need to modify
- * next-electron-server to prevent it from calling registerSchemesAsPrivileged.
- * Instead, we (a) repeat what next-electron-server had done here, and (b)
- * ensure that we're called after {@link setupRendererServer}.
- */
const registerPrivilegedSchemes = () => {
protocol.registerSchemesAsPrivileged([
{
- // Taken verbatim from next-electron-server's code (index.js)
scheme: "ente",
privileges: {
standard: true,
@@ -244,149 +147,53 @@ const registerPrivilegedSchemes = () => {
]);
};
-/**
- * Register a handler for deeplinks, for the "ente://" protocol.
- *
- * See: [Note: Passkey verification in the desktop app].
- *
- * Implementation notes:
- * - https://www.electronjs.org/docs/latest/tutorial/launch-app-from-url-in-another-app
- * - This works only when the app is packaged.
- * - On Windows and Linux, we get the deeplink in the "second-instance" event.
- * - On macOS, we get the deeplink in the "open-url" event.
- */
const registerForEnteLinks = () => app.setAsDefaultProtocolClient("ente");
-/** Sibling of {@link registerForEnteLinks}. */
const handleEnteLinks = (mainWindow: BrowserWindow, url: string) => {
- // [Note: Using deeplinks to navigate in desktop app]
- //
- // Both
- //
- // - our deeplink protocol, and
- // - the protocol we're using to serve/ our bundled web app
- //
- // use the same scheme ("ente://"), so the URL can directly be forwarded.
+ // Deep links and the bundled renderer deliberately share the ente:// scheme.
mainWindow.webContents.send("openEnteURL", url);
};
-/** Attach handlers to the (node) process. */
const attachProcessHandlers = () => {
- // Gracefully quit the app if we get a SIGINT.
- //
- // This is meant to allow graceful shutdowns during development, when the
- // app is launched using `npm run dev`. In such cases, pressing CTRL-C sends a
- // SIGINT to the process. The default handling of SIGINT is not graceful
- // enough (apparently), since I can observe that sometimes recent writes to
- // local storage are lost. This has also been reported by other people:
- // https://github.com/electron/electron/issues/22048
- //
- // Hopefully handling SIGINT prevents that issue. But beyond that, it allows
- // us to also write out `userPreferences.json` (as would happen during a
- // normal quit sequence), so this is an improvement either ways.
+ // Electron's default SIGINT shutdown can lose recent storage writes in dev.
process.on("SIGINT", () => app.quit());
};
-/**
- * Wait for the renderer process' dev server to be ready.
- *
- * After creating the main window, we load the web app into it using `loadURL`.
- * In production, these are served directly from the SSR-ed static files bundled
- * with the app, and so can be served instantly. However, during development, we
- * start a dev server for serving the HMR-ed files.
- *
- * This Next.js HMR server takes time to startup and is sometimes not ready to
- * handle incoming requests when the main window tries to load it. In such
- * cases, Electron just hangs with this:
- *
- * [main] Error: net::ERR_CONNECTION_REFUSED
- * [main] at SimpleURLLoaderWrapper.<anonymous> (node:electron/js2c/browser_init:2:114482)
- * [main] at SimpleURLLoaderWrapper.emit (node:events:519:28)
- *
- * As a workaround, we wait for 1 second.
- *
- * I'd also tried fancier workaround - polling the URL - but waits until the dev
- * server has the response ready, delaying everything many seconds (we just want
- * to see if the dev server can accept connections). The 1 second delay seems to
- * get the job done for now.
- *
- * This workaround can likely be removed when we migrate to Vite.
- */
+// loadURL does not retry if the Next dev server returns ERR_CONNECTION_REFUSED.
const waitForRendererDevServer = () => wait(1000);
-/**
- * Create an return the {@link BrowserWindow} that will form our app's UI.
- *
- * This window will show the HTML served from {@link rendererURL}.
- */
const createMainWindow = () => {
const icon = nativeImage.createFromPath(
path.join(isDev ? "build" : process.resourcesPath, "window-icon.png"),
);
const bounds = windowBounds();
- // Create the main window. This'll show our web content.
const window = new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, "preload.js"),
sandbox: true,
},
icon,
- // Set the window's position and size (if we have one saved).
...(bounds ?? {}),
- // Enforce a minimum size
...minimumWindowSize(),
- // [Note: Customize the desktop title bar]
- //
- // 1. Remove the default title bar.
- // 2. Reintroduce the title bar controls.
- // 3. Show a custom title bar in the renderer.
- //
- // For step 3, we use `app-region: drag` to allow dragging the window by
- // the title bar, and use the Window Controls Overlay CSS environment
- // variables to determine its dimensions. Note that these overlay CSS
- // environment vars are only available when titleBarOverlay is true, so
- // unlike the tutorial which enables it only for Windows and Linux, we
- // do it (Step 2) unconditionally (i.e., on macOS too).
- //
- // https://www.electronjs.org/docs/latest/tutorial/custom-title-bar#create-a-custom-title-bar
- //
- // Note that by default on Windows, the color of the WCO title bar
- // overlay (three buttons - minimize, maximize, close - on the top
- // right) is static, and unlike Linux, doesn't adapt to the theme /
- // content. Explicitly choosing a dark background, while it won't work
- // always (if the user's theme is light), is better than picking a light
- // background since the main image viewer is always dark.
+ // The overlay must be enabled on macOS too for its CSS dimensions.
titleBarStyle: "hidden",
titleBarOverlay:
process.platform == "win32"
? { color: "black", symbolColor: "#cdcdcd" }
: true,
- // The color to show in the window until the web content gets loaded.
- // https://www.electronjs.org/docs/latest/api/browser-window#setting-the-backgroundcolor-property
- //
- // To avoid a flash, we want to use the same background color as the
- // theme of their choice. Unless the user has modified their preference
- // to not follow the system, we can deduce it from the current OS theme.
- //
- // See: https://www.electronjs.org/docs/latest/tutorial/dark-mode
+ // Match the initial paint to the OS theme to avoid a white or black flash.
backgroundColor: nativeTheme.shouldUseDarkColors ? "black" : "white",
- // We'll show it conditionally depending on `wasAutoLaunched` later.
show: false,
});
const wasAutoLaunched = autoLauncher.wasAutoLaunched();
if (wasAutoLaunched) {
- // Don't automatically show the app's window if we were auto-launched.
- // On macOS, also hide the dock icon.
app.dock?.hide();
} else {
- // Show our window otherwise, maximizing it if we're not asked to set it
- // to a specific size.
bounds ? window.show() : window.maximize();
}
- // Open the DevTools automatically when running in dev mode
if (isDev) window.webContents.openDevTools();
window.webContents.on("render-process-gone", (_, details) => {
@@ -394,23 +201,14 @@ const createMainWindow = () => {
window.webContents.reload();
});
- // "The unresponsive event is fired when Chromium detects that your
- // webContents is not responding to input messages for > 30 seconds."
window.webContents.on("unresponsive", () => {
- // There is a known case when this can happen: When the user to select a
- // folder to upload (Upload > Folder), the browser callback to us takes
- // some time. When trying to upload very large folders on slower Windows
- // machines, this can take up to 30 seconds.
log.warn("MainWindow's webContents are unresponsive");
});
window.on("close", (event) => {
if (!shouldAllowWindowClose) {
event.preventDefault();
- // Only hide the dock icon when we are intercepting an explicit
- // close action. On macOS, the generic "hide" event is also emitted
- // for occlusion changes, so reacting there causes the dock icon to
- // disappear when the window is fully covered by another window.
+ // macOS also emits "hide" for occlusion, so change the Dock here only.
if (shouldHideDockIcon()) {
app.dock?.hide();
}
@@ -421,57 +219,23 @@ const createMainWindow = () => {
window.on("show", () => void app.dock?.show());
- // Let ipcRenderer know when mainWindow is in the foreground so that it can
- // in turn inform the renderer process.
window.on("focus", () => window.webContents.send("mainWindowFocus"));
window.on("blur", () => window.webContents.send("mainWindowBlur"));
return window;
};
-/**
- * The position and size to use when showing the main window.
- *
- * The return value is `undefined` if the app's window was maximized the last
- * time around, and so if we should restore it to the maximized state.
- *
- * Otherwise it returns the position and size of the window the last time the
- * app quit.
- *
- * If there is no such saved value (or if it is the first time the user is
- * running the app), return a default size.
- */
const windowBounds = () => {
if (userPreferences.get("isWindowMaximized")) return undefined;
const bounds = userPreferences.get("windowBounds");
if (bounds) return bounds;
- // Default size. Picked arbitrarily as something that should look good on
- // first launch. We don't provide a position to let Electron center the app.
return { width: 1170, height: 710 };
};
-/**
- * If for some reason {@link windowBounds} is outside the screen's bounds (e.g.
- * if the user's screen resolution has changed), then the previously saved
- * bounds might not be appropriate.
- *
- * Luckily, if we try to set an x/y position that is outside the screen's
- * bounds, then Electron automatically clamps x + width and y + height to lie
- * within the screen's available space, and we do not need to tackle such out of
- * bounds cases specifically.
- *
- * However there is no minimum window size the Electron enforces by default. As
- * a safety valve, provide an (arbitrary) minimum size so that the user can
- * resize it back to sanity if something I cannot currently anticipate happens.
- */
const minimumWindowSize = () => ({ minWidth: 200, minHeight: 200 });
-/**
- * Sibling of {@link windowBounds}, see that function's documentation for more
- * details.
- */
const saveWindowBounds = (window: BrowserWindow) => {
if (window.isMaximized()) {
userPreferences.set("isWindowMaximized", true);
@@ -482,10 +246,6 @@ const saveWindowBounds = (window: BrowserWindow) => {
}
};
-/**
- * Automatically set the save path for user initiated downloads to the system's
- * "downloads" directory instead of asking the user to select a save location.
- */
const setDownloadPath = (webContents: WebContents) => {
webContents.session.on("will-download", (_, item) => {
item.setSavePath(
@@ -507,30 +267,9 @@ const uniqueSavePath = (dirPath: string, fileName: string) => {
return savePath;
};
-/**
- * Allow opening external links, e.g. when the user clicks on the "Feature
- * requests" button in the sidebar (to open our GitHub repository), or when they
- * click the "Support" button to send an email to support.
- *
- * Security: Only allow http/https/mailto schemes to be opened externally.
- * Disallow other protocols (e.g. custom OS handlers) to avoid potential RCE
- * vectors on some platforms when delegating to the OS via shell.openExternal.
- *
- * @param webContents The renderer to configure.
- */
const allowExternalLinks = (webContents: WebContents) =>
- // By default, if the user were open a link, say
- // https://github.com/ente/ente/discussions, then it would open a _new_
- // BrowserWindow within our app.
- //
- // This is not the behaviour we want; what we want is to ask the system to
- // handle the link (e.g. open the URL in the default browser, or if it is a
- // mailto: link, then open the user's mail client).
- //
- // Returning `action` "deny" accomplishes this.
webContents.setWindowOpenHandler(({ url }) => {
if (!url.startsWith(rendererURL)) {
- // Only allow http/https/mailto external links for safety.
const isAllowedScheme = (() => {
try {
const u = new URL(url);
@@ -545,10 +284,6 @@ const allowExternalLinks = (webContents: WebContents) =>
})();
if (isAllowedScheme) {
- // This does not work in Ubuntu currently: mailto links seem to just
- // get ignored, and HTTP links open in the text editor instead of in
- // the browser.
- // https://github.com/electron/electron/issues/31485
void shell.openExternal(url);
} else {
log.warn(`Blocked external open for disallowed scheme: ${url}`);
@@ -559,33 +294,14 @@ const allowExternalLinks = (webContents: WebContents) =>
}
});
-/**
- * Handle back button presses on the Stripe checkout page.
- *
- * For payments, we show the Stripe checkout page to the user in the app's
- * window. On this page there is a back button that allows the user to get back
- * to the app's contents. Since we're not showing the browser controls, this is
- * the only way to get back to the app.
- *
- * If the user enters something in the text fields on this page (e.g. if they
- * start entering their credit card number), and then press back, then the
- * browser shows the user a dialog asking them to confirm if they want to
- * discard their unsaved changes. However, when running in the context of an
- * Electron app, this dialog is not shown, and instead the app just gets stuck
- * (the back button stops working, and quitting the app also doesn't work since
- * there is an invisible modal dialog).
- *
- * So we instead intercept these back button presses, and show the same dialog
- * that the browser would've shown.
- */
+// Electron hides Stripe's beforeunload dialog, leaving an invisible modal that
+// wedges navigation and quit. Recreate the browser prompt ourselves.
const handleBackOnStripeCheckout = (window: BrowserWindow) =>
window.webContents.on("will-prevent-unload", (event) => {
const url = new URL(window.webContents.getURL());
- // Only intercept on Stripe checkout pages.
+
if (url.host != "checkout.stripe.com") return;
- // The dialog copy is similar to what Chrome would've shown.
- // https://www.electronjs.org/docs/latest/api/web-contents#event-will-prevent-unload
const choice = dialog.showMessageBoxSync(window, {
type: "question",
buttons: ["Leave", "Stay"],
@@ -598,53 +314,8 @@ const handleBackOnStripeCheckout = (window: BrowserWindow) =>
if (leave) event.preventDefault();
});
-/**
- * Allow uploads to arbitrary S3 buckets.
- *
- * The embedded web app within in the desktop app is served over the ente://
- * protocol. When pages in that web app make requests, their originate from this
- * "ente://app" origin, which thus serves as the value for the
- * "Access-Control-Allow-Origin" header in the CORS preflight requests.
- *
- * Some S3 providers (B2 is the motivating example for this workaround) do not
- * allow whitelisting custom URI schemes. That is, even if we set
- * "`allowedOrigin: ["*"]` in our B2 bucket CORS configuration, when the web
- * code makes a CORS request with ACAO "ente://app", it gets back
- * "Access-Control-Allow-Origin" set to `null` in the response, and thus the
- * request fails (since it does not match the origin we sent).
- *
- * This is not an issue for production apps since they fetches or uploads via a
- * worker instead of directly touching an S3 provider.
- *
- * This is not also an issue for fetches in the self hosted apps since those
- * involve a redirection, and during a redirection Chromium sets the ACAO in the
- * request to `null` (this is the correct behaviour as per the spec, for more
- * details See: [Note: Passing credentials for self-hosted file fetches]).
- *
- * But this is an issue for uploads in the self hosted apps (or when we
- * ourselves are trying to test things by with an arbitrary S3 bucket without
- * going via a worker). During upload, there is no redirection, so the request
- * ACAO is "ente://app" but the response ACAO is `null` which don't match,
- * causing the request to fail.
- *
- * As a workaround, we intercept the ACAO header and set it to `*`.
- *
- * However, an unconditional interception causes problems with requests that use
- * credentials, since "*" is not a valid value in such cases. One such example
- * is the HCaptcha requests made by Stripe when we initiate a payment within the
- * desktop app:
- *
- * > Access to XMLHttpRequest at 'https://api2.hcaptcha.com/getcaptcha/xxx' from
- * > origin 'https://newassets.hcaptcha.com' has been blocked by CORS policy:
- * > The value of the 'Access-Control-Allow-Origin' header in the response must
- * > not be the wildcard '*' when the request's credentials mode is 'include'.
- * > The credentials mode of requests initiated by the XMLHttpRequest is
- * > controlled by the withCredentials attribute.
- *
- * So we only do this workaround if there was either no ACAO specified in the
- * response, or if the ACAO in the response was "null" (the string serialization
- * of `null`).
- */
+// B2 answers ente://app uploads with Access-Control-Allow-Origin: null. Rewrite
+// missing/null values only; wildcards break Stripe hCaptcha's credentialed calls.
const allowAllCORSOrigins = (webContents: WebContents) =>
webContents.session.webRequest.onHeadersReceived(
({ responseHeaders }, callback) => {
@@ -663,14 +334,7 @@ const allowAllCORSOrigins = (webContents: WebContents) =>
},
);
-/**
- * OSM services expect requests to identify the originating app. Our desktop
- * renderer is served from the custom "ente://app" origin, so requests from the
- * Electron session do not naturally carry an app-specific browser identity.
- *
- * Prefix OSM requests with a truthful desktop app User-Agent token instead of
- * forging a web Referer. This applies to both map tiles and Nominatim lookups.
- */
+// OSM requires application identification; custom-scheme requests lack one.
const allowOpenStreetMapRequestIdentification = (webContents: WebContents) =>
webContents.session.webRequest.onBeforeSendHeaders(
{
@@ -701,20 +365,7 @@ const openStreetMapUserAgent = (existingUserAgent: string | undefined) => {
: appIdentifier;
};
-/**
- * Add an icon for our app in the system tray.
- *
- * For example, these are the small icons that appear on the top right of the
- * screen in the main menu bar on macOS.
- */
const setupTrayItem = (mainWindow: BrowserWindow) => {
- // There are a total of 6 files corresponding to this tray icon.
- //
- // On macOS, use template images (filename needs to end with "Template.ext")
- // https://www.electronjs.org/docs/latest/api/native-image#template-image-macos
- //
- // And for each (template or otherwise), there are 3 "retina" variants
- // https://www.electronjs.org/docs/latest/api/native-image#high-resolution-image
const iconName =
process.platform == "darwin"
? "taskbar-icon-Template.png"
@@ -738,5 +389,4 @@ const setupTrayItem = (mainWindow: BrowserWindow) => {
}
};
-// Go for it.
main();
diff --git a/desktop/src/main/ipc.ts b/desktop/src/main/ipc.ts
index 4ca1e128e1..fb912df295 100644
--- a/desktop/src/main/ipc.ts
+++ b/desktop/src/main/ipc.ts
@@ -1,13 +1,3 @@
-/**
- * @file Listen for IPC events sent/invoked by the renderer process, and route
- * them to their correct handlers.
- *
- * This file is meant as a sibling to `preload.ts`, but this one runs in the
- * context of the main process, and can import other files from `src/`.
- *
- * See [Note: types.ts <-> preload.ts <-> ipc.ts]
- */
-
import type { FSWatcher } from "chokidar";
import type { BrowserWindow, IpcMainEvent, IpcMainInvokeEvent } from "electron";
import { ipcMain, safeStorage } from "electron/main";
@@ -108,14 +98,8 @@ const parsePersistedAppLockConfig = (
const rendererOrigin = "ente://app";
-/**
- * Guard against IPC from anything other than our own renderer.
- *
- * The preload script exposes the {@link Electron} object to whatever document
- * is loaded in the main window, including any external page (e.g. the Stripe
- * checkout) the window navigates to. Ensure that the frame invoking us is
- * actually our renderer before running the privileged handler.
- */
+// The preload bridge remains exposed while the window visits Stripe, so every
+// privileged handler must verify that its caller is our renderer.
const ensureTrustedIPCSender = (
channel: string,
event: IpcMainEvent | IpcMainInvokeEvent,
@@ -128,11 +112,6 @@ const ensureTrustedIPCSender = (
return false;
};
-/**
- * A variant of {@link ipcMain.handle} that ignores requests from untrusted
- * senders. See {@link ensureTrustedIPCSender}.
- */
-// The type parameters preserve each handler's specific argument types.
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
const handle = <A extends unknown[], R>(
channel: string,
@@ -144,10 +123,6 @@ const handle = <A extends unknown[], R>(
return handler(event, ...args);
});
-/**
- * A variant of {@link ipcMain.on} that ignores requests from untrusted senders.
- * See {@link ensureTrustedIPCSender}.
- */
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
const on = <A extends unknown[]>(
channel: string,
@@ -157,36 +132,13 @@ const on = <A extends unknown[]>(
if (ensureTrustedIPCSender(channel, event)) handler(event, ...args);
});
-/**
- * Listen for IPC events sent/invoked by the renderer process, and route them to
- * their correct handlers.
- */
export const attachIPCHandlers = () => {
- // Notes:
- //
- // The first parameter of the handler passed to `ipcMain.handle` is the
- // `event`, and is usually ignored. The rest of the parameters are the
- // arguments passed to `ipcRenderer.invoke`.
- //
- // [Note: Catching exception during .send/.on]
- //
- // While we can use ipcRenderer.send/ipcMain.on for one-way communication,
- // that has the disadvantage that any exceptions thrown in the processing of
- // the handler are not sent back to the renderer. So we use the
- // ipcRenderer.invoke/ipcMain.handle 2-way pattern even for things that are
- // conceptually one way. An exception (pun intended) to this is logToDisk,
- // which is a primitive, frequently used, operation and shouldn't throw, so
- // having its signature by synchronous is a bit convenient.
-
- // - General
-
handle("appVersion", () => appVersion());
handle("openDirectory", (_, dirPath: string) => openDirectory(dirPath));
handle("openLogDirectory", () => openLogDirectory());
- // See [Note: Catching exception during .send/.on]
on("logToDisk", (_, message: string) => logToDisk(message));
handle("selectDirectory", () => selectDirectory());
@@ -223,24 +175,12 @@ export const attachIPCHandlers = () => {
handle("toggleAutoLaunch", () => autoLauncher.toggleAutoLaunch());
- // - Desktop app lock (native device authentication)
- //
- // These handlers are the main-process bridge for the desktop app lock flow:
- // the renderer asks about native auth capability/support, then requests a
- // native unlock prompt when the user needs to unlock the app.
-
- // Returns richer capability details (for example, available prompt type)
- // so the UI can decide which app-lock option to show.
handle("getNativeDeviceLockCapability", () =>
getNativeDeviceLockCapability(),
);
- // Triggers the macOS-native Touch ID prompt and returns the auth result
- // back to the renderer. Other platforms currently return false.
handle("promptDeviceLock", (_, reason: string) => promptDeviceLock(reason));
- // - App update
-
on("updateAndRestart", () => updateAndRestart());
on("updateOnNextRestart", (_, version: string) =>
@@ -249,8 +189,6 @@ export const attachIPCHandlers = () => {
on("skipAppUpdate", (_, version: string) => skipAppUpdate(version));
- // - FS
-
handle("fsExists", (_, path: string) => fsExists(path));
handle("fsRename", (_, oldPath: string, newPath: string) =>
@@ -279,8 +217,6 @@ export const attachIPCHandlers = () => {
handle("fsFindFiles", (_, folderPath: string) => fsFindFiles(folderPath));
- // - Conversion
-
handle("convertToJPEG", (_, imageData: Uint8Array) =>
convertToJPEG(imageData),
);
@@ -311,8 +247,6 @@ export const attachIPCHandlers = () => {
ffmpegDetermineVideoDuration(pathOrZipItem),
);
- // - Upload
-
handle("listZipItems", (_, zipPath: string) => listZipItems(zipPath));
handle("pathOrZipItemSize", (_, pathOrZipItem: string | ZipItem) =>
@@ -340,28 +274,13 @@ export const attachIPCHandlers = () => {
handle("clearPendingUploads", () => clearPendingUploads());
};
-/**
- * A subset of {@link attachIPCHandlers} for functions that need a reference to
- * the main window to do their thing.
- */
export const attachMainWindowIPCHandlers = (mainWindow: BrowserWindow) => {
- // - Utility processes
-
on("triggerCreateUtilityProcess", (_, type: UtilityProcessType) =>
triggerCreateUtilityProcess(type, mainWindow),
);
};
-/**
- * Sibling of {@link attachIPCHandlers} that attaches handlers specific to the
- * watch folder functionality.
- *
- * It gets passed a {@link FSWatcher} instance which it can then forward to the
- * actual handlers if they need access to it to do their thing.
- */
export const attachFSWatchIPCHandlers = (watcher: FSWatcher) => {
- // - Watch
-
handle("watchGet", () => watchGet(watcher));
handle(
@@ -387,10 +306,6 @@ export const attachFSWatchIPCHandlers = (watcher: FSWatcher) => {
);
};
-/**
- * Sibling of {@link attachIPCHandlers} specifically for use with the logout
- * event with needs access to the {@link FSWatcher} instance.
- */
export const attachLogoutIPCHandler = (watcher: FSWatcher) => {
handle("logout", () => logout(watcher));
};
diff --git a/desktop/src/main/log-worker.ts b/desktop/src/main/log-worker.ts
index 7f0eb7a066..6512ebd9e9 100644
--- a/desktop/src/main/log-worker.ts
+++ b/desktop/src/main/log-worker.ts
@@ -1,56 +1,24 @@
-/**
- * A object that behaves similar to the default export of "./log", except this
- * can be used from within a utility process.
- *
- * ---
- *
- * We cannot directly do
- *
- * import log from "../log";
- *
- * because that requires the Electron APIs that are not available to a utility
- * process (See: [Note: Using Electron APIs in UtilityProcess]).
- *
- * But even if that were to work, logging will still be problematic since we'd
- * try opening the log file from two different Node.js processes (this one, and
- * the main one), and I didn't find any indication in the electron-log
- * repository that the log file's integrity would be maintained in such cases.
- *
- * So instead we provide this proxy log object that uses the
- * `process.parentPort` to transport the logs over to the main process, where
- * the {@link processUtilityProcessLogMessage} function in the main process is
- * expected to handle these (sending them to the actual log).
- */
+// Utility processes cannot use Electron's logger or safely share its log file;
+// proxy their records to the main process.
export default {
error: (s: string, e?: unknown) =>
mainProcess("log.errorString", messageWithError(s, e)),
warn: (s: string, e?: unknown) =>
mainProcess("log.warnString", messageWithError(s, e)),
info: (...ms: unknown[]) => mainProcess("log.info", ms),
- /**
- * Unlike the real {@link log.debug}, this is (a) eagerly evaluated, and (b)
- * accepts only strings.
- */
debugString: (s: string) => mainProcess("log.debugString", s),
};
-/**
- * Send a message to the main process using a barebones RPC protocol.
- */
const mainProcess = (method: string, param: unknown) =>
process.parentPort.postMessage({ method, p: param });
-// Duplicated verbatim from ./log.ts
const messageWithError = (message: string, e?: unknown) => {
if (!e) return message;
let es: string;
if (e instanceof Error) {
- // In practice, we expect ourselves to be called with Error objects, so
- // this is the happy path so to say.
es = [`${e.name}: ${e.message}`, e.stack].filter((x) => x).join("\n");
} else {
- // For the rest rare cases, use the default string serialization of e.
// eslint-disable-next-line @typescript-eslint/no-base-to-string
es = String(e);
}
diff --git a/desktop/src/main/log.ts b/desktop/src/main/log.ts
index 5e165da0fd..b296213d07 100644
--- a/desktop/src/main/log.ts
+++ b/desktop/src/main/log.ts
@@ -2,38 +2,22 @@ import log from "electron-log";
import util from "node:util";
import { isDev } from "./utils/electron";
-/**
- * Initialize logging in the main process.
- *
- * This will set our underlying logger up to log to a file named `ente.log`, see
- * [Note: App log path].
- *
- * On dev builds, it will also log to the console.
- */
export const initLogging = () => {
log.transports.file.fileName = "ente.log";
- log.transports.file.maxSize = 50 * 1024 * 1024; // 50 MB
+ log.transports.file.maxSize = 50 * 1024 * 1024;
log.transports.file.format = "[{y}-{m}-{d}T{h}:{i}:{s}{z}] {text}";
log.transports.console.level = false;
- // Log unhandled errors and promise rejections.
log.errorHandler.startCatching({
onError: ({ error, errorName }) => {
logError(errorName, error);
- // Prevent the default electron-log actions (e.g. showing a dialog)
- // from getting triggered.
+ // Suppress electron-log's default dialog.
return false;
},
});
};
-/**
- * Write a {@link message} to the on-disk log.
- *
- * This is used by the renderer process (via the contextBridge) to add entries
- * in the log that is saved on disk.
- */
export const logToDisk = (message: string) => {
log.info(`[rndr] ${message}`);
};
@@ -43,11 +27,8 @@ const messageWithError = (message: string, e?: unknown) => {
let es: string;
if (e instanceof Error) {
- // In practice, we expect ourselves to be called with Error objects, so
- // this is the happy path so to say.
es = [`${e.name}: ${e.message}`, e.stack].filter((x) => x).join("\n");
} else {
- // For the rest rare cases, use the default string serialization of e.
// eslint-disable-next-line @typescript-eslint/no-base-to-string
es = String(e);
}
@@ -83,21 +64,11 @@ const logDebug = (param: () => unknown) => {
}
};
-/**
- * Handle log messages posted from the utility process in the main process.
- *
- * See: [Note: Using Electron APIs in UtilityProcess]
- *
- * @param message The arbitrary message that was received as an argument to the
- * "message" event invoked on a {@link UtilityProcess}.
- *
- * @returns true if the message was recognized and handled, and false otherwise.
- */
export const processUtilityProcessLogMessage = (
logTag: string,
message: unknown,
) => {
- const m = message; /* shorter alias */
+ const m = message;
if (m && typeof m == "object" && "method" in m && "p" in m) {
const p = m.p;
switch (m.method) {
@@ -115,7 +86,6 @@ export const processUtilityProcessLogMessage = (
break;
case "log.info":
if (Array.isArray(p)) {
- // Need to cast from any[] to unknown[]
logInfo(logTag, ...(p as unknown[]));
return true;
}
@@ -133,53 +103,9 @@ export const processUtilityProcessLogMessage = (
return false;
};
-/**
- * Ente's logger.
- *
- * This is an object that provides three functions to log at the corresponding
- * levels - error, info or debug.
- *
- * {@link initLogging} needs to be called once before using any of these.
- */
export default {
- /**
- * Log an error message with an optional associated error object.
- *
- * {@link e} is generally expected to be an `instanceof Error` but it can be
- * any arbitrary object that we obtain, say, when in a try-catch handler (in
- * JavaScript any arbitrary value can be thrown).
- *
- * The log is written to disk and printed to the main (Node.js) process's
- * console.
- */
error: logError,
- /**
- * Sibling of {@link error}, with the same parameters and behaviour, except
- * it gets prefixed with a warning instead of an error tag.
- */
warn: logWarn,
- /**
- * Log a message.
- *
- * This is meant as a replacement of {@link console.log}, and takes an
- * arbitrary number of arbitrary parameters that it then serializes.
- *
- * The log is written to disk. In development builds, the log is also
- * printed to the main (Node.js) process console.
- */
info: logInfo,
- /**
- * Log a debug message.
- *
- * To avoid running unnecessary code in release builds, this takes a
- * function to call to get the log message instead of directly taking the
- * message. The provided function will only be called in development builds.
- *
- * The function can return an arbitrary value which is serialized before
- * being logged.
- *
- * This log is NOT written to disk. It is printed to the main (Node.js)
- * process console, but only on development builds.
- */
debug: logDebug,
};
diff --git a/desktop/src/main/menu.ts b/desktop/src/main/menu.ts
index e7012248cc..9d55167b56 100644
--- a/desktop/src/main/menu.ts
+++ b/desktop/src/main/menu.ts
@@ -9,12 +9,7 @@ import { allowWindowClose } from "../main";
import { forceCheckForAppUpdates } from "./services/app-update";
import { setShouldHideDockIcon, shouldHideDockIcon } from "./services/store";
-/** Create and return the entries in the app's main menu bar */
export const createApplicationMenu = (mainWindow: BrowserWindow) => {
- // The state of checkboxes
- //
- // Whenever the menu is redrawn the current value of these variables is used
- // to set the checked state for the various settings checkboxes.
let hideDockIcon = shouldHideDockIcon();
const macOSOnly = (options: MenuItemConstructorOptions[]) =>
@@ -23,9 +18,7 @@ export const createApplicationMenu = (mainWindow: BrowserWindow) => {
const handleCheckForUpdates = () => forceCheckForAppUpdates(mainWindow);
const toggleHideDockIcon = () => {
- // Persist
setShouldHideDockIcon(!hideDockIcon);
- // And update the in-memory state
hideDockIcon = !hideDockIcon;
};
@@ -113,10 +106,6 @@ export const createApplicationMenu = (mainWindow: BrowserWindow) => {
]);
};
-/**
- * Create and return a {@link Menu} that is shown when the user clicks on our
- * system tray icon (e.g. the icon list at the top right of the screen on macOS)
- */
export const createTrayContextMenu = (mainWindow: BrowserWindow) => {
const handleOpen = () => {
mainWindow.show();
diff --git a/desktop/src/main/stores/upload-status.ts b/desktop/src/main/stores/upload-status.ts
index 76fa0ba273..6c930977ec 100644
--- a/desktop/src/main/stores/upload-status.ts
+++ b/desktop/src/main/stores/upload-status.ts
@@ -2,32 +2,13 @@ import Store, { Schema } from "electron-store";
import type { PreUploadSkippedFile, ZipItem } from "../../types/ipc";
export interface UploadStatusStore {
- /**
- * The collection to which we're uploading, or the root collection.
- *
- * Not all pending uploads will have an associated collection.
- */
collectionName?: string;
- /**
- * Paths to regular files that are pending upload.
- */
filePaths?: string[];
- /**
- * Each item is the path to a zip file and the name of an entry within it.
- */
zipItems?: ZipItem[];
- /**
- * @deprecated Legacy paths to zip files, now subsumed into zipItems.
- */
+ /** @deprecated Legacy paths to zip files, now subsumed into zipItems. */
zipPaths?: string[];
- /**
- * Files that were skipped because either we could not open them (zip files)
- * or they are hidden dot files.
- */
preUploadSkippedFiles?: PreUploadSkippedFile[];
- /** Whether Takeout-favorited uploads should be added to Favorites. */
importTakeoutFavorites?: boolean;
- /** Whether media originating from Google Photos partner sharing is uploaded. */
includePartnerSharedFiles?: boolean;
}
diff --git a/desktop/src/main/stores/user-preferences.ts b/desktop/src/main/stores/user-preferences.ts
index 12d529c395..49536a7d1f 100644
--- a/desktop/src/main/stores/user-preferences.ts
+++ b/desktop/src/main/stores/user-preferences.ts
@@ -1,32 +1,11 @@
import Store, { Schema } from "electron-store";
interface UserPreferences {
- /**
- * If true, then the user has set a preference to also hide the dock icon on
- * macOS when the window is closed using the x traffic light. The tray icon
- * remains visible and can then be used to reopen the app when needed.
- */
hideDockIcon?: boolean;
skipAppVersion?: string;
muteUpdateNotificationVersion?: string;
- /**
- * The changelog version for which we last showed the "What's new" screen.
- *
- * See: [Note: Conditions for showing "What's new"]
- */
lastShownChangelogVersion?: number;
- /**
- * The last position and size of our app's window.
- *
- * This value is saved when the app is about to quit, and is used to restore
- * the window to the previous state when it restarts. It is only saved if
- * the app is not maximized (when the app was maximized when it was being
- * quit then {@link isWindowMaximized} will be set instead).
- */
windowBounds?: { x: number; y: number; width: number; height: number };
- /**
- * `true` if the app's main window is maximized the last time it was closed.
- */
isWindowMaximized?: boolean;
}
diff --git a/desktop/src/main/stream.ts b/desktop/src/main/stream.ts
index 263755a92a..e092c7b982 100644
--- a/desktop/src/main/stream.ts
+++ b/desktop/src/main/stream.ts
@@ -1,6 +1,3 @@
-/**
- * @file stream data to-from renderer using a custom protocol handler.
- */
import { net, protocol, type BrowserWindow } from "electron/main";
import { randomUUID } from "node:crypto";
import fs from "node:fs/promises";
@@ -18,28 +15,7 @@ import {
makeTempFilePath,
} from "./utils/temp";
-/**
- * Register a protocol handler that we use for streaming large files between the
- * main (Node.js) and renderer (Chromium) processes.
- *
- * [Note: IPC streams]
- *
- * When running without node integration, there is no direct way to pass streams
- * across IPC. And passing the entire contents of the file is not feasible for
- * large video files because of the memory pressure the copying would entail.
- *
- * As an alternative, we register a custom protocol handler that can provides a
- * bi-directional stream. The renderer can stream data to the node side by
- * streaming the request. The node side can stream to the renderer side by
- * streaming the response.
- *
- * The stream is not full duplex - while both reads and writes can be streamed,
- * they need to be streamed separately.
- *
- * See also: [Note: Transferring large amount of data over IPC]
- *
- * Depends on {@link registerPrivilegedSchemes}.
- */
+// This protocol avoids contextBridge's buffer copies for large files.
export const registerStreamProtocol = (mainWindow: BrowserWindow) => {
protocol.handle("stream", (request: Request) => {
try {
@@ -57,10 +33,8 @@ const handleStreamRequest = async (
mainWindow: BrowserWindow,
request: Request,
): Promise<Response> => {
- // Electron strips Origin/Referer from custom-scheme requests, so we cannot
- // identify the caller from the request itself. Instead gate on the main
- // window's current URL: only honor stream requests while our own renderer
- // (and not, say, a payment page it navigated to) is the loaded document.
+ // Custom-scheme requests omit Origin and Referer, so gate them by the
+ // document loaded in the app's only window.
const windowURL = mainWindow.webContents.getURL();
if (
windowURL != rendererOrigin &&
@@ -69,8 +43,7 @@ const handleStreamRequest = async (
return new Response("", { status: 403 });
const url = request.url;
- // The request URL contains the command to run as the host, and the
- // pathname of the file(s) as the search params.
+
const { host, searchParams } = new URL(url);
switch (host) {
case "read":
@@ -117,26 +90,11 @@ const handleStreamRequest = async (
const handleRead = async (path: string) => {
const res = await net.fetch(pathToFileURL(path).toString());
if (res.ok) {
- // net.fetch already seems to add "Content-Type" and "Last-Modified"
- // headers, but I couldn't find documentation for this. In any case,
- // since we already are stat-ting the file for the "Content-Length", we
- // explicitly add the "X-Last-Modified-Ms" too,
- //
- // 1. Guaranteeing its presence,
- //
- // 2. Having it be in the exact format we want (no string <-> date
- // conversions),
- //
- // 3. Retaining milliseconds.
-
const stat = await fs.stat(path);
- // Add the file's size as the Content-Length header.
const fileSize = stat.size;
res.headers.set("Content-Length", `${fileSize}`);
- // Add the file's last modified time (as epoch milliseconds).
- // See: [Note: Integral last modified time]
const mtimeMs = stat.mtime.getTime();
res.headers.set("X-Last-Modified-Ms", `${mtimeMs}`);
}
@@ -151,25 +109,16 @@ const handleReadZip = async (zipPath: string, entryName: string) => {
return new Response("", { status: 404 });
}
- // zip.stream returns an "old style" NodeJS.ReadableStream. We then write it
- // to the writable end of the web stream pipe, the readable end of which is
- // relayed back to the renderer as the response.
const { writable, readable } = new TransformStream();
const stream = await zip.stream(entry);
- // Silence a type error about the Promise<void> returned by the close method
- // of writable as not being assignable to Promise<undefined> which started
- // appearing after updating to TypeScript 5.8.
- //
+ // Node and DOM disagree about WritableStream.close's Promise return.
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
const nodeWritable = Writable.fromWeb(writable as any);
stream.pipe(nodeWritable);
nodeWritable.on("error", (e: unknown) => {
- // If the renderer process closes the network connection (say when it
- // only needs the content-length and doesn't care about the body), we
- // get an AbortError. Handle them here otherwise they litter the logs
- // with unhandled exceptions.
+ // Closing the response body early aborts the writable side.
if (e instanceof Error && e.name == "AbortError") return;
log.error("Error event for the writable end of zip stream", e);
});
@@ -178,18 +127,11 @@ const handleReadZip = async (zipPath: string, entryName: string) => {
markClosableZip(zipPath);
});
- // While it is documented that entry.time is the modification time,
- // the units are not mentioned. By seeing the source code, we can
- // verify that it is indeed epoch milliseconds. See `parseZipTime`
- // in the node-stream-zip source,
- // https://github.com/antelle/node-stream-zip/blob/master/node_stream_zip.js
+ // node-stream-zip's parseZipTime returns epoch milliseconds.
const modifiedMs = entry.time;
return new Response(readable, {
headers: {
- // We don't know the exact type, but it doesn't really matter, just
- // set it to a generic binary content-type so that the browser
- // doesn't tinker with it thinking of it as text.
"Content-Type": "application/octet-stream",
"Content-Length": `${entry.size}`,
"X-Last-Modified-Ms": `${modifiedMs}`,
@@ -202,48 +144,12 @@ const handleWrite = async (path: string, request: Request) => {
return new Response("", { status: 200 });
};
-/**
- * A map from token to file paths generated as a result of stream://video
- * requests we have received.
- */
+// Chromium cannot stream both halves of one fetch. Video operations return a
+// token for a second read request; a final done request releases the temp file.
const pendingVideoResults = new Map<string, string>();
-/**
- * Clear any in-memory state for in-flight streamed video processing requests.
- * Meant to be called during logout.
- */
export const clearPendingVideoResults = () => pendingVideoResults.clear();
-/**
- * [Note: Convert to MP4]
- *
- * When we want to convert a video to MP4, if we were to send the entire
- * contents of the video from the renderer to the main process over IPC, it just
- * causes the renderer to run out of memory and restart when the videos are very
- * large. So we need to stream the original video renderer β†’ main and then
- * stream back the converted video renderer ← main.
- *
- * Currently Chromium does not support bi-directional streaming ("full" duplex
- * mode for the Web fetch API). So we need to simulate that using two different
- * streaming requests.
- *
- * renderer β†’ main stream://video?op=convert-to-mp4
- * β†’ request.body is the original video
- * ← response is [token]
- *
- * renderer β†’ main stream://video?token=<token>
- * ← response.body is the converted video
- *
- * renderer β†’ main stream://video?token=<token>&done
- * ← 200 OK
- *
- * Note that the conversion itself is not streaming. The conversion still
- * happens in a single invocation of ffmpeg, we are just streaming the data
- * across the IPC boundary to allow us to pass large amounts of data without
- * running out of memory.
- *
- * See also: [Note: IPC streams]
- */
const handleConvertToMP4Write = async (request: Request) => {
const worker = await ffmpegUtilityProcess();
@@ -285,22 +191,6 @@ const handleVideoDone = async (token: string) => {
return new Response("", { status: 200 });
};
-/**
- * Generate a HLS playlist for the given video.
- *
- * See: [Note: Convert to MP4] for the general architecture of commands that do
- * renderer <-> main I/O using streams.
- *
- * The difference here is that we the conversion generates two streams^ - one
- * for the HLS playlist itself, and one for the file containing the encrypted
- * and transcoded video chunks. The video stream we write to the pre-signed
- * object upload URL(s), and then we return a JSON object containing the token
- * for the playlist, and other metadata for use by the renderer.
- *
- * ^ if the video doesn't require a stream to be generated (e.g. it is very
- * small and already uses a compatible codec) then a HTT 204 is returned and
- * no stream is generated.
- */
const handleGenerateHLSWrite = async (
request: Request,
params: URLSearchParams,
@@ -348,7 +238,6 @@ const handleGenerateHLSWrite = async (
);
if (!result) {
- // This video doesn't require stream generation.
return new Response(null, { status: 204 });
}
diff --git a/desktop/src/main/types/any-shell-escape.d.ts b/desktop/src/main/types/any-shell-escape.d.ts
index c5fef6fb96..d6397f7aa7 100644
--- a/desktop/src/main/types/any-shell-escape.d.ts
+++ b/desktop/src/main/types/any-shell-escape.d.ts
@@ -1,24 +1,3 @@
-/**
- * Escape and stringify an array of arguments to be executed on the shell.
- *
- * @example
- *
- * const shellescape = require('any-shell-escape');
- *
- * const args = ['curl', '-v', '-H', 'Location;', '-H', "User-Agent: FooBar's so-called \"Browser\"", 'http://www.daveeddy.com/?name=dave&age=24'];
- *
- * const escaped = shellescape(args);
- * console.log(escaped);
- *
- * yields (on POSIX shells):
- *
- * curl -v -H 'Location;' -H 'User-Agent: FooBar'"'"'s so-called "Browser"' 'http://www.daveeddy.com/?name=dave&age=24'
- *
- * or (on Windows):
- *
- * curl -v -H "Location;" -H "User-Agent: FooBar's so-called ""Browser""" "http://www.daveeddy.com/?name=dave&age=24"
-Which is suitable for being executed by the shell.
- */
declare module "any-shell-escape" {
declare const shellescape: (args: readonly string | string[]) => string;
export default shellescape;
diff --git a/desktop/src/main/utils/comlink.ts b/desktop/src/main/utils/comlink.ts
index f0edd758af..80a83cce16 100644
--- a/desktop/src/main/utils/comlink.ts
+++ b/desktop/src/main/utils/comlink.ts
@@ -1,18 +1,8 @@
import type { Endpoint } from "comlink";
import type { MessagePortMain } from "electron";
-/**
- * An adaptation of the `nodeEndpoint` function from comlink suitable for use in
- * TypeScript with an Electron utility process.
- *
- * This is an adaption of the following function from comlink:
- * https://github.com/GoogleChromeLabs/comlink/blob/main/src/node-adapter.ts
- *
- * It has been modified (somewhat hackily) to be useful with an Electron
- * MessagePortMain instead of a Node.js worker_thread. Only things that we
- * currently need have been made to work as you can see by the abundant type
- * casts. Caveat emptor.
- */
+// Adapted from Comlink's nodeEndpoint for Electron's MessagePortMain:
+// https://github.com/GoogleChromeLabs/comlink/blob/main/src/node-adapter.ts
export const messagePortMainEndpoint = (mp: MessagePortMain): Endpoint => {
type NL = EventListenerOrEventListenerObject;
type EL = (data: Electron.MessageEvent) => void;
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index 308d172e9c..ce10b6b3a8 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -1,67 +1,10 @@
-/**
- * @file The preload script
- *
- * The preload script runs in a renderer process before its web contents begin
- * loading. During their execution they have access to a subset of Node.js APIs
- * and imports. Its purpose is to expose the relevant imports and other
- * functions as an object on the DOM, so that the renderer process can invoke
- * functions that live in the main (Node.js) process if needed.
- *
- * Ref: https://www.electronjs.org/docs/latest/tutorial/tutorial-preload
- *
- * Note that this script cannot import other code from `src/` - conceptually it
- * can be thought of as running in a separate, third, process different from
- * both the main or a renderer process (technically, it runs in a BrowserWindow
- * context that runs prior to the renderer process).
- *
- * > Since enabling the sandbox disables Node.js integration in your preload
- * > scripts, you can no longer use require("../my-script"). In other words,
- * > your preload script needs to be a single file.
- * >
- * > https://www.electronjs.org/blog/breach-to-barrier
- *
- * If we really wanted, we could setup a bundler to package this into a single
- * file. However, since this is just boilerplate code providing a bridge between
- * the main and renderer, we avoid introducing another moving part into the mix
- * and just keep the entire preload setup in this single file.
- *
- * [Note: types.ts <-> preload.ts <-> ipc.ts]
- *
- * The following three files are boilerplatish linkage of the same functions,
- * and when changing one of them, remember to see if the other two also need
- * changing:
- *
- * - [renderer] web/packages/base/types/ipc.ts contains docs
- * - [preload] desktop/src/preload.ts β†•οΈŽ
- * - [main] desktop/src/main/ipc.ts contains impl
- */
-
-// This code runs in the (isolated) web layer. Contrary to the impression given
-// by the Electron docs (as of 2024), the window object is actually available to
-// the preload script, and it is necessary for legitimate uses too.
-//
-// > The isolated world is connected to the DOM just the same is the main world,
-// > it is just the JS contexts that are separated.
-// >
-// > https://github.com/electron/electron/issues/27024#issuecomment-745618327
-//
-// Adding this reference here tells TypeScript that DOM typings (in particular,
-// window) should be introduced in the ambient scope.
-//
-// [Note: Node and web stream type mismatch]
-//
-// Unfortunately, adding this reference causes the ReadableStream typings to
-// break since lib.dom.d.ts adds its own incompatible definitions of
-// ReadableStream to the global scope.
-//
-// https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/68407
-
+// Sandboxed preload scripts cannot import runtime code from src, so this file
+// must remain self-contained. DOM types expose window here but conflict with
+// Node's ReadableStream types; see main/utils/stream.ts.
/// <reference lib="dom" />
import { contextBridge, ipcRenderer, webUtils } from "electron/renderer";
-// While we can't import other code, we can import types since they're just
-// needed when compiling and will not be needed or looked around for at runtime.
import type { IpcRendererEvent } from "electron";
import type {
AppUpdate,
@@ -75,21 +18,10 @@ import type {
ZipItem,
} from "./types/ipc";
-// - Infrastructure
-
-// We need to wait until the renderer is ready before sending ports via
-// postMessage, and this promise comes handy in such cases. We create the
-// promise at the top level so that it is guaranteed to be registered before the
-// load event is fired.
-//
-// See: https://www.electronjs.org/docs/latest/tutorial/message-ports
-
const windowLoaded = new Promise((resolve) => {
window.onload = resolve;
});
-// - General
-
const appVersion = () => ipcRenderer.invoke("appVersion");
const logToDisk = (message: string): void =>
@@ -102,9 +34,6 @@ const openLogDirectory = () => ipcRenderer.invoke("openLogDirectory");
const selectDirectory = () => ipcRenderer.invoke("selectDirectory");
-// The path that we get back from `webUtils.getPathForFile` on Windows uses "\"
-// as the path separator. Convert them to POSIX separators.
-
const pathForFile =
process.platform == "win32"
? (file: File) => webUtils.getPathForFile(file).replace(/\\/g, "/")
@@ -179,8 +108,6 @@ const onOpenEnteURL = (cb: ((url: string) => void) | undefined) => {
if (cb) ipcRenderer.on("openEnteURL", (_, url: string) => cb(url));
};
-// - App update
-
const onAppUpdateAvailable = (
cb: ((update: AppUpdate) => void) | undefined,
) => {
@@ -201,8 +128,6 @@ const skipAppUpdate = (version: string) => {
ipcRenderer.send("skipAppUpdate", version);
};
-// - FS
-
const fsExists = (path: string) => ipcRenderer.invoke("fsExists", path);
const fsMkdirIfNeeded = (dirPath: string) =>
@@ -228,8 +153,6 @@ const fsIsDir = (dirPath: string) => ipcRenderer.invoke("fsIsDir", dirPath);
const fsStatMtime = (path: string) => ipcRenderer.invoke("fsStatMtime", path);
-// - Conversion
-
const convertToJPEG = (
imageData: Uint8Array,
): Promise<Uint8Array<ArrayBuffer>> =>
@@ -262,13 +185,10 @@ const ffmpegExec = (
const ffmpegDetermineVideoDuration = (pathOrZipItem: string | ZipItem) =>
ipcRenderer.invoke("ffmpegDetermineVideoDuration", pathOrZipItem);
-// - Utility processes
-
const triggerCreateUtilityProcess = (type: UtilityProcessType) => {
const portEvent = `utilityProcessPort/${type}`;
const l = (event: IpcRendererEvent) => {
void windowLoaded.then(() => {
- // "*"" is the origin to send to.
window.postMessage(portEvent, "*", event.ports);
ipcRenderer.off(portEvent, l);
});
@@ -277,8 +197,6 @@ const triggerCreateUtilityProcess = (type: UtilityProcessType) => {
ipcRenderer.send("triggerCreateUtilityProcess", type);
};
-// - Watch
-
const watchGet = () => ipcRenderer.invoke("watchGet");
const watchAdd = (folderPath: string, collectionMapping: CollectionMapping) =>
@@ -327,8 +245,6 @@ const watchRemoveListeners = () => {
ipcRenderer.removeAllListeners("watchRemoveDir");
};
-// - Upload
-
const listZipItems = (zipPath: string) =>
ipcRenderer.invoke("listZipItems", zipPath);
@@ -348,52 +264,8 @@ const markUploadedZipItem = (item: ZipItem, associatedItem?: ZipItem) =>
const clearPendingUploads = () => ipcRenderer.invoke("clearPendingUploads");
-/**
- * These objects exposed here will become available to the JS code in our
- * renderer (the web/ code) as `window.ElectronAPIs.*`
- *
- * There are a few related concepts at play here, and it might be worthwhile to
- * read their (excellent) documentation to get an understanding;
- *`
- * - ContextIsolation:
- * https://www.electronjs.org/docs/latest/tutorial/context-isolation
- *
- * - IPC https://www.electronjs.org/docs/latest/tutorial/ipc
- *
- * ---
- *
- * [Note: Transferring large amount of data over IPC]
- *
- * Electron's IPC implementation uses the HTML standard Structured Clone
- * Algorithm to serialize objects passed between processes.
- * https://www.electronjs.org/docs/latest/tutorial/ipc#object-serialization
- *
- * In particular, ArrayBuffer is eligible for structured cloning.
- * https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm
- *
- * Also, ArrayBuffer is "transferable", which means it is a zero-copy operation
- * operation when it happens across threads.
- * https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects
- *
- * In our case though, we're not dealing with threads but separate processes.
- * Electron currently only supports transferring MessagePorts:
- * https://github.com/electron/electron/issues/34905
- *
- * So the ArrayBuffer will be copied:
- *
- * > "parameters, errors and return values are **copied** when they're sent over
- * > the bridge".
- * >
- * > https://www.electronjs.org/docs/latest/api/context-bridge#methods
- *
- * The copy itself is relatively fast, but the problem with transferring large
- * amounts of data is potentially running out of memory during the copy.
- *
- * For an alternative, see [Note: IPC streams].
- */
+// contextBridge copies ArrayBuffers between processes; use stream:// for large data.
contextBridge.exposeInMainWorld("electron", {
- // - General
-
appVersion,
logToDisk,
openDirectory,
@@ -417,15 +289,11 @@ contextBridge.exposeInMainWorld("electron", {
onMainWindowBlur,
onOpenEnteURL,
- // - App update
-
onAppUpdateAvailable,
updateAndRestart,
updateOnNextRestart,
skipAppUpdate,
- // - FS
-
fs: {
exists: fsExists,
rename: fsRename,
@@ -440,19 +308,13 @@ contextBridge.exposeInMainWorld("electron", {
findFiles: fsFindFiles,
},
- // - Conversion
-
convertToJPEG,
generateImageThumbnail,
ffmpegExec,
ffmpegDetermineVideoDuration,
- // - ML
-
triggerCreateUtilityProcess,
- // - Watch
-
watch: {
get: watchGet,
add: watchAdd,
@@ -464,8 +326,6 @@ contextBridge.exposeInMainWorld("electron", {
onRemoveDir: watchOnRemoveDir,
},
- // - Upload
-
listZipItems,
pathOrZipItemSize,
pendingUploads,