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(standalone): support app CSS
Elian Doran8b98fdcba197
diff --git a/apps/client-standalone/src/lightweight/browser_routes.ts b/apps/client-standalone/src/lightweight/browser_routes.tsindex dc6868145e..c51aeaabaf 100644--- a/apps/client-standalone/src/lightweight/browser_routes.ts+++ b/apps/client-standalone/src/lightweight/browser_routes.ts@@ -254,12 +254,9 @@ function bootstrapRoute(): BootstrapDefinition {triliumVersion: packageJson.version,device: false as const, // Let the client detect device type.appPath: assetPath,+ instanceName: "standalone",// TODO: Fill properly- currentLocale: { id: "en", name: "English", rtl: false },- isRtl: false,- instanceName: null,- appCssNoteIds: [],TRILIUM_SAFE_MODE: false};diff --git a/apps/server/src/routes/api/files.ts b/apps/server/src/routes/api/files.tsindex 8d5199385a..75cd081683 100644--- a/apps/server/src/routes/api/files.ts+++ b/apps/server/src/routes/api/files.ts@@ -1,17 +1,14 @@import { ValidationError } from "@triliumnext/core";import chokidar from "chokidar";-import type { Request, Response } from "express";+import type { Request } from "express";import fs from "fs";import { Readable } from "stream";import tmp from "tmp";import becca from "../../becca/becca.js";-import type BAttachment from "../../becca/entities/battachment.js";-import type BNote from "../../becca/entities/bnote.js";import dataDirs from "../../services/data_dir.js";import log from "../../services/log.js";import noteService from "../../services/notes.js";-import protectedSessionService from "../../services/protected_session.js";import utils from "../../services/utils.js";import ws from "../../services/ws.js";@@ -64,49 +61,6 @@ function updateAttachment(req: Request<{ attachmentId: string }>) {};}-function downloadData(noteOrAttachment: BNote | BAttachment, res: Response, contentDisposition: boolean) {- if (noteOrAttachment.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {- return res.status(401).send("Protected session not available");- }-- if (contentDisposition) {- const fileName = noteOrAttachment.getFileName();-- res.setHeader("Content-Disposition", utils.getContentDisposition(fileName));- }-- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader("Content-Type", noteOrAttachment.mime);-- res.send(noteOrAttachment.getContent());-}--function downloadNoteInt(noteId: string, res: Response, contentDisposition = true) {- const note = becca.getNote(noteId);-- if (!note) {- return res.setHeader("Content-Type", "text/plain").status(404).send(`Note '${noteId}' doesn't exist.`);- }-- return downloadData(note, res, contentDisposition);-}--function downloadAttachmentInt(attachmentId: string, res: Response, contentDisposition = true) {- const attachment = becca.getAttachment(attachmentId);-- if (!attachment) {- return res.setHeader("Content-Type", "text/plain").status(404).send(`Attachment '${attachmentId}' doesn't exist.`);- }-- return downloadData(attachment, res, contentDisposition);-}--const downloadFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, true);-const openFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, false);--const downloadAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, true);-const openAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, false);-function fileContentProvider(req: Request<{ noteId: string }>) {// Read the file name from route params.const note = becca.getNoteOrThrow(req.params.noteId);@@ -248,13 +202,8 @@ function uploadModifiedFileToAttachment(req: Request<{ attachmentId: string }>)export default {updateFile,updateAttachment,- openFile,fileContentProvider,- downloadFile,- downloadNoteInt,saveNoteToTmpDir,- openAttachment,- downloadAttachment,saveAttachmentToTmpDir,attachmentContentProvider,uploadModifiedFileToNote,diff --git a/apps/server/src/routes/index.ts b/apps/server/src/routes/index.tsindex f63d382023..a3428c5d2e 100644--- a/apps/server/src/routes/index.ts+++ b/apps/server/src/routes/index.ts@@ -76,7 +76,6 @@ export function bootstrap(req: Request, res: Response) {&& isElectron&& (isWindows11 || isMac)&& !nativeTitleBarVisible,- appCssNoteIds: getAppCssNoteIds(),isMainWindow: view === "mobile" ? true : !req.query.extraWindow,iconPackCss: iconPacks.map((p: iconPackService.ProcessedIconPack) => iconPackService.generateCss(p, p.builtin@@ -144,7 +143,3 @@ function getThemeCssUrl(theme: string, themeNote: BNote | null) {// baseline light themereturn false;}--function getAppCssNoteIds() {- return attributeService.getNotesWithLabel("appCss").map((note) => note.noteId);-}diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex edb17af7a9..364c309704 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -93,7 +93,6 @@ function register(app: express.Application) {});route(PUT, "/api/notes/:noteId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);- route(GET, "/api/notes/:noteId/open", [auth.checkApiAuthOrElectron], filesRoute.openFile);asyncRoute(GET,"/api/notes/:noteId/open-partial",@@ -104,15 +103,11 @@ function register(app: express.Application) {}}));- route(GET, "/api/notes/:noteId/download", [auth.checkApiAuthOrElectron], filesRoute.downloadFile);- // this "hacky" path is used for easier referencing of CSS resources- route(GET, "/api/notes/download/:noteId", [auth.checkApiAuthOrElectron], filesRoute.downloadFile);apiRoute(PST, "/api/notes/:noteId/save-to-tmp-dir", filesRoute.saveNoteToTmpDir);apiRoute(PST, "/api/notes/:noteId/upload-modified-file", filesRoute.uploadModifiedFileToNote);// TODO: Bring back attachment uploading// route(PST, "/api/notes/:noteId/attachments/upload", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);- route(GET, "/api/attachments/:attachmentId/open", [auth.checkApiAuthOrElectron], filesRoute.openAttachment);asyncRoute(GET,"/api/attachments/:attachmentId/open-partial",diff --git a/packages/trilium-core/src/routes/api/files.ts b/packages/trilium-core/src/routes/api/files.tsnew file mode 100644index 0000000000..cd116b886f--- /dev/null+++ b/packages/trilium-core/src/routes/api/files.ts@@ -0,0 +1,57 @@+import { Request, Response } from "express";+import becca from "../../becca/becca";+import BAttachment from "../../becca/entities/battachment";+import BNote from "../../becca/entities/bnote";+import protected_session from "../../services/protected_session";+import { utils } from "../..";++const downloadFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, true);+const openFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, false);++const downloadAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, true);+const openAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, false);++function downloadNoteInt(noteId: string, res: Response, contentDisposition = true) {+ const note = becca.getNote(noteId);++ if (!note) {+ return res.setHeader("Content-Type", "text/plain").status(404).send(`Note '${noteId}' doesn't exist.`);+ }++ return downloadData(note, res, contentDisposition);+}++function downloadAttachmentInt(attachmentId: string, res: Response, contentDisposition = true) {+ const attachment = becca.getAttachment(attachmentId);++ if (!attachment) {+ return res.setHeader("Content-Type", "text/plain").status(404).send(`Attachment '${attachmentId}' doesn't exist.`);+ }++ return downloadData(attachment, res, contentDisposition);+}++function downloadData(noteOrAttachment: BNote | BAttachment, res: Response, contentDisposition: boolean) {+ if (noteOrAttachment.isProtected && !protected_session.isProtectedSessionAvailable()) {+ return res.status(401).send("Protected session not available");+ }++ if (contentDisposition) {+ const fileName = noteOrAttachment.getFileName();++ res.setHeader("Content-Disposition", utils.getContentDisposition(fileName));+ }++ res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");+ res.setHeader("Content-Type", noteOrAttachment.mime);++ res.send(noteOrAttachment.getContent());+}++export default {+ openFile,+ downloadFile,+ downloadNoteInt,+ openAttachment,+ downloadAttachment,+}diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 22feecddeb..b016a40172 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -24,6 +24,7 @@ import autocompleteApiRoute from "./api/autocomplete";import similarNotesRoute from "./api/similar_notes";import imageRoute from "./api/image";import setupApiRoute from "./api/setup";+import filesRoute from "./api/files";// TODO: Deduplicate with routes.tsconst GET = "get",@@ -190,6 +191,14 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRoutasyncApiRoute(GET, "/api/similar-notes/:noteId", similarNotesRoute.getSimilarNotes);apiRoute(PST, "/api/relation-map", relationMapApiRoute.getRelationMap);apiRoute(GET, "/api/recent-changes/:ancestorNoteId", recentChangesApiRoute.getRecentChanges);++ //#region Files+ route(GET, "/api/notes/:noteId/open", [checkApiAuthOrElectron], filesRoute.openFile);+ route(GET, "/api/notes/:noteId/download", [checkApiAuthOrElectron], filesRoute.downloadFile);+ // this "hacky" path is used for easier referencing of CSS resources+ route(GET, "/api/notes/download/:noteId", [checkApiAuthOrElectron], filesRoute.downloadFile);+ route(GET, "/api/attachments/:attachmentId/open", [checkApiAuthOrElectron], filesRoute.openAttachment);+ //#endregion}/** Handling common patterns. If entity is not caught, serialization to JSON will fail */diff --git a/packages/trilium-core/src/services/bootstrap_utils.ts b/packages/trilium-core/src/services/bootstrap_utils.tsindex 7f41145870..6ea765554c 100644--- a/packages/trilium-core/src/services/bootstrap_utils.ts+++ b/packages/trilium-core/src/services/bootstrap_utils.ts@@ -4,6 +4,7 @@ import protected_session from "./protected_session";import { generateCss, generateIconRegistry, getIconPacks, MIME_TO_EXTENSION_MAPPINGS } from "./icon_packs";import options from "./options";import { getCurrentLocale } from "./i18n";+import attributes from "./attributes";export default function getSharedBootstrapItems(assetPath: string, dbInitialized: boolean) {const sql = getSql();@@ -18,6 +19,7 @@ export default function getSharedBootstrapItems(assetPath: string, dbInitializedlayoutOrientation: "vertical" as const,headingStyle: "plain" as const,componentId: "",+ appCssNoteIds: getAppCssNoteIds(),...getIconConfig(assetPath)};@@ -52,3 +54,7 @@ export function getIconConfig(assetPath: string): Pick<BootstrapDefinition, "ico.join("\n\n"),};}++function getAppCssNoteIds() {+ return attributes.getNotesWithLabel("appCss").map((note) => note.noteId);+}diff --git a/packages/trilium-core/src/services/utils/index.ts b/packages/trilium-core/src/services/utils/index.tsindex ae0dcf7c62..b2f1188ee1 100644--- a/packages/trilium-core/src/services/utils/index.ts+++ b/packages/trilium-core/src/services/utils/index.ts@@ -1,7 +1,7 @@import { getCrypto } from "../encryption/crypto";import { sanitizeFileName } from "../sanitizer";import { encodeBase64 } from "./binary";-import mimeTypes from "mime-types";+import { extensions as mimeToExt, types as extToMime } from "mime-types";import escape from "escape-html";import unescape from "unescape";import path from "path";@@ -161,12 +161,13 @@ export function formatDownloadTitle(fileName: string, type: string | null, mime:if (mimeLc === "application/octet-stream") return "";// if fileName has an extension matching the mime already - reuse it- const mimeTypeFromFileName = mimeTypes.lookup(fileName);- if (mimeTypeFromFileName === mimeLc) return "";+ const dotIdx = fileName.lastIndexOf(".");+ const ext = dotIdx !== -1 ? fileName.substring(dotIdx + 1).toLowerCase() : "";+ if (ext && extToMime[ext] === mimeLc) return "";// as last resort try to get extension from mimeType- const extensions = mimeTypes.extension(mime);- return extensions ? `.${extensions}` : "";+ const exts = mimeToExt[mime];+ return exts?.length ? `.${exts[0]}` : "";};return `${fileNameBase}${getExtension()}`;