Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(electron): handle URL download and open custom
Elian Doran21f5246895c9
diff --git a/apps/client/src/services/open.ts b/apps/client/src/services/open.tsindex e8500d6cdb..06944f8057 100644--- a/apps/client/src/services/open.ts+++ b/apps/client/src/services/open.ts@@ -4,7 +4,6 @@ import options from "./options.js";import server from "./server.js";import utils from "./utils.js";-type ExecFunction = (command: string, cb: (err: string, stdout: string, stderror: string) => void) => void;interface TmpResponse {tmpFilePath: string;@@ -29,10 +28,8 @@ function getOpenFileUrl(type: string, noteId: string) {}function download(url: string) {- if (utils.isElectron()) {- const remote = utils.dynamicRequire("@electron/remote");-- remote.getCurrentWebContents().downloadURL(url);+ if (window.electronApi) {+ window.electronApi.shell.downloadURL(url);} else {window.location.href = url;}@@ -60,69 +57,12 @@ function downloadAttachment(attachmentId: string) {async function openCustom(type: string, entityId: string, mime: string) {checkType(type);- if (!utils.isElectron() || utils.isMac()) {+ if (!window.electronApi || utils.isMac()) {return;}const resp = await server.post<TmpResponse>(`${type}/${entityId}/save-to-tmp-dir`);- let filePath = resp.tmpFilePath;- const exec = utils.dynamicRequire("child_process").exec as ExecFunction;- const platform = process.platform;-- if (platform === "linux") {- // we don't know which terminal is available, try in succession- const terminals = ["x-terminal-emulator", "gnome-terminal", "konsole", "xterm", "xfce4-terminal", "mate-terminal", "rxvt", "terminator", "terminology"];- const openFileWithTerminal = (terminal: string) => {- const command = `${terminal} -e 'mimeopen -d "${filePath}"'`;- console.log(`Open Note custom: ${command} `);- exec(command, (error, stdout, stderr) => {- if (error) {- console.error(`Open Note custom: Failed to open file with ${terminal}: ${error}`);- searchTerminal(terminals.indexOf(terminal) + 1);- } else {- console.log(`Open Note custom: File opened with ${terminal}: ${stdout}`);- }- });- };-- const searchTerminal = (index: number) => {- const terminal = terminals[index];- if (!terminal) {- console.error("Open Note custom: No terminal found!");- // TODO: Remove {url: true} if not needed.- (open as any)(getFileUrl(type, entityId), { url: true });- return;- }- exec(`which ${terminal}`, (error, stdout, stderr) => {- if (stdout.trim()) {- openFileWithTerminal(terminal);- } else {- searchTerminal(index + 1);- }- });- };- searchTerminal(0);- } else if (platform === "win32") {- if (filePath.indexOf("/") !== -1) {- // Note that the path separator must be \ instead of /- filePath = filePath.replace(/\//g, "\\");- }- const command = `rundll32.exe shell32.dll,OpenAs_RunDLL ${filePath}`;- exec(command, (err, stdout, stderr) => {- if (err) {- console.error("Open Note custom: ", err);- // TODO: This appears to be broken, since getFileUrl expects two arguments, with the first one being the type.- // Also don't know why {url: true} is passed.- (open as any)(getFileUrl(entityId), { url: true });- return;- }- });- } else {- console.log('Currently "Open Note custom" only supports linux and windows systems');- // TODO: This appears to be broken, since getFileUrl expects two arguments, with the first one being the type.- // Also don't know why {url: true} is passed.- (open as any)(getFileUrl(entityId), { url: true });- }+ window.electronApi.shell.openCustom(resp.tmpFilePath);}const openNoteCustom = async (noteId: string, mime: string) => await openCustom("notes", noteId, mime);diff --git a/apps/desktop/spec/preload.spec.ts b/apps/desktop/spec/preload.spec.tsindex 1e05fade31..687f8048fa 100644--- a/apps/desktop/spec/preload.spec.ts+++ b/apps/desktop/spec/preload.spec.ts@@ -272,6 +272,22 @@ describe("preload script", () => {args: ["file:///tmp/test.txt"]});});++ it("downloadURL sends correct IPC message", () => {+ shell().downloadURL("https://example.com/file.zip");+ expect(ipcRendererSent).toContainEqual({+ channel: "download-url",+ args: ["https://example.com/file.zip"]+ });+ });++ it("openCustom sends correct IPC message", () => {+ shell().openCustom("/tmp/test.txt");+ expect(ipcRendererSent).toContainEqual({+ channel: "open-custom",+ args: ["/tmp/test.txt"]+ });+ });});describe("contextMenu", () => {diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 3227c19a4e..97483ec7a3 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -116,6 +116,12 @@ contextBridge.exposeInMainWorld("electronApi", {},openFileUrl(fileUrl: string): Promise<string> {return ipcRenderer.invoke("open-file-url", fileUrl);+ },+ downloadURL(url: string) {+ ipcRenderer.send("download-url", url);+ },+ openCustom(filePath: string) {+ ipcRenderer.send("open-custom", filePath);}},diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex 5785275d22..de17e15239 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -224,6 +224,56 @@ electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {return electron.shell.openPath(url.fileURLToPath(normalized));});+electron.ipcMain.on("download-url", (event, downloadUrl: string) => {+ event.sender.downloadURL(downloadUrl);+});++electron.ipcMain.on("open-custom", (_event, filePath: string) => {+ const platform = process.platform;++ if (platform === "linux") {+ const { exec } = require("child_process");+ const terminals = ["x-terminal-emulator", "gnome-terminal", "konsole", "xterm", "xfce4-terminal", "mate-terminal", "rxvt", "terminator", "terminology"];++ const openFileWithTerminal = (terminal: string) => {+ const command = `${terminal} -e 'mimeopen -d "${filePath}"'`;+ exec(command, (error: Error | null) => {+ if (error) {+ console.error(`Open custom: Failed with ${terminal}: ${error}`);+ searchTerminal(terminals.indexOf(terminal) + 1);+ }+ });+ };++ const searchTerminal = (index: number) => {+ if (index >= terminals.length) {+ console.error("Open custom: No terminal found!");+ electron.shell.openPath(filePath);+ return;+ }+ exec(`which ${terminals[index]}`, (error: Error | null, stdout: string) => {+ if (stdout.trim()) {+ openFileWithTerminal(terminals[index]);+ } else {+ searchTerminal(index + 1);+ }+ });+ };+ searchTerminal(0);+ } else if (platform === "win32") {+ const { exec } = require("child_process");+ const winPath = filePath.replace(/\//g, "\\");+ exec(`rundll32.exe shell32.dll,OpenAs_RunDLL ${winPath}`, (err: Error | null) => {+ if (err) {+ console.error("Open custom:", err);+ electron.shell.openPath(filePath);+ }+ });+ } else {+ electron.shell.openPath(filePath);+ }+});+electron.ipcMain.on("navigation-history", (event, method: string) => {const wc = event.sender;switch (method) {diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 30d6fd875a..f3789368e7 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -68,6 +68,8 @@ export interface ElectronShellApi {openExternal(url: string): void;openPath(path: string): Promise<string>;openFileUrl(fileUrl: string): Promise<string>;+ downloadURL(url: string): void;+ openCustom(filePath: string): void;}export interface ElectronContextMenuApi {