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
fix(clipper): keep embedded YouTube videos as link previews (closes #1449)
Elian Doraneec52f8c844e
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 8f4c2f8b29..363b1b5f19 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@@ -94,6 +94,12 @@note 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 clonedback into the inbox.</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+ title and thumbnail. As with a link preview added in the editor, the video+ plays only when clicked. Other embedded content (such as videos from other+ websites) is not saved.</p><h2>Keyboard shortcuts</h2><p>Keyboard shortcuts are available for most functions:</p><ul>diff --git a/apps/server/src/routes/api/clipper.spec.ts b/apps/server/src/routes/api/clipper.spec.tsindex 88e0c080c8..375149d165 100644--- a/apps/server/src/routes/api/clipper.spec.ts+++ b/apps/server/src/routes/api/clipper.spec.ts@@ -6,6 +6,13 @@ import clipperRoute, { processContent } from "./clipper";const { buildNote } = becca_easy_mocking;+const resolveYouTubePreview = vi.hoisted(() => vi.fn());++vi.mock("@triliumnext/core", async (importOriginal) => ({+ ...await importOriginal<typeof import("@triliumnext/core")>(),+ resolveYouTubePreview+}));+vi.mock("../../services/image.js", () => ({default: {saveImageToAttachment() {@@ -57,6 +64,42 @@ describe("processContent", () => {expect(processed).toStrictEqual(`<img src="OKZxZA3MonZJkwFcEhId" >`);}});++ it("turns embedded YouTube players into link previews", async () => {+ resolveYouTubePreview.mockImplementation(async (_noteId: string, url: string) => ({+ url,+ embedType: "youtube",+ title: "Tom & \"Jerry\"",+ siteName: "YouTube",+ image: "api/attachments/thumb/image/cover.jpg"+ }));++ const processed = await cls.init(() => processContent([], note, [+ `<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1"></iframe>`,+ `<iframe src="https://www.youtube-nocookie.com/embed/jNQXAC9IVRw"></iframe>`,+ `<iframe src="https://player.vimeo.com/video/76979871"></iframe>`+ ].join("")));++ expect(resolveYouTubePreview.mock.calls).toEqual([+ [ note.noteId, "https://www.youtube.com/watch?v=dQw4w9WgXcQ", "dQw4w9WgXcQ" ],+ [ note.noteId, "https://www.youtube.com/watch?v=jNQXAC9IVRw", "jNQXAC9IVRw" ]+ ]);+ expect(processed).toStrictEqual([ "dQw4w9WgXcQ", "jNQXAC9IVRw" ].map((id) =>+ `<section class="link-embed" data-url="https://www.youtube.com/watch?v=${id}"`+ + ` data-embed-type="youtube" data-title="Tom & "Jerry""`+ + ` data-site-name="YouTube" data-image="api/attachments/thumb/image/cover.jpg"></section>`+ ).join(""));+ });++ it("keeps a YouTube player as a bare link preview when its metadata cannot be stored", async () => {+ resolveYouTubePreview.mockRejectedValue(new Error("offline"));++ const processed = await cls.init(() => processContent([], note,+ `<p>Watch:</p><iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"></iframe>`));++ expect(processed).toStrictEqual(`<p>Watch:</p><section class="link-embed"`+ + ` data-url="https://www.youtube.com/watch?v=dQw4w9WgXcQ" data-embed-type="youtube"></section>`);+ });});// These exercise the route handlers against the real in-memory DB.diff --git a/apps/server/src/routes/api/clipper.ts b/apps/server/src/routes/api/clipper.tsindex 06a5e33745..c21e4d2b3c 100644--- a/apps/server/src/routes/api/clipper.ts+++ b/apps/server/src/routes/api/clipper.ts@@ -1,4 +1,5 @@-import { app_info as appInfo, attribute_formatter as attributeFormatter, attributes as attributeService, becca, type BNote, date_notes as dateNoteService, date_utils as dateUtils, getLog, note_service as noteService, sanitize, search as searchService, ValidationError, ws } from "@triliumnext/core";+import { escapeHtml, extractYouTubeVideoId, type LinkEmbedMetadata } from "@triliumnext/commons";+import { app_info as appInfo, attribute_formatter as attributeFormatter, attributes as attributeService, becca, type BNote, date_notes as dateNoteService, date_utils as dateUtils, getLog, note_service as noteService, resolveYouTubePreview, sanitize, search as searchService, ValidationError, ws } from "@triliumnext/core";import type { Request } from "express";import { parse } from "node-html-parser";import path from "path";@@ -143,7 +144,7 @@ function sanitizeLabelValue(value: string) {}export async function processContent(images: Image[], note: BNote, content: string) {- let rewrittenContent = sanitize.sanitizeHtml(content);+ let rewrittenContent = sanitize.sanitizeHtml(await replaceYouTubePlayers(note, content));if (images) {for (const { src, dataUrl, imageId } of images) {@@ -189,6 +190,53 @@ export async function processContent(images: Image[], note: BNote, content: strireturn rewrittenContent;}+/**+ * Replaces each embedded YouTube player with a link preview, which the sanitizer keeps and which+ * starts playing only when clicked. The sanitizer removes every other iframe.+ */+async function replaceYouTubePlayers(note: BNote, content: string) {+ if (typeof content !== "string" || !content.includes("<iframe")) {+ return content;+ }++ const dom = parse(content);+ const players = dom.querySelectorAll("iframe").flatMap((iframe) => {+ const videoId = extractYouTubeVideoId(iframe.getAttribute("src") ?? "");+ return videoId ? [ { iframe, videoId } ] : [];+ });++ await Promise.all(players.map(async ({ iframe, videoId }) => {+ const url = `https://www.youtube.com/watch?v=${videoId}`;+ let metadata: LinkEmbedMetadata;+ try {+ metadata = await resolveYouTubePreview(note.noteId, url, videoId);+ } catch (e) {+ getLog().info(`Could not resolve the preview of a clipped YouTube video: ${e}`);+ metadata = { url, embedType: "youtube" };+ }+ iframe.replaceWith(renderLinkEmbed(metadata));+ }));++ return dom.toString();+}++/** The markup the text editor stores for a block link preview. */+function renderLinkEmbed(metadata: LinkEmbedMetadata) {+ const attributes = ([+ [ "data-url", metadata.url ],+ [ "data-embed-type", metadata.embedType ],+ [ "data-title", metadata.title ],+ [ "data-description", metadata.description ],+ [ "data-favicon", metadata.favicon ],+ [ "data-site-name", metadata.siteName ],+ [ "data-image", metadata.image ]+ ] as const)+ .filter(([ , value ]) => value)+ .map(([ name, value ]) => ` ${name}="${escapeHtml(value ?? "")}"`)+ .join("");+ return `<section class="link-embed"${attributes}></section>`;+}+function openNote(req: Request<{ noteId: string }>) {if (utils.isElectron) {ws.sendMessageToAllClients({diff --git a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.mdindex fcf734344b..8907fb23c5 100644--- a/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md+++ b/docs/User Guide/User Guide/Installation & Setup/Web Clipper.md@@ -50,6 +50,10 @@ By default, that's the <a class="reference-link" href="../Advanced%20Usage/AdvaFurther 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.+## Embedded videos++A YouTube video embedded in a clipped page is saved as a <a class="reference-link" href="../Note%20Types/Text/Link%20Previews.md">Link Previews</a> embed, with the video's title and thumbnail. As with a link preview added in the editor, the video plays only when clicked. Other embedded content (such as videos from other websites) is not saved.+## Keyboard shortcutsKeyboard shortcuts are available for most functions:diff --git a/packages/commons/src/lib/link_embed.spec.ts b/packages/commons/src/lib/link_embed.spec.tsindex efb54f2b6d..6b2b93651c 100644--- a/packages/commons/src/lib/link_embed.spec.ts+++ b/packages/commons/src/lib/link_embed.spec.ts@@ -25,6 +25,7 @@ describe("extractYouTubeVideoId", () => {it("extracts the id from an embed URL", () => {expect(extractYouTubeVideoId("https://www.youtube.com/embed/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");+ expect(extractYouTubeVideoId("https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");});it("extracts the id from a shorts URL", () => {diff --git a/packages/commons/src/lib/link_embed.ts b/packages/commons/src/lib/link_embed.tsindex f782f873bf..c242e4211e 100644--- a/packages/commons/src/lib/link_embed.ts+++ b/packages/commons/src/lib/link_embed.ts@@ -1,6 +1,6 @@import { fnv1a } from "./utils.js";-export const YOUTUBE_REGEX = /(?:youtube\.com\/watch\?[^\s#]*v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/;+export const YOUTUBE_REGEX = /(?:youtube\.com\/watch\?[^\s#]*v=|youtu\.be\/|youtube(?:-nocookie)?\.com\/embed\/|youtube\.com\/shorts\/)([a-zA-Z0-9_-]{11})/;export function extractYouTubeVideoId(url: string): string | null {const match = url.match(YOUTUBE_REGEX);diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex d1d80c5059..75f41beb0a 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -157,6 +157,7 @@ export type { RequestProvider, ExecOpts, CookieJar, FetchApiOpts, FetchResourceOexport type * from "./meta";export type { QueryString, QueryValue, Request, RequestHeaders, Response } from "./http_interface";export * as routeHelpers from "./routes/helpers";+export { resolveYouTubePreview } from "./routes/api/link_embed";export { getZipProvider, type ZipArchive, type ZipProvider } from "./services/zip_provider";export { default as zipImportService } from "./services/import/zip";diff --git a/packages/trilium-core/src/routes/api/link_embed.ts b/packages/trilium-core/src/routes/api/link_embed.tsindex a4c6eb60f1..2a154a3f58 100644--- a/packages/trilium-core/src/routes/api/link_embed.ts+++ b/packages/trilium-core/src/routes/api/link_embed.ts@@ -586,7 +586,7 @@ async function getMetadata(req: Request) {// A YouTube link stays resolved even when oEmbed is unreachable: the player embeds from the// video ID alone, so the preview is worth showing with or without the title and channel.if (videoId) {- return await storePictures(noteIdParam, url, await fetchYouTubeMetadata(url, videoId));+ return await resolveYouTubePreview(noteIdParam, url, videoId);}try {@@ -617,6 +617,14 @@ async function getMetadata(req: Request) {}}+/**+ * The metadata of a preview for a YouTube video, with its thumbnail and favicon stored as attachments+ * of the note `noteId`.+ */+export async function resolveYouTubePreview(noteId: string, url: string, videoId: string) {+ return await storePictures(noteId, url, await fetchYouTubeMetadata(url, videoId));+}+/*** The degraded result for a URL whose page told us nothing: everything the caller gets back is* derived from the URL itself. Flagged so the caller can keep a plain link instead of rendering a