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(clipper): save a PDF tab as a file note (closes #1209)
Elian Doranb02a3fcf34e9
diff --git a/apps/server/spec/etapi/app-info.spec.ts b/apps/server/spec/etapi/app-info.spec.tsindex 03a5a389b5..236e661ad6 100644--- a/apps/server/spec/etapi/app-info.spec.ts+++ b/apps/server/spec/etapi/app-info.spec.ts@@ -15,6 +15,6 @@ describe("etapi/app-info", () => {const response = await supertest(app).get("/etapi/app-info").expect(200);- expect(response.body.clipperProtocolVersion).toBe("1.0");+ expect(response.body.clipperProtocolVersion).toBe("1.1");});});diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.htmlindex ae909bf9be..65f12b24f4 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Web Clipper.html@@ -24,6 +24,7 @@<li>select text and clip it with the right-click context menu</li><li>click on an image or link and save it through context menu</li><li>save whole page from the popup or context menu</li>+ <li>save a PDF that the browser shows, as a file note</li><li>save a screenshot of an area you select, of the visible part of the pageor of the whole page, from either popup or context menu</li><li>create short text note from popup</li>@@ -55,6 +56,13 @@of the note. When it states when it was last modified, that date showsbelow, marked by the <span class="tn-icon bx bx-history"></span> icon, andis saved in the <code>#modifiedDate</code> label.</li>+ <li><em>PDF</em>, when the tab shows a PDF in the browser's viewer: <em>Save PDF to Trilium</em> downloads+ the PDF and saves it as a file note, which Trilium opens in its <a+ class="reference-link" href="#root/_help_XJGJrpu7F9sh">PDFs</a> viewer.+ Only the title and the description can be edited, since a file note has+ no text of its own for your note. The page's address is saved in the note's <code>#pageUrl</code> label+ and the PDF's file name in <code>#originalFileName</code>. Saving a PDF+ needs Trilium v0.107.0 or later.</li><li><em>Bookmark</em>, always: there is no preview, and <em>Save bookmark</em> savesa link to the page with your note as the content of the note. Left empty,the title stays the page's title.</li>@@ -77,10 +85,11 @@next to the title of the note (see <a class="reference-link" href="#root/_help_B5dihXRDksTk">Note badges</a>).</p><p>The popup opens on the selection if there is one, otherwise on <em>Page</em>,showing the article, or the whole page when the page has no article. On- a page that shows nothing to save, it opens on <em>Bookmark</em> and says- so. The keyboard shortcuts and the context menu still save right away,- without a preview: saving the whole page that way saves the article, or- the whole page when the page has no article.</p>+ a PDF, it opens on <em>PDF</em>. On a page that shows nothing to save, it+ opens on <em>Bookmark</em> and says so. The keyboard shortcuts and the context+ menu still save right away, without a preview: saving the whole page that+ way saves the article, the whole page when the page has no article, or+ the PDF when the tab shows one.</p></li><li><p>Pages the extension cannot access (the browser's own pages, the extension@@ -138,7 +147,8 @@<p>Further clippings of the same kind from the same page are added to thenote created by the first one, even on a later day or after that note wasmoved out of the clipper inbox. The note stays where it is and is not cloned- back into the inbox.</p>+ back into the inbox. A PDF is the exception: each save creates a new file+ note, since the PDF can have changed since it was last saved.</p><p>The icon of a clipped note shows what was saved:</p><ul><li><span class="tn-icon bx bx-paperclip"></span> a selection, a screenshot@@ -148,7 +158,8 @@<li><span class="tn-icon bx bx-window-alt"></span> the tabs of a window.</li></ul><p>The icon is derived from the note's <code>#clipType</code> label, so setting- an <code>#iconClass</code> label on the note replaces it.</p>+ an <code>#iconClass</code> label on the note replaces it. A saved PDF has+ the icon of a PDF file, like any other PDF in Trilium.</p><h2>Embedded videos</h2><p>A YouTube video embedded in a clipped page is saved as a <a class="reference-link"href="#root/_help_UmgZAfcltxkS">Link Previews</a> embed, with the video's@@ -211,6 +222,10 @@one the message names.</li><li>Trilium rejected the request: the message includes the reason Triliumgave.</li>+ <li>A PDF could not be saved: Trilium is older than v0.107.0, the website+ refused to send the PDF again, or the PDF is larger than 100 MB. The extension+ downloads the PDF with the browser's cookies for that website, so a PDF+ behind a login can be saved while you are logged in.</li></ul><p>The extension downloads the images of a clipping itself, so that theyare stored in Trilium together with the note. If some of them cannot bediff --git a/apps/server/src/assets/etapi.openapi.yaml b/apps/server/src/assets/etapi.openapi.yamlindex 45d2fff99c..4e2b74c5a0 100644--- a/apps/server/src/assets/etapi.openapi.yaml+++ b/apps/server/src/assets/etapi.openapi.yaml@@ -1423,7 +1423,7 @@ components:clipperProtocolVersion:type: stringdescription: version of the supported Trilium Web Clipper protocol- example: 1.0+ example: 1.1utcDateTime:type: stringdescription: current UTC date timediff --git a/apps/server/src/routes/api/clipper.spec.ts b/apps/server/src/routes/api/clipper.spec.tsindex 7619c80f3d..6065e8c715 100644--- a/apps/server/src/routes/api/clipper.spec.ts+++ b/apps/server/src/routes/api/clipper.spec.ts@@ -225,6 +225,55 @@ describe("clipper route handlers", () => {});});+ describe("saving files", () => {+ const PDF = Buffer.from("%PDF-1.7 bytes");++ function createFile(body: object) {+ return cls.init(() => clipperRoute.createFile({ body } as unknown as Request));+ }++ it("saves a PDF as a file note, a new one each time", async () => {+ const body = {+ title: " Annual report ",+ fileName: "../report.pdf",+ pageUrl: "https://example.com/report.pdf",+ dataUrl: `data:application/pdf;base64,${PDF.toString("base64")}`,+ labels: { pageDescription: "Tom & <b>Jerry</b>" }+ };+ const { noteId } = await createFile(body);++ const note = becca.getNoteOrThrow(noteId);+ expect(note.title).toBe("Annual report");+ expect(note.type).toBe("file");+ expect(note.mime).toBe("application/pdf");+ expect(Buffer.from(note.getContent())).toEqual(PDF);+ expect(note.getLabelValue("clipType")).toBe("file");+ expect(note.getLabelValue("pageUrl")).toBe("https://example.com/report.pdf");+ expect(note.getLabelValue("originalFileName")).toBe("report.pdf");+ expect(note.getLabelValue("pageDescription")).toBe("Tom & Jerry");++ const second = await createFile(body);+ expect(second.noteId).not.toBe(noteId);+ });++ it("titles the note after the file, or the page without one", async () => {+ const dataUrl = `data:application/pdf;base64,${PDF.toString("base64")}`;+ const named = await createFile({ title: " ", fileName: "report.pdf", pageUrl: "https://example.com/a", dataUrl });+ expect(becca.getNoteOrThrow(named.noteId).title).toBe("report.pdf");++ const unnamed = await createFile({ pageUrl: "https://example.com/b", dataUrl });+ const note = becca.getNoteOrThrow(unnamed.noteId);+ expect(note.title).toBe("Clipped file from https://example.com/b");+ expect(note.hasLabel("originalFileName")).toBe(false);+ });++ it("rejects a file that is not a base64 data URL", async () => {+ await expect(createFile({ title: "x", dataUrl: "https://example.com/report.pdf" }))+ .rejects.toThrow("The file must be sent as a base64 data URL.");+ await expect(createFile({ title: "x" })).rejects.toThrow("The file must be sent as a base64 data URL.");+ });+ });+it("creates a standalone note with labels", async () => {const result = await cls.init(() => clipperRoute.createNote({body: {diff --git a/apps/server/src/routes/api/clipper.ts b/apps/server/src/routes/api/clipper.tsindex 29470d45f9..d193608ea5 100644--- a/apps/server/src/routes/api/clipper.ts+++ b/apps/server/src/routes/api/clipper.ts@@ -140,6 +140,45 @@ async function createNote(req: Request) {};}+/**+ * Saves a file the extension downloaded, such as the PDF a tab shows, as a file note. Each call+ * creates a note, since a file at the same address can have changed since it was last clipped.+ */+async function createFile(req: Request) {+ const { dataUrl, labels } = req.body;+ const header = typeof dataUrl === "string" ? /^data:([\w.+-]+\/[\w.+-]+);base64,/.exec(dataUrl) : null;+ if (!header) {+ throw new ValidationError("The file must be sent as a base64 data URL.");+ }++ const pageUrl = req.body.pageUrl ? sanitize.sanitizeUrl(req.body.pageUrl) : "";+ const fileName = typeof req.body.fileName === "string" ? path.basename(req.body.fileName).trim() : "";+ const trimmedTitle = typeof req.body.title === "string" ? req.body.title.trim() : "";+ const title = trimmedTitle || fileName || `Clipped file from ${pageUrl}`;++ const clipperInbox = await getClipperInboxNote();+ const { note } = noteService.createNewNote({+ parentNoteId: clipperInbox.noteId,+ title,+ content: Buffer.from(dataUrl.substring(header[0].length), "base64"),+ type: "file",+ mime: header[1]+ });++ note.setLabel("clipType", "file");+ if (pageUrl) {+ note.setLabel("pageUrl", pageUrl);+ }+ if (fileName) {+ note.setLabel("originalFileName", fileName);+ }+ setLabels(note, labels);++ return {+ noteId: note.noteId+ };+}+/*** Renders saved browser tabs as a list of link mentions, each with the tab's favicon stored as an* attachment of `note`. Returns undefined when automatic link previews are turned off or the@@ -327,6 +366,7 @@ async function findNotesByUrl(req: Request<{ noteUrl: string }>) {export default {createNote,+ createFile,addClipping,openNote,handshake,diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.tsindex 6933c8e606..1e00258ead 100644--- a/apps/server/src/routes/routes.ts+++ b/apps/server/src/routes/routes.ts@@ -135,6 +135,7 @@ function register(app: express.Application) {route(GET, "/api/clipper/handshake", clipperMiddleware, clipperRoute.handshake, apiResultHandler);asyncRoute(PST, "/api/clipper/clippings", clipperMiddleware, clipperRoute.addClipping, apiResultHandler);asyncRoute(PST, "/api/clipper/notes", clipperMiddleware, clipperRoute.createNote, apiResultHandler);+ asyncRoute(PST, "/api/clipper/files", clipperMiddleware, clipperRoute.createFile, apiResultHandler);route(PST, "/api/clipper/open/:noteId", clipperMiddleware, clipperRoute.openNote, apiResultHandler);asyncRoute(GET, "/api/clipper/notes-by-url/:noteUrl", clipperMiddleware, clipperRoute.findNotesByUrl, apiResultHandler);diff --git a/apps/web-clipper/entrypoints/background/index.spec.ts b/apps/web-clipper/entrypoints/background/index.spec.tsindex 9728f9b5b9..e6325bf00f 100644--- a/apps/web-clipper/entrypoints/background/index.spec.ts+++ b/apps/web-clipper/entrypoints/background/index.spec.ts@@ -6,7 +6,8 @@ const { facade, TriliumError } = vi.hoisted(() => ({callService: vi.fn<(method: string, path: string, body?: unknown) => Promise<any>>(),triggerSearchForTrilium: vi.fn(),sendTriliumSearchStatusToPopup: vi.fn(),- triggerSearchNoteByUrl: vi.fn()+ triggerSearchNoteByUrl: vi.fn(),+ requireMinorVersion: vi.fn(async (_minor: number, _feature: string) => {})},TriliumError: class extends Error {@@ -40,6 +41,7 @@ vi.mock("./trilium_server_facade", () => ({triggerSearchForTrilium = facade.triggerSearchForTrilium;sendTriliumSearchStatusToPopup = facade.sendTriliumSearchStatusToPopup;triggerSearchNoteByUrl = facade.triggerSearchNoteByUrl;+ requireMinorVersion = facade.requireMinorVersion;}}));@@ -73,7 +75,12 @@ const tabsSendMessage = vi.fn((_tabId: number, message: { name: string }) => Promise.resolve(tabMessageHandler(message)));/** How `readable-page.js` reads the active tab, by variant; nothing to save unless a test says so. */let pageReadings: Record<string, unknown>;-const executeScript = vi.fn(async ({ args }: { args?: [ string ] }) => args ? [ { result: pageReadings[args[0]] } ] : []);+/** Whether the active tab shows a PDF, as the check run in the tab answers. */+let pdfTab: boolean;+const executeScript = vi.fn(async ({ args, func }: { args?: [ string ], func?: unknown }) => {+ if (args) return [ { result: pageReadings[args[0]] } ];+ return func ? [ { result: pdfTab } ] : [];+});const contextMenusCreate = vi.fn();const contextMenusRemoveAll = vi.fn(async () => {});const getContexts = vi.fn(async (): Promise<unknown[]> => []);@@ -93,6 +100,7 @@ describe("background", () => {tabs = [ ACTIVE_TAB ];tabMessageHandler = () => undefined;pageReadings = {};+ pdfTab = false;facade.callService.mockResolvedValue({ noteId: "saved" });vi.stubGlobal("fetch", fetchMock);vi.spyOn(console, "log").mockImplementation(() => {});@@ -306,7 +314,7 @@ describe("background", () => {await onContextMenuClicked({ menuItemId: "trilium-save-page" });await sendRuntimeMessage({ name: "save-whole-page" });- expect(executeScript).toHaveBeenCalledTimes(6);+ expect(executeScript).toHaveBeenCalledTimes(9);expect(executeScript).toHaveBeenCalledWith({ target: { tabId: 7 }, files: [ "/readable-page.js" ] });expect(executeScript).not.toHaveBeenCalledWith(expect.objectContaining({ args: [ "wholePage" ] }));expect(facade.callService).toHaveBeenCalledTimes(3);@@ -341,6 +349,8 @@ describe("background", () => {await onCommand("saveWholePage");tabs = [ ACTIVE_TAB ];+ // Once for the PDF check, once for the page.+ executeScript.mockRejectedValueOnce(new Error("Cannot access a chrome:// URL"));executeScript.mockRejectedValueOnce(new Error("Cannot access a chrome:// URL"));await onCommand("saveWholePage");expect(await lastToast()).toMatchObject({@@ -348,7 +358,7 @@ describe("background", () => {message: "Saving to Trilium failed: Cannot access a chrome:// URL"});- expect(executeScript).toHaveBeenCalledTimes(5);+ expect(executeScript).toHaveBeenCalledTimes(7);expect(facade.callService).not.toHaveBeenCalled();});@@ -391,6 +401,117 @@ describe("background", () => {});});+ describe("saving a PDF", () => {+ const PDF = "%PDF-1.7 bytes";+ const PDF_DATA_URL = `data:application/pdf;base64,${btoa(PDF)}`;++ function answerPdf(body: BodyInit = PDF, headers: Record<string, string> = {}, status = 200) {+ fetchMock.mockImplementation(async () => new Response(body, { status, headers }));+ }++ afterEach(() => {+ fetchMock.mockImplementation(fetchMockDefault);+ });++ it("saves the PDF the tab shows as a file, from the shortcut, the menu and the popup", async () => {+ pdfTab = true;+ answerPdf(PDF, { "Content-Disposition": "inline; filename*=UTF-8''Annual%20report.pdf" });++ await onCommand("saveWholePage");+ await onContextMenuClicked({ menuItemId: "trilium-save-page" });+ await sendRuntimeMessage({ name: "save-whole-page" });++ expect(executeScript).not.toHaveBeenCalledWith(expect.objectContaining({ files: [ "/readable-page.js" ] }));+ expect(facade.requireMinorVersion).toHaveBeenCalledWith(1, "Saving a PDF");+ expect(fetchMock).toHaveBeenCalledWith(PAGE_URL, { credentials: "include" });+ expect(facade.callService.mock.calls).toEqual(Array(3).fill([ "POST", "files", {+ title: "Active page",+ fileName: "Annual report.pdf",+ pageUrl: PAGE_URL,+ dataUrl: PDF_DATA_URL+ } ]));+ expect(await lastToast()).toMatchObject({ message: "PDF has been saved to Trilium.", noteId: "saved" });+ });++ it("saves the PDF the popup names, with the user's title and description", async () => {+ answerPdf();+ const pdfUrl = "https://example.com/files/report";++ await sendRuntimeMessage({ name: "save-pdf", url: pdfUrl, title: "Edited", description: "Summary" });++ expect(fetchMock).toHaveBeenCalledWith(pdfUrl, { credentials: "include" });+ expect(lastPayload()).toEqual({+ title: "Edited",+ fileName: "report.pdf",+ pageUrl: pdfUrl,+ dataUrl: PDF_DATA_URL,+ labels: { pageDescription: "Summary" }+ });++ await sendRuntimeMessage({ name: "save-pdf", url: pdfUrl, title: "" });+ expect(lastPayload()).toMatchObject({ title: "Active page" });+ expect(lastPayload()).not.toHaveProperty("labels");+ });++ it("names the file as the website does, or else after its address", async () => {+ const savedFileName = async (url: string, disposition?: string) => {+ answerPdf(PDF, disposition ? { "Content-Disposition": disposition } : {});+ await sendRuntimeMessage({ name: "save-pdf", url, title: "T" });+ return (lastPayload() as { fileName?: string }).fileName;+ };++ expect(await savedFileName(PAGE_URL, `attachment; filename="Q3 results.PDF"`)).toBe("Q3 results.PDF");+ expect(await savedFileName(PAGE_URL, "attachment; filename=plain")).toBe("plain.pdf");+ expect(await savedFileName(PAGE_URL, "attachment; filename*=UTF-8''%E0%A4%A")).toBe("%E0%A4%A.pdf");+ expect(await savedFileName("https://example.com/a/%C3%A9t%C3%A9.pdf?x=1")).toBe("été.pdf");+ expect(await savedFileName("https://example.com/a/%E0%A4%A")).toBe("%E0%A4%A.pdf");+ expect(await savedFileName("https://example.com/a/", "inline")).toBeUndefined();+ });++ it("saves nothing that is not a PDF, too large, or out of reach, and says why", async () => {+ const failure = async (message: object) => {+ facade.callService.mockClear();+ tabsSendMessage.mockClear();+ await sendRuntimeMessage({ name: "save-pdf", url: PAGE_URL, title: "T", ...message });+ expect(facade.callService).not.toHaveBeenCalled();+ return (await lastToast() as { message?: string } | undefined)?.message;+ };++ facade.requireMinorVersion.mockRejectedValueOnce(+ new TriliumError("version-mismatch", "Saving a PDF needs a newer version of Trilium."));+ expect(await failure({})).toBe("Saving a PDF needs a newer version of Trilium.");+ expect(fetchMock).not.toHaveBeenCalled();++ answerPdf("Not found", {}, 404);+ expect(await failure({})).toBe("Saving to Trilium failed: The PDF could not be downloaded: HTTP 404");++ answerPdf("<html></html>");+ expect(await failure({})).toBe("Saving to Trilium failed: The page is not a PDF.");++ const TOO_LARGE = "Saving to Trilium failed: The PDF is larger than 100 MB, the most the clipper saves.";+ answerPdf(PDF, { "Content-Length": String(100 * 1024 * 1024 + 1) });+ expect(await failure({})).toBe(TOO_LARGE);++ const unannounced = new Response(PDF);+ vi.spyOn(unannounced, "blob").mockResolvedValue({ size: 100 * 1024 * 1024 + 1 } as Blob);+ fetchMock.mockResolvedValueOnce(unannounced);+ expect(await failure({})).toBe(TOO_LARGE);++ answerPdf();+ vi.stubGlobal("FileReader", class {++ result = null;+ onloadend: (() => void) | null = null;++ readAsDataURL() {+ setTimeout(() => this.onloadend?.());+ }++ });+ expect(await failure({})).toBe("Saving to Trilium failed: The PDF could not be read.");+ });+ });+describe("screenshots", () => {it("crops the screenshot in an offscreen document and saves it as an image", async () => {tabMessageHandler = () => ({diff --git a/apps/web-clipper/entrypoints/background/index.ts b/apps/web-clipper/entrypoints/background/index.tsindex ffc4fc5693..b3a4e5e855 100644--- a/apps/web-clipper/entrypoints/background/index.ts+++ b/apps/web-clipper/entrypoints/background/index.ts@@ -1,7 +1,7 @@import {type ScreenshotSlice, ScreenshotStitcher, type StitchMessage, type StitchRequest} from "@/screenshot";-import { extractPage, randomString, type Rect } from "@/utils";+import { extractPage, isPdfTab, randomString, type Rect } from "@/utils";import setupContextMenu from "./context_menu";import TriliumServerFacade, { TriliumError } from "./trilium_server_facade";@@ -52,6 +52,8 @@ const CAPTURE_INTERVAL_MS = 550;const SCROLL_SETTLE_MS = 150;/** The most captures a full-page screenshot takes, about a minute; a longer page is cut off. */const MAX_SCREENSHOT_CAPTURES = 100;+/** The largest PDF the clipper saves. It reaches Trilium as base64 in a single request. */+const MAX_PDF_SIZE = 100 * 1024 * 1024;/** An image of a clipping; `content` references it by `imageId` until Trilium stores it. */type ClippedImage = { imageId: string, src: string, dataUrl?: string };@@ -482,7 +484,15 @@ export default defineBackground(() => {* whole page when it has none.*/async function saveWholePage(page?: object) {- const payload = page ?? await readActivePage();+ let payload = page;+ if (!payload) {+ const activeTab = await getActiveTab();+ if (activeTab.url && await isPdfTab(activeTab)) {+ await savePdf(activeTab.url, activeTab.title);+ return;+ }+ payload = await readPage(activeTab);+ }const failedImages = await postProcessImages(payload);@@ -491,8 +501,52 @@ export default defineBackground(() => {toast(savedMessage("Page", failedImages), resp.noteId);}- async function readActivePage() {- const activeTab = await getActiveTab();+ /**+ * Downloads the PDF at `url`, as the browser does, with the website's cookies, and saves it as a+ * file note. Trilium has the route for it since protocol version 1.1.+ */+ async function savePdf(url: string, title: string | undefined, description?: string) {+ await triliumServerFacade.requireMinorVersion(1, "Saving a PDF");+ const { dataUrl, fileName } = await downloadPdf(url);++ const resp = await triliumServerFacade.callService("POST", "files", {+ title: title || (await getActiveTab()).title,+ fileName,+ pageUrl: url,+ dataUrl,+ ...(description && { labels: { pageDescription: description } })+ });++ toast(savedMessage("PDF", 0), resp.noteId);+ }++ async function downloadPdf(url: string) {+ const response = await fetch(url, { credentials: "include" });+ if (!response.ok) {+ throw new Error(`The PDF could not be downloaded: HTTP ${response.status}`);+ }+ if (Number(response.headers.get("content-length")) > MAX_PDF_SIZE) {+ throw pdfTooLarge();+ }++ const blob = await response.blob();+ if (blob.size > MAX_PDF_SIZE) {+ throw pdfTooLarge();+ }+ // A PDF can have bytes before its header, within the first kilobyte.+ if (!(await blob.slice(0, 1024).text()).includes("%PDF-")) {+ throw new Error("The page is not a PDF.");+ }++ const dataUrl = await blob2base64(new Blob([ blob ], { type: "application/pdf" }));+ if (!dataUrl) {+ throw new Error("The PDF could not be read.");+ }++ return { dataUrl, fileName: pdfFileName(response, url) };+ }++ async function readPage(activeTab: Browser.tabs.Tab) {const tabId = activeTab.id;if (tabId !== undefined) {const article = await extractPage(tabId, "article");@@ -665,6 +719,9 @@ export default defineBackground(() => {else if (request.name === 'save-whole-page') {return await saveWholePage(request.page);}+ else if (request.name === 'save-pdf') {+ return await savePdf(request.url, request.title, request.description);+ }else if (request.name === 'save-selection') {return await saveSelection(request.selection);}@@ -703,6 +760,35 @@ function escapeHtml(value: string) {.replaceAll(">", ">");}+function pdfTooLarge() {+ return new Error(`The PDF is larger than ${MAX_PDF_SIZE / 1024 / 1024} MB, the most the clipper saves.`);+}++/**+ * The PDF's file name, as the website gives it or as its address ends, with a `.pdf` extension;+ * `undefined` when neither names it.+ */+function pdfFileName(response: Response, url: string) {+ const disposition = response.headers.get("content-disposition") ?? "";+ const encoded = /filename\*=[^']*'[^']*'([^;]+)/i.exec(disposition)?.[1];+ const plain = /filename=\s*"?([^";]+)/i.exec(disposition)?.[1];+ const { pathname } = new URL(url);+ const name = (encoded && decodeComponent(encoded.trim()))+ || plain?.trim()+ || decodeComponent(pathname.slice(pathname.lastIndexOf("/") + 1));+ if (!name) return undefined;+ return /\.pdf$/i.test(name) ? name : `${name}.pdf`;+}++/** Decodes a percent-encoded name, or keeps it as it is when it is malformed. */+function decodeComponent(value: string) {+ try {+ return decodeURIComponent(value);+ } catch {+ return value;+ }+}+function failureMessage(error: unknown) {if (error instanceof TriliumError) return error.message;const details = error instanceof Error ? error.message : "";diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.tsindex 098503c7dc..e9ade97213 100644--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.spec.ts@@ -7,8 +7,8 @@ const fetchMock = vi.fn<(url: string, init?: RequestInit) => Promise<Response>>(const SERVER = { triliumServerUrl: "https://trilium.example", authToken: "secret" };const LOCAL_DATE_TIME = /^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d{3}[+-]\d\d:\d\d$/;const DESKTOP_HANDSHAKE = "http://127.0.0.1:37743/api/clipper/handshake";-const FOUND_DESKTOP = { status: "found-desktop", port: 37743, url: "http://127.0.0.1:37743" };-const FOUND_SERVER = { status: "found-server", url: "https://trilium.example", token: "secret" };+const FOUND_DESKTOP = { status: "found-desktop", port: 37743, url: "http://127.0.0.1:37743", protocolMinor: 0 };+const FOUND_SERVER = { status: "found-server", url: "https://trilium.example", token: "secret", protocolMinor: 0 };type PopupMessage = { name: string, triliumSearch?: unknown, searchNote?: unknown };const sendMessage = vi.fn(async (_message: PopupMessage) => {});@@ -65,7 +65,7 @@ describe("TriliumServerFacade", () => {await vi.advanceTimersByTimeAsync(60 * 1000);expect(fetchMock).toHaveBeenCalledTimes(2);expect(searchStatuses()).toEqual([- { status: "found-desktop", port: 12345, url: "http://127.0.0.1:12345" }+ { status: "found-desktop", port: 12345, url: "http://127.0.0.1:12345", protocolMinor: 2 }]);});@@ -306,6 +306,26 @@ describe("TriliumServerFacade", () => {await expect(facade.callService("GET", "notes-by-url/x")).rejects.toThrow(expect.objectContaining({ message: expect.stringContaining("Update the web clipper") }));});++ it("rejects a feature that needs a later minor version than Trilium has", async () => {+ fetchMock.mockResolvedValue(handshake("1"));+ const facade = await createFacade();++ await expect(facade.requireMinorVersion(1, "Saving a PDF")).rejects.toThrow(expect.objectContaining({+ reason: "version-mismatch",+ message: "Saving a PDF needs a newer version of Trilium. Update Trilium to the latest version."+ }));+ await expect(facade.requireMinorVersion(0, "Saving a PDF")).resolves.toBeUndefined();++ fetchMock.mockResolvedValue(handshake("1.1"));+ await facade.triggerSearchForTrilium();+ await expect(facade.requireMinorVersion(1, "Saving a PDF")).resolves.toBeUndefined();++ fetchMock.mockResolvedValue(handshake("2.0"));+ await facade.triggerSearchForTrilium();+ await expect(facade.requireMinorVersion(1, "Saving a PDF")).rejects.toThrow(+ expect.objectContaining({ message: expect.stringContaining("Update the web clipper") }));+ });});it("looks up the note saved for a URL and reports it to the popup", async () => {diff --git a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts b/apps/web-clipper/entrypoints/background/trilium_server_facade.tsindex cde15ad2e5..4f2f82606e 100644--- a/apps/web-clipper/entrypoints/background/trilium_server_facade.ts+++ b/apps/web-clipper/entrypoints/background/trilium_server_facade.ts@@ -10,10 +10,12 @@ export type TriliumSearchStatus = {status: "found-desktop",port: number;url: string;+ protocolMinor: number;} | {status: "found-server",url: string;token: string;+ protocolMinor: number;} | {status: "version-mismatch";extensionMajor: number;@@ -23,6 +25,7 @@ export type TriliumSearchStatus = {/** The outcome of a finished search. */type SearchResult = Exclude<TriliumSearchStatus, { status: "searching" }>;type FoundStatus = Exclude<SearchResult, { status: "not-found" }>;+type CompatibleStatus = Exclude<FoundStatus, { status: "version-mismatch" }>;export type TriliumSearchNoteStatus = {status: "not-found",@@ -131,16 +134,19 @@ export default class TriliumServerFacade {const server = triliumServerUrl && authToken? handshake(triliumServerUrl, SERVER_TIMEOUT_MS, { Authorization: authToken })- .then((json) => json && checkVersion(json, {+ .then((json) => json && checkVersion(json, (protocolMinor) => ({status: "found-server",url: triliumServerUrl,- token: authToken- }))+ token: authToken,+ protocolMinor+ }))): Promise.resolve(null);const desktop = await handshake(desktopUrl, DESKTOP_TIMEOUT_MS);if (desktop) {- return checkVersion(desktop, { status: "found-desktop", port, url: desktopUrl });+ return checkVersion(desktop, (protocolMinor) => ({+ status: "found-desktop", port, url: desktopUrl, protocolMinor+ }));}return await server ?? { status: "not-found" };@@ -189,7 +195,19 @@ export default class TriliumServerFacade {return import.meta.env.DEV ? 37743 : 37840;}- async callService(method: string, path: string, body?: string | object) {+ /**+ * Rejects unless Trilium supports minor version `minor` of the protocol, which `feature` needs:+ * a minor version adds an API that older versions of Trilium do not have.+ */+ async requireMinorVersion(minor: number, feature: string) {+ const search = await this.waitForCompatibleTrilium();+ if (search.protocolMinor < minor) {+ throw new TriliumError("version-mismatch",+ `${feature} needs a newer version of Trilium. Update Trilium to the latest version.`);+ }+ }++ private async waitForCompatibleTrilium(): Promise<CompatibleStatus> {const search = await this.waitForTriliumSearch();if (search.status === "version-mismatch") {const { extensionMajor, triliumMajor } = search;@@ -197,6 +215,11 @@ export default class TriliumServerFacade {throw new TriliumError("version-mismatch", "This version of the web clipper does not "+ `work with this version of Trilium. Update ${outdated} to the latest version.`);}+ return search;+ }++ async callService(method: string, path: string, body?: string | object) {+ const search = await this.waitForCompatibleTrilium();let response: Response;try {@@ -262,14 +285,18 @@ async function handshake(url: string, timeoutMs: number, headers?: Record<string}}-function checkVersion(json: HandshakeResponse, found: FoundStatus): SearchResult {- const [ major = NaN ] = json.protocolVersion+/**+ * Reports a Trilium of another major version as a mismatch, or else `found` with the minor version,+ * which tells the features Trilium supports.+ */+function checkVersion(+ json: HandshakeResponse,+ found: (protocolMinor: number) => CompatibleStatus+): SearchResult {+ const [ major = NaN, minor = 0 ] = json.protocolVersion.split(".").map(chunk => parseInt(chunk, 10));- // minor version is intended to be used to dynamically limit features provided by extension- // if some specific Trilium API is not supported. So far not needed.-if (major !== PROTOCOL_VERSION_MAJOR) {return {status: "version-mismatch",@@ -277,7 +304,7 @@ function checkVersion(json: HandshakeResponse, found: FoundStatus): SearchResulttriliumMajor: major};}- return found;+ return found(minor);}function notFound() {diff --git a/apps/web-clipper/entrypoints/popup/main.tsx b/apps/web-clipper/entrypoints/popup/main.tsxindex bbe69a8a10..a5792a1c1a 100644--- a/apps/web-clipper/entrypoints/popup/main.tsx+++ b/apps/web-clipper/entrypoints/popup/main.tsx@@ -8,6 +8,7 @@ import Bookmark from "@boxicons/js/icons/Bookmark";import Calendar from "@boxicons/js/icons/Calendar";import Cog from "@boxicons/js/icons/Cog";import Crop from "@boxicons/js/icons/Crop";+import FileDetail from "@boxicons/js/icons/FileDetail";import Globe from "@boxicons/js/icons/Globe";import HelpCircle from "@boxicons/js/icons/HelpCircle";import Highlight from "@boxicons/js/icons/Highlight";@@ -27,7 +28,7 @@ import type { ComponentChildren } from "preact";import { Fragment, render } from "preact";import { useEffect, useRef, useState } from "preact/hooks";-import { extractPage, type PageVariant, type ReadablePage } from "@/utils";+import { extractPage, isPdfTab, type PageVariant, type ReadablePage } from "@/utils";import type { TriliumSearchNoteStatus, TriliumSearchStatus } from "../background/trilium_server_facade";@@ -71,13 +72,16 @@ interface TabContent {url?: string;/** What the page says about itself, which a note clip saves in its `#pageDescription` label. */description?: string;+ /** Whether the tab shows a PDF in the browser's viewer, which is saved as a file. */+ pdf: boolean;}/**- * What the card saves: the selection, the page (`clipType: "page"`), or a note about the page with a- * link to it (`clipType: "note"`), which the popup calls a bookmark.+ * What the card saves: the selection, the page (`clipType: "page"`), the PDF the tab shows as a file+ * (`clipType: "file"`), or a note about the page with a link to it (`clipType: "note"`), which the+ * popup calls a bookmark.*/-type ClipMode = "selection" | "page" | "note";+type ClipMode = "selection" | "page" | "pdf" | "note";/** What the user has chosen and typed in the card, kept by `Popup` so a reconnection does not lose it. */interface Draft {@@ -129,9 +133,11 @@ const PREVIEW_STYLE = `.embed-chip-detail { color: light-dark(#666, #bbb); }`;-const MODE_LABELS: Record<ClipMode, string> = { selection: "Selection", page: "Page", note: "Bookmark" };+const MODE_LABELS: Record<ClipMode, string> = { selection: "Selection", page: "Page", pdf: "PDF", note: "Bookmark" };/** The icon of the note each mode saves, as Trilium draws it from the note's `#clipType`. */-const MODE_ICONS: Record<ClipMode, IconDefinition> = { selection: Paperclip, page: Globe, note: Bookmark };+const MODE_ICONS: Record<ClipMode, IconDefinition> = {+ selection: Paperclip, page: Globe, pdf: FileDetail, note: Bookmark+};const VARIANT_LABELS: Record<PageVariant, string> = { article: "Article", wholePage: "Whole page" };@@ -145,6 +151,7 @@ const VARIANT_UNAVAILABLE: Record<PageVariant, string> = {const SAVE_BUTTONS: Record<ClipMode, { icon: IconDefinition, label: string, command: string, shortcut?: string }> = {selection: { icon: Highlight, label: "Save selection", command: "saveSelection" },page: { icon: Article, label: "Save page to Trilium", command: "saveWholePage" },+ pdf: { icon: FileDetail, label: "Save PDF to Trilium", command: "saveWholePage" },note: { icon: Bookmark, label: "Save bookmark", command: "", shortcut: "Ctrl+Enter" }};@@ -273,7 +280,7 @@ function CaptureActions({ disabled, shortcuts, draft, onDraftChange }: {const pageDisabledReason = disabledReason ?? (tab?.page === "inaccessible" ? UNREACHABLE_TITLE : undefined);let main: ComponentChildren;- if (tab?.page === "inaccessible") {+ if (tab?.page === "inaccessible" && !tab.pdf) {main = (<EmptyState icon={Lock}>{"The extension cannot access this page.\nIf it is a regular web page, reload it."}@@ -372,7 +379,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {/** Either reading: both carry the same title and labels. */const pageReading = page?.article ?? page?.wholePage ?? undefined;const selection = tab?.selection ?? undefined;- const modes = tab ? availableModes(!!page, selection) : [];+ const modes = tab ? availableModes(!!page, selection, tab.pdf) : [];const mode = chosenMode && modes.includes(chosenMode) ? chosenMode : modes[0];const clip = mode === "selection" ? selection : mode === "page" ? pageClip : undefined;const shownTitle = title ?? (pageReading ?? selection)?.title ?? tab?.title ?? "";@@ -424,9 +431,21 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {window.close();}+ function savePdf() {+ void sendMessage({+ name: "save-pdf",+ url: tab?.url,+ title: shownTitle.trim(),+ ...(savedDescription && { description: savedDescription })+ });+ window.close();+ }+let onSave: (() => void) | undefined;if (mode === "note") {onSave = () => void saveNote();+ } else if (mode === "pdf") {+ onSave = savePdf;} else if (clip) {onSave = () => saveClip(clip);}@@ -438,7 +457,7 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {}}- const pageUrl = mode === "note" ? tab?.url : clip?.pageUrl;+ const pageUrl = mode === "note" || mode === "pdf" ? tab?.url : clip?.pageUrl;const pageLabels = mode === "page" ? pageReading?.labels : undefined;const published = pageLabels?.publishedDate;const modified = pageLabels?.modifiedDate;@@ -477,30 +496,33 @@ function PagePreview({ tab, disabled, shortcuts, draft, onDraftChange }: {{mode === "note" && modes.length === 1 && (<div className="clip-hint">This page has nothing to save; save it as a bookmark.</div>)}+ {mode === "pdf" && <div className="clip-hint">The PDF is saved as a file in Trilium.</div>}<div className="page-body">{mode && (<div className={mode === "note" ? "page-fields bookmark" : "page-fields"}>- <div className="page-field">- <span- className="page-field-icon"- title={mode === "note"- ? "Your note about the page. It is saved as the content of the note."- : "Your note about the page. It is saved above the clipped content."}- >- <Icon icon={InfoCircle} />- </span>- <textarea- ref={textAreaRef}- className="note-text"- aria-label="Your note"- placeholder="Add a note about this page"- rows={1}- value={text}- onInput={(e) => onDraftChange({ ...draft, text: e.currentTarget.value })}- onKeyDown={saveOnCtrlEnter}- />- </div>+ {mode !== "pdf" && (+ <div className="page-field">+ <span+ className="page-field-icon"+ title={mode === "note"+ ? "Your note about the page. It is saved as the content of the note."+ : "Your note about the page. It is saved above the clipped content."}+ >+ <Icon icon={InfoCircle} />+ </span>+ <textarea+ ref={textAreaRef}+ className="note-text"+ aria-label="Your note"+ placeholder="Add a note about this page"+ rows={1}+ value={text}+ onInput={(e) => onDraftChange({ ...draft, text: e.currentTarget.value })}+ onKeyDown={saveOnCtrlEnter}+ />+ </div>+ )}<div className="page-field"><spanclassName="page-field-icon"@@ -631,11 +653,12 @@ function fitToContent(frame: HTMLIFrameElement) {}).observe(root);}-/** The modes the page offers, the default first: the selection, then the page, then a note. */-function availableModes(hasPage: boolean, selection: SelectedContent | undefined): ClipMode[] {+/** The modes the page offers, the default first: the selection, the page or the PDF, then a note. */+function availableModes(hasPage: boolean, selection: SelectedContent | undefined, pdf: boolean): ClipMode[] {const modes: ClipMode[] = [];if (selection) modes.push("selection");if (hasPage) modes.push("page");+ if (pdf) modes.push("pdf");modes.push("note");return modes;}@@ -694,12 +717,20 @@ function describeStatus(status: TriliumSearchStatus | undefined) {/** Asks the content script of the active tab for its readable page and its selection, together. */async function readActiveTab(): Promise<TabContent> {const [ tab ] = await browser.tabs.query({ active: true, currentWindow: true });- if (tab?.id === undefined) return { page: "inaccessible", selection: null };+ if (tab?.id === undefined) return { page: "inaccessible", selection: null, pdf: false };- const [ page, selection, description ] = await Promise.all([- readPage(tab.id), readSelection(tab.id), readDescription(tab.id)+ const [ pdf, page, selection, description ] = await Promise.all([+ isPdfTab(tab), readPage(tab.id), readSelection(tab.id), readDescription(tab.id)]);- return { page, selection, title: tab.title, url: tab.url, description };+ // The page around Chrome's PDF viewer has nothing to save but the PDF.+ return {+ page: pdf && typeof page === "object" ? "unreadable" : page,+ selection,+ title: tab.title,+ url: tab.url,+ description,+ };}/**diff --git a/apps/web-clipper/entrypoints/popup/popup.spec.tsx b/apps/web-clipper/entrypoints/popup/popup.spec.tsxindex c51bb44e26..be3fc2f661 100644--- a/apps/web-clipper/entrypoints/popup/popup.spec.tsx+++ b/apps/web-clipper/entrypoints/popup/popup.spec.tsx@@ -1,5 +1,6 @@import Bookmark from "@boxicons/js/icons/Bookmark";import Crop from "@boxicons/js/icons/Crop";+import FileDetail from "@boxicons/js/icons/FileDetail";import Globe from "@boxicons/js/icons/Globe";import Paperclip from "@boxicons/js/icons/Paperclip";import { readFileSync } from "fs";@@ -33,8 +34,12 @@ const PAGE = {const WHOLE_PAGE = { ...PAGE, content: `<nav>Menu</nav><p>Body</p><img src="i1">` };/** How `readable-page.js` reads the tab, by variant, as `browser.scripting.executeScript()` answers. */let pageReadings: Record<string, unknown> = {};-const executeScript = vi.fn(async ({ args }: { args?: [ string ] }): Promise<unknown> =>- args ? [ { result: pageReadings[args[0]] } ] : []);+/** Whether the tab shows a PDF, as the check run in the tab answers. */+let pdfTab = false;+const executeScript = vi.fn(async ({ args, func }: { args?: [ string ], func?: unknown }): Promise<unknown> => {+ if (args) return [ { result: pageReadings[args[0]] } ];+ return func ? [ { result: pdfTab } ] : [];+});const tabsQuery = vi.fn(async (): Promise<{ id?: number, title?: string, url?: string }[]> => [ { id: 7 } ]);const SELECTION = {title: "Page title",@@ -62,6 +67,7 @@ describe("popup", () => {selection = undefined;metadata = {};pageReadings = { article: PAGE, wholePage: WHOLE_PAGE };+ pdfTab = false;Object.assign(fakeBrowser.runtime, { sendMessage, openOptionsPage });Object.assign(fakeBrowser.commands, { getAll: getAllCommands });Object.assign(fakeBrowser.tabs, { query: tabsQuery, sendMessage: tabsSendMessage });@@ -741,6 +747,59 @@ describe("popup", () => {expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-whole-page", page: PAGE });});+ describe("a PDF", () => {+ const PDF_TAB = { id: 7, title: "Annual report", url: "https://example.com/files/report.pdf" };++ it("offers to save the PDF in Chrome's viewer as a file, or a bookmark of it", async () => {+ pdfTab = true;+ tabsQuery.mockResolvedValueOnce([ PDF_TAB ]);+ await rerender();++ expect(modes()).toEqual([ [ "PDF", "true" ], [ "Bookmark", "false" ] ]);+ expect(headingIcon()).toEqual(pathsOf(iconVariant(FileDetail).content));+ expect(container.querySelector<HTMLInputElement>(".page-title")?.value).toBe("Annual report");+ expect(container.querySelector(".page-meta")?.textContent).toBe("example.com");+ expect(container.querySelector(".clip-hint")?.textContent).toBe("The PDF is saved as a file in Trilium.");+ expect(container.querySelector(".note-text")).toBeNull();+ expect(container.querySelector(".page-author")).toBeNull();+ expect(container.querySelector(".page-content")).toBeNull();+ expect(placeholder()).toBeUndefined();+ expect(shortcutOf("Save PDF to Trilium").text).toBe("Alt+Shift+S");++ await type(".page-title", "Edited");+ await type(".page-description", " Key figures ");+ await click("Save PDF to Trilium");+ expect(sendMessage).toHaveBeenLastCalledWith({+ name: "save-pdf", url: PDF_TAB.url, title: "Edited", description: "Key figures"+ });+ expect(closeWindow).toHaveBeenCalledOnce();++ await click("Bookmark");+ expect(container.querySelector(".note-text")).not.toBeNull();+ expect(container.querySelector(".clip-hint")).toBeNull();+ });++ it("offers it in Firefox's viewer, where the website names the type, keeping out what needs the page", async () => {+ const fetchMock = vi.fn(async () => new Response(null, { headers: { "Content-Type": "application/pdf" } }));+ vi.stubGlobal("fetch", fetchMock);+ executeScript.mockRejectedValueOnce(new Error("Missing host permission for the tab"));+ executeScript.mockRejectedValueOnce(new Error("Missing host permission for the tab"));+ tabsSendMessage.mockRejectedValueOnce(new Error("Could not establish connection."));+ tabsSendMessage.mockRejectedValueOnce(new Error("Could not establish connection."));+ tabsQuery.mockResolvedValueOnce([ { ...PDF_TAB, title: "report.pdf" } ]);+ await rerender();++ expect(fetchMock).toHaveBeenCalledWith(PDF_TAB.url, { method: "HEAD", credentials: "include" });+ expect(container.querySelector(".capture-actions > .no-items")).toBeNull();+ expect(modes()).toEqual([ [ "PDF", "true" ], [ "Bookmark", "false" ] ]);+ expect(button("Crop screenshot")?.disabled).toBe(true);+ expect(button("All tabs in window")?.disabled).toBe(false);++ await click("Save PDF to Trilium");+ expect(sendMessage).toHaveBeenLastCalledWith({ name: "save-pdf", url: PDF_TAB.url, title: "report.pdf" });+ });+ });+it("renders itself into the page's root element", async () => {const root = document.createElement("div");root.id = "root";diff --git a/apps/web-clipper/utils.spec.ts b/apps/web-clipper/utils.spec.tsindex 3842c796e3..770bea5be2 100644--- a/apps/web-clipper/utils.spec.ts+++ b/apps/web-clipper/utils.spec.ts@@ -1,8 +1,8 @@import type { Window as HappyDOMWindow } from "happy-dom";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { fakeBrowser } from "wxt/testing/fake-browser";-import { createLink, extractPage, getPageLocationOrigin, randomString } from "./utils";+import { createLink, extractPage, getPageLocationOrigin, isPdfTab, randomString } from "./utils";describe("randomString", () => {it("returns alphanumeric strings of the requested length", () => {@@ -70,6 +70,69 @@ describe("extractPage", () => {});});++describe("isPdfTab", () => {+ const TAB = { id: 7, url: "https://example.com/report" };+ const executeScript = vi.fn(async ({ func }: { func: () => unknown }) => [ { result: func() } ]);+ const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => new Response(null));++ beforeEach(() => {+ Object.assign(fakeBrowser, { scripting: { executeScript } });+ vi.stubGlobal("fetch", fetchMock);+ });++ afterEach(() => {+ Reflect.deleteProperty(fakeBrowser, "scripting");+ document.body.innerHTML = "";+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("asks the page around Chrome's viewer what it shows", async () => {+ expect(await isPdfTab(TAB)).toBe(false);+ expect(executeScript).toHaveBeenCalledWith({ target: { tabId: 7 }, func: expect.any(Function) });++ document.body.innerHTML = `<embed type="application/pdf" src="https://example.com/a.pdf">`;+ expect(await isPdfTab(TAB)).toBe(false);+ document.body.innerHTML = `<embed type="application/pdf" src="about:blank">`;+ expect(await isPdfTab(TAB)).toBe(true);++ document.body.innerHTML = "";+ vi.spyOn(document, "contentType", "get").mockReturnValue("application/pdf");+ expect(await isPdfTab(TAB)).toBe(true);++ executeScript.mockResolvedValueOnce([]);+ expect(await isPdfTab(TAB)).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("asks the website where the browser runs no script, as in Firefox's viewer", async () => {+ executeScript.mockRejectedValue(new Error("Missing host permission for the tab"));+ const answer = (contentType?: string) => fetchMock.mockImplementation(async () =>+ new Response(null, { headers: contentType ? { "Content-Type": contentType } : {} }));++ answer("Application/PDF; qs=0.001");+ expect(await isPdfTab(TAB)).toBe(true);+ expect(fetchMock).toHaveBeenCalledWith(TAB.url, { method: "HEAD", credentials: "include" });++ answer("text/html");+ expect(await isPdfTab(TAB)).toBe(false);+ answer();+ expect(await isPdfTab(TAB)).toBe(false);+ fetchMock.mockRejectedValue(new TypeError("Failed to fetch"));+ expect(await isPdfTab(TAB)).toBe(false);+ });++ it("checks only web pages in a tab it can address", async () => {+ expect(await isPdfTab({ id: 7, url: "chrome://settings" })).toBe(false);+ expect(await isPdfTab({ id: 7 })).toBe(false);+ expect(await isPdfTab({ url: TAB.url })).toBe(false);+ expect(executeScript).not.toHaveBeenCalled();+ expect(fetchMock).not.toHaveBeenCalled();+ });+});+function setUrl(url: string) {(window as unknown as HappyDOMWindow).happyDOM.setURL(url);}diff --git a/apps/web-clipper/utils.ts b/apps/web-clipper/utils.tsindex a0ad71d661..91c79402b3 100644--- a/apps/web-clipper/utils.ts+++ b/apps/web-clipper/utils.ts@@ -36,6 +36,37 @@ export async function extractPage(tabId: number, variant: PageVariant): Promise<return (injection?.result ?? undefined) as ReadablePage | undefined;}+/**+ * Whether the tab shows a PDF in the browser's own viewer. Chrome runs scripts in the page around+ * its viewer; Firefox runs none in its viewer, so the website is asked for the type instead.+ */+export async function isPdfTab({ id, url }: { id?: number, url?: string }) {+ if (id === undefined || !url || !/^https?:\/\//.test(url)) return false;++ try {+ const [ injection ] = await browser.scripting.executeScript({ target: { tabId: id }, func: isPdfDocument });+ return injection?.result === true;+ } catch {+ try {+ const response = await fetch(url, { method: "HEAD", credentials: "include" });+ return isPdfType(response.headers.get("content-type"));+ } catch {+ return false;+ }+ }+}++/** Runs in the tab. Chrome's viewer is an `<embed>` of `about:blank` in the page at the PDF's address. */+function isPdfDocument() {+ return document.contentType === "application/pdf"+ || !!document.querySelector("embed[type='application/pdf'][src='about:blank']");+}++/** Whether a `Content-Type` header names a PDF, whatever its parameters. */+export function isPdfType(contentType: string | null) {+ return contentType?.split(";")[0]?.trim().toLowerCase() === "application/pdf";+}+export function randomString(len: number) {let text = "";const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex 1dc13028a1..a708d92a71 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -22,6 +22,7 @@ The extension is available from the official browser web stores:* select text and clip it with the right-click context menu* click on an image or link and save it through context menu* save whole page from the popup or context menu+* save a PDF that the browser shows, as a file note* save a screenshot of an area you select, of the visible part of the page or of the whole page, from either popup or context menu* create short text note from popup@@ -33,13 +34,14 @@ Clicking the extension's button in the browser toolbar opens its popup:* _Selection_, when text is selected on the page: _Save selection_ saves it into the note of that page's clippings, as the context menu does.* _Page_: _Save page to Trilium_ saves the page's text and images. A smaller switch at the top of the preview chooses how much of the page to keep: _Article_ keeps only the page's main text, without its menus, sidebars and footers, and _Whole page_ keeps everything the page shows. _Whole page_ is for pages that are not an article (such as a gallery or a page of cards), where _Article_ can leave out part of the content; the preview shows what each one keeps. _Article_ is unavailable on a page where Trilium finds no article. The author the page names shows under the description, marked by the <span class="tn-icon bx bx-user"></span> icon. It can be edited or cleared before saving, or written in when the page names none, and is saved in the `#pageAuthor` label of the note. When the page states when it was published, that date shows under the author, marked by the <span class="tn-icon bx bx-calendar"></span> icon, and is saved in the `#publishedDate` label of the note. When it states when it was last modified, that date shows below, marked by the <span class="tn-icon bx bx-history"></span> icon, and is saved in the `#modifiedDate` label.+ * _PDF_, when the tab shows a PDF in the browser's viewer: _Save PDF to Trilium_ downloads the PDF and saves it as a file note, which Trilium opens in its <a class="reference-link" href="../Note%20Types/File/PDFs.md">PDFs</a> viewer. Only the title and the description can be edited, since a file note has no text of its own for your note. The page's address is saved in the note's `#pageUrl` label and the PDF's file name in `#originalFileName`. Saving a PDF needs Trilium v0.107.0 or later.* _Bookmark_, always: there is no preview, and _Save bookmark_ saves a link to the page with your note as the content of the note. Left empty, the title stays the page's title.The box for your note, marked by the <span class="tn-icon bx bx-info-circle"></span> icon, has the cursor when the popup opens, so a note (such as why the page is worth keeping) can be typed right away. It grows with its text, and keeps it when switching between _Selection_, _Page_ and _Bookmark_. A note on a selection or a page is saved above the clipped content, in a _Note_ admonition. Left empty, nothing is added. <kbd>Ctrl</kbd>+<kbd>Enter</kbd> in any of the popup's fields saves, whichever is chosen.The description, marked by the <span class="tn-icon bx bx-align-left"></span> icon, comes from the page's `description` meta tag, or the one it gives social sites. It can be edited or cleared before saving, or written in when the page has none, and is saved in the `#pageDescription` label of the note. Clippings saved with the keyboard shortcuts or the context menu, screenshots and images included, get the description as the page gives it. Each clipping that brings a description updates the label. The description, the author and the dates are shown by clicking the _Web clip_ badge next to the title of the note (see <a class="reference-link" href="../Basic%20Concepts%20and%20Features/Notes/Note%20badges.md">Note badges</a>).- The popup opens on the selection if there is one, otherwise on _Page_, showing the article, or the whole page when the page has no article. On a page that shows nothing to save, it opens on _Bookmark_ and says so. The keyboard shortcuts and the context menu still save right away, without a preview: saving the whole page that way saves the article, or the whole page when the page has no article.+ The popup opens on the selection if there is one, otherwise on _Page_, showing the article, or the whole page when the page has no article. On a PDF, it opens on _PDF_. On a page that shows nothing to save, it opens on _Bookmark_ and says so. The keyboard shortcuts and the context menu still save right away, without a preview: saving the whole page that way saves the article, the whole page when the page has no article, or the PDF when the tab shows one.* Pages the extension cannot access (the browser's own pages, the extension stores, and pages that were open before the extension was installed until they are reloaded) cannot be saved or captured, so the popup says so in place of the preview, and only _Tabs_ remains available there.* Below the preview, a row of buttons offers the other actions: _Crop_ (a screenshot of an area you select), _Screenshot_ (of the visible part of the page), _Full page_ (a screenshot of the whole page) and _Tabs_ (saves the links of every tab in the current window as a list of <a class="reference-link" href="../Note%20Types/Text/Link%20Previews.md">Link Previews</a>, or of plain links when _Autogenerate link previews_ is turned off). Hovering over a button shows its full name and, if it has one, its keyboard shortcut.* _Full page_ scrolls through the page, takes a screenshot of each part and joins them into one image, then scrolls back to where the page was. The scrollbars are hidden while it does, so they do not appear in the image. Stay on the tab until it is saved: switching to another tab stops the screenshot. A header that stays at the top of the window appears once, at the top of the image, and headings that stick while scrolling appear where they are in the page. Other elements that stay in place while scrolling (such as cookie banners and chat buttons) are left out, while a background that fills the whole window repeats on every screen. A long page is saved as several images, one below the other in the note. A page longer than 100 screens is cut off there, and the message after saving says so.@@ -53,7 +55,7 @@ Trilium will save these clippings as a new child note under a "clipper inbox" noBy default, that's the <a class="reference-link" href="../Advanced%20Usage/Advanced%20Showcases/Day%20Notes.md">Day Notes</a> but you can override that by setting the [label](../Advanced%20Usage/Attributes.md) `clipperInbox`, on any other note.-Further clippings of the same kind from the same page are added to the note created by the first one, even on a later day or after that note was moved out of the clipper inbox. The note stays where it is and is not cloned back into the inbox.+Further clippings of the same kind from the same page are added to the note created by the first one, even on a later day or after that note was moved out of the clipper inbox. The note stays where it is and is not cloned back into the inbox. A PDF is the exception: each save creates a new file note, since the PDF can have changed since it was last saved.The icon of a clipped note shows what was saved:@@ -62,7 +64,7 @@ The icon of a clipped note shows what was saved:* <span class="tn-icon bx bx-bookmark"></span> a bookmark;* <span class="tn-icon bx bx-window-alt"></span> the tabs of a window.-The icon is derived from the note's `#clipType` label, so setting an `#iconClass` label on the note replaces it.+The icon is derived from the note's `#clipType` label, so setting an `#iconClass` label on the note replaces it. A saved PDF has the icon of a PDF file, like any other PDF in Trilium.## Embedded videos@@ -103,6 +105,7 @@ After each clipping, a notification in the corner of the page confirms that it w* Trilium was not found: start the desktop application, or check the server address and token in the extension's options.* The versions of Trilium and the extension are not compatible: update the one the message names.* Trilium rejected the request: the message includes the reason Trilium gave.+* A PDF could not be saved: Trilium is older than v0.107.0, the website refused to send the PDF again, or the PDF is larger than 100 MB. The extension downloads the PDF with the browser's cookies for that website, so a PDF behind a login can be saved while you are logged in.The extension downloads the images of a clipping itself, so that they are stored in Trilium together with the note. If some of them cannot be downloaded (for example because the website refuses the request), the clipping is still saved, and the notification says how many images are missing. Those images keep their address on the original website: Trilium tries to download them once more if _Download images automatically_ is enabled in <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Options.md">Options</a> → _Media_, and otherwise the note shows them from the website for as long as it serves them.diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex 7256e7a28d..570c4facd9 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -195,7 +195,7 @@ const BUILTIN_ATTRIBUTES = [{ type: "label", name: "clipperInbox", valueType: "boolean" },// Stamped by the web clipper on what it saves, recording which of its actions produced the note.{ type: "label", name: "clipType", valueType: "select", selectOptions: [- "clippings", "page", "note", "tabs"+ "clippings", "page", "note", "tabs", "file"] },{ type: "label", name: "sentFromSender", valueType: "boolean" },{ type: "label", name: "hideChildrenOverview", valueType: "boolean" },diff --git a/packages/trilium-core/src/services/app_info.spec.ts b/packages/trilium-core/src/services/app_info.spec.tsindex 1d3746e029..6f51c72703 100644--- a/packages/trilium-core/src/services/app_info.spec.ts+++ b/packages/trilium-core/src/services/app_info.spec.ts@@ -20,7 +20,7 @@ describe("app_info", () => {// These are protocol constants; bumping them is a deliberate,// breaking change, so they are locked here as a regression guard.expect(appInfo.syncVersion).toBe(40);- expect(appInfo.clipperProtocolVersion).toBe("1.0");+ expect(appInfo.clipperProtocolVersion).toBe("1.1");});it("reports a valid current UTC timestamp", () => {diff --git a/packages/trilium-core/src/services/app_info.ts b/packages/trilium-core/src/services/app_info.tsindex 846893bcff..15bb29f9d6 100644--- a/packages/trilium-core/src/services/app_info.ts+++ b/packages/trilium-core/src/services/app_info.ts@@ -4,7 +4,7 @@ import { AppInfo } from "@triliumnext/commons";import { getMaxMigrationVersion } from "../migrations/migrations.js";const SYNC_VERSION = 40;-const CLIPPER_PROTOCOL_VERSION = "1.0";+const CLIPPER_PROTOCOL_VERSION = "1.1";const appInfo: AppInfo = {appVersion: packageJson.version,