Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

feat(web): add on-demand video preservation (#3183)

Mohamed Bassem1b97a83e9131
diff --git a/apps/web/components/dashboard/bookmarks/BookmarkOptions.tsx b/apps/web/components/dashboard/bookmarks/BookmarkOptions.tsx
index 1ed6a5ac..4d16df26 100644
--- a/apps/web/components/dashboard/bookmarks/BookmarkOptions.tsx
+++ b/apps/web/components/dashboard/bookmarks/BookmarkOptions.tsx
@@ -23,6 +23,7 @@ import {
Download,
FileDown,
FileText,
+ FileVideo,
ImagePlus,
Link,
List,
@@ -47,6 +48,7 @@ import {
import { useBookmarkGridContext } from "@karakeep/shared-react/hooks/bookmark-grid-context";
import { useBookmarkListContext } from "@karakeep/shared-react/hooks/bookmark-list-context";
import {
+ usePreserveBookmarkVideo,
useRecrawlBookmark,
useUpdateBookmark,
} from "@karakeep/shared-react/hooks/bookmarks";
@@ -101,7 +103,8 @@ export default function BookmarkOptions({
const linkId = bookmark.id;
const { data: session } = useSession();
- const demoMode = !!useClientConfig().demoMode;
+ const clientConfig = useClientConfig();
+ const demoMode = !!clientConfig.demoMode;
// Check if the current user owns this bookmark
const isOwner = session?.user?.id === bookmark.userId;
@@ -214,6 +217,13 @@ export default function BookmarkOptions({
onError,
});
+ const preserveVideoMutator = usePreserveBookmarkVideo({
+ onSuccess: () => {
+ toast.success(t("toasts.bookmarks.preserve_video"));
+ },
+ onError,
+ });
+
const removeFromListMutator = useRemoveBookmarkFromList({
onSuccess: () => {
toast.success(t("toasts.bookmarks.delete_from_list"));
@@ -400,6 +410,16 @@ export default function BookmarkOptions({
});
},
},
+ {
+ id: "preserve-video",
+ title: t("actions.preserve_video"),
+ icon: <FileVideo className="size-4" />,
+ visible: clientConfig.crawler.videoDownloadOnDemand,
+ disabled: demoMode,
+ onClick: () => {
+ preserveVideoMutator.mutate({ bookmarkId: bookmark.id });
+ },
+ },
{
id: "download-full-page-archive",
title: t("actions.download_full_page_archive_file"),
diff --git a/apps/web/lib/i18n/locales/en/translation.json b/apps/web/lib/i18n/locales/en/translation.json
index cfd0ded5..19ef81fb 100644
--- a/apps/web/lib/i18n/locales/en/translation.json
+++ b/apps/web/lib/i18n/locales/en/translation.json
@@ -77,6 +77,7 @@
"preserve_offline_archive": "Preserve Offline Archive",
"download_full_page_archive_file": "Download Archive File",
"preserve_as_pdf": "Preserve as PDF",
+ "preserve_video": "Preserve Video",
"download_pdf_file": "Download PDF File",
"edit_tags": "Edit Tags",
"edit_notes": "Edit Notes",
@@ -1129,6 +1130,7 @@
"refetch": "Re-fetch has been enqueued!",
"full_page_archive": "Full Page Archive creation has been triggered",
"preserve_pdf": "PDF preservation has been triggered",
+ "preserve_video": "Video download has been triggered",
"delete_from_list": "The bookmark has been deleted from the list",
"clipboard_copied": "Link has been added to your clipboard!",
"update_banner": "Banner has been updated!",
diff --git a/apps/workers/workers/videoWorker.ts b/apps/workers/workers/videoWorker.ts
index 32723b88..08ad2fdf 100644
--- a/apps/workers/workers/videoWorker.ts
+++ b/apps/workers/workers/videoWorker.ts
@@ -100,7 +100,7 @@ function prepareYtDlpArguments(
async function runWorker(job: DequeuedJob<ZVideoRequest>) {
const jobId = job.id;
- const { bookmarkId } = job.data;
+ const { bookmarkId, onDemand } = job.data;
addLogFields<"videoWorker.run">({ "bookmark.id": bookmarkId });
const {
@@ -109,7 +109,10 @@ async function runWorker(job: DequeuedJob<ZVideoRequest>) {
videoAssetId: oldVideoAssetId,
} = await getBookmarkDetails(bookmarkId);
- if (!serverConfig.crawler.downloadVideo) {
+ const downloadEnabled = onDemand
+ ? serverConfig.crawler.downloadVideoOnDemand
+ : serverConfig.crawler.downloadVideo;
+ if (!downloadEnabled) {
logger.info(
`[VideoCrawler][${jobId}] Skipping video download from "${url}", because it is disabled in the config.`,
);
diff --git a/docs/docs/03-configuration/01-environment-variables.md b/docs/docs/03-configuration/01-environment-variables.md
index fca42f40..c217c25c 100644
--- a/docs/docs/03-configuration/01-environment-variables.md
+++ b/docs/docs/03-configuration/01-environment-variables.md
@@ -157,6 +157,7 @@ Either `OPENAI_API_KEY` or `OLLAMA_BASE_URL` need to be set for automatic taggin
| CRAWLER_VIDEO_DOWNLOAD | No | false | Whether to download videos from the page or not (using yt-dlp) |
| CRAWLER_VIDEO_DOWNLOAD_MAX_SIZE | No | 50 | The maximum file size for the downloaded video. The quality will be chosen accordingly. Use -1 to disable the limit. |
| CRAWLER_VIDEO_DOWNLOAD_TIMEOUT_SEC | No | 600 | How long to wait for the video download to finish |
+| CRAWLER_VIDEO_DOWNLOAD_ON_DEMAND | No | Value of `CRAWLER_VIDEO_DOWNLOAD` | Whether users can explicitly download the video of a single link bookmark (using yt-dlp) through the "Preserve Video" action. Defaults to the value of `CRAWLER_VIDEO_DOWNLOAD`, but can be set independently (e.g. enable on-demand downloads while keeping automatic downloads off). The size and timeout limits above still apply. |
| CRAWLER_ENABLE_ADBLOCKER | No | true | Whether to enable an adblocker in the crawler or not. If you're facing troubles downloading the adblocking lists on worker startup, you can disable this. |
| CRAWLER_ENABLE_AUTOCONSENT | No | true | Whether to automatically opt out of supported consent dialogs during browser-based crawls. When a consent management platform is detected, the crawler waits up to 3 seconds for the opt-out to finish before extracting content and capturing page assets. Set to `false` to disable this behavior. |
| CRAWLER_YTDLP_ARGS | No | [] | Include additional yt-dlp arguments to be passed at crawl time separated by %%: https://github.com/yt-dlp/yt-dlp?tab=readme-ov-file#general-options |
diff --git a/packages/shared-react/hooks/bookmarks.ts b/packages/shared-react/hooks/bookmarks.ts
index 09743f11..da066aea 100644
--- a/packages/shared-react/hooks/bookmarks.ts
+++ b/packages/shared-react/hooks/bookmarks.ts
@@ -173,6 +173,15 @@ export function useRecrawlBookmark(
);
}
+export function usePreserveBookmarkVideo(
+ opts?: Parameters<
+ TRPCApi["bookmarks"]["preserveVideo"]["mutationOptions"]
+ >[0],
+) {
+ const api = useTRPC();
+ return useMutation(api.bookmarks.preserveVideo.mutationOptions(opts));
+}
+
export function useUpdateBookmarkTags(
opts?: Parameters<TRPCApi["bookmarks"]["updateTags"]["mutationOptions"]>[0],
) {
diff --git a/packages/shared-react/providers/client-config-provider.tsx b/packages/shared-react/providers/client-config-provider.tsx
index 49b1a290..d38bd749 100644
--- a/packages/shared-react/providers/client-config-provider.tsx
+++ b/packages/shared-react/providers/client-config-provider.tsx
@@ -26,6 +26,9 @@ export const DEFAULT_CLIENT_CONFIG: ZClientConfig = {
stripe: {
isConfigured: false,
},
+ crawler: {
+ videoDownloadOnDemand: false,
+ },
legal: {},
disableNewReleaseCheck: true,
};
@@ -65,6 +68,10 @@ export function ClientConfigProvider({
...DEFAULT_CLIENT_CONFIG.stripe,
...value?.stripe,
},
+ crawler: {
+ ...DEFAULT_CLIENT_CONFIG.crawler,
+ ...value?.crawler,
+ },
legal: {
...DEFAULT_CLIENT_CONFIG.legal,
...value?.legal,
diff --git a/packages/shared-server/src/queues.ts b/packages/shared-server/src/queues.ts
index f4078e34..95b288ce 100644
--- a/packages/shared-server/src/queues.ts
+++ b/packages/shared-server/src/queues.ts
@@ -271,6 +271,9 @@ export async function triggerSearchReindex(
export const zvideoRequestSchema = z.object({
bookmarkId: z.string(),
url: z.string(),
+ // Explicitly requested by the user (e.g. "Preserve Video"), as opposed to
+ // the automatic download after a crawl.
+ onDemand: z.boolean().optional(),
});
export type ZVideoRequest = z.infer<typeof zvideoRequestSchema>;
diff --git a/packages/shared/config.ts b/packages/shared/config.ts
index f23c1566..4a5048d1 100644
--- a/packages/shared/config.ts
+++ b/packages/shared/config.ts
@@ -153,6 +153,7 @@ const allEnv = z.object({
CRAWLER_VIDEO_DOWNLOAD: stringBool("false"),
CRAWLER_VIDEO_DOWNLOAD_MAX_SIZE: z.coerce.number().default(50),
CRAWLER_VIDEO_DOWNLOAD_TIMEOUT_SEC: z.coerce.number().default(10 * 60),
+ CRAWLER_VIDEO_DOWNLOAD_ON_DEMAND: optionalStringBool(),
CRAWLER_ENABLE_ADBLOCKER: stringBool("true"),
CRAWLER_ENABLE_AUTOCONSENT: stringBool("true"),
CRAWLER_YTDLP_ARGS: z
@@ -427,6 +428,8 @@ const serverConfigSchema = allEnv.transform((val, ctx) => {
downloadVideo: val.CRAWLER_VIDEO_DOWNLOAD,
maxVideoDownloadSize: val.CRAWLER_VIDEO_DOWNLOAD_MAX_SIZE,
downloadVideoTimeout: val.CRAWLER_VIDEO_DOWNLOAD_TIMEOUT_SEC,
+ downloadVideoOnDemand:
+ val.CRAWLER_VIDEO_DOWNLOAD_ON_DEMAND ?? val.CRAWLER_VIDEO_DOWNLOAD,
enableAdblocker: val.CRAWLER_ENABLE_ADBLOCKER,
enableAutoconsent: val.CRAWLER_ENABLE_AUTOCONSENT,
ytDlpArguments: val.CRAWLER_YTDLP_ARGS,
@@ -642,6 +645,9 @@ export const clientConfig = {
stripe: {
isConfigured: serverConfig.stripe.isConfigured,
},
+ crawler: {
+ videoDownloadOnDemand: serverConfig.crawler.downloadVideoOnDemand,
+ },
legal: {
termsOfServiceUrl: serverConfig.legal.termsOfServiceUrl,
privacyPolicyUrl: serverConfig.legal.privacyPolicyUrl,
diff --git a/packages/shared/types/config.ts b/packages/shared/types/config.ts
index de245b2e..8305e9c6 100644
--- a/packages/shared/types/config.ts
+++ b/packages/shared/types/config.ts
@@ -34,6 +34,9 @@ export const zClientConfigSchema = z.object({
stripe: z.object({
isConfigured: z.boolean(),
}),
+ crawler: z.object({
+ videoDownloadOnDemand: z.boolean(),
+ }),
legal: z.object({
termsOfServiceUrl: z.string().optional(),
privacyPolicyUrl: z.string().optional(),
diff --git a/packages/trpc/routers/bookmarks.test.ts b/packages/trpc/routers/bookmarks.test.ts
index 233f54fd..4cf3caa1 100644
--- a/packages/trpc/routers/bookmarks.test.ts
+++ b/packages/trpc/routers/bookmarks.test.ts
@@ -9,6 +9,7 @@ import {
users,
} from "@karakeep/db/schema";
import * as sharedServer from "@karakeep/shared-server";
+import serverConfig from "@karakeep/shared/config";
import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";
import { WebhooksService } from "../models/webhooks.service";
@@ -1140,6 +1141,73 @@ describe("Bookmark Routes", () => {
expect(emptyResult.bookmarks.length).toEqual(0);
});
+ describe("preserveVideo", () => {
+ test<CustomTestContext>("is rejected when on-demand video downloads are disabled", async ({
+ apiCallers,
+ }) => {
+ const api = apiCallers[0].bookmarks;
+ const bookmark = await api.createBookmark({
+ url: "https://youtube.com/watch?v=abc",
+ type: BookmarkTypes.LINK,
+ });
+ const enqueueMock = getTestQueueMocks().videoWorkerEnqueue;
+ enqueueMock.mockClear();
+
+ const originalValue = serverConfig.crawler.downloadVideoOnDemand;
+ serverConfig.crawler.downloadVideoOnDemand = false;
+ try {
+ await expect(
+ api.preserveVideo({ bookmarkId: bookmark.id }),
+ ).rejects.toThrow(/disabled/);
+ } finally {
+ serverConfig.crawler.downloadVideoOnDemand = originalValue;
+ }
+ expect(enqueueMock).not.toHaveBeenCalled();
+ });
+
+ test<CustomTestContext>("enqueues an on-demand video download for links", async ({
+ apiCallers,
+ }) => {
+ const api = apiCallers[0].bookmarks;
+ const bookmark = await api.createBookmark({
+ url: "https://youtube.com/watch?v=abc",
+ type: BookmarkTypes.LINK,
+ });
+ const textBookmark = await api.createBookmark({
+ text: "hello",
+ type: BookmarkTypes.TEXT,
+ });
+ const enqueueMock = getTestQueueMocks().videoWorkerEnqueue;
+ enqueueMock.mockClear();
+
+ const originalValue = serverConfig.crawler.downloadVideoOnDemand;
+ serverConfig.crawler.downloadVideoOnDemand = true;
+ try {
+ await api.preserveVideo({ bookmarkId: bookmark.id });
+ expect(enqueueMock).toHaveBeenCalledWith(
+ {
+ bookmarkId: bookmark.id,
+ url: "https://youtube.com/watch?v=abc",
+ onDemand: true,
+ },
+ expect.objectContaining({ groupId: expect.any(String) }),
+ );
+
+ await expect(
+ api.preserveVideo({ bookmarkId: textBookmark.id }),
+ ).rejects.toThrow(/link bookmarks/);
+
+ // Users can't trigger downloads for bookmarks they don't own
+ await expect(
+ apiCallers[1].bookmarks.preserveVideo({ bookmarkId: bookmark.id }),
+ ).rejects.toThrow();
+ } finally {
+ serverConfig.crawler.downloadVideoOnDemand = originalValue;
+ }
+ expect(enqueueMock).toHaveBeenCalledTimes(1);
+ });
+ });
+
describe("Bookmark Quotas", () => {
test<CustomTestContext>("create bookmark with no quota (unlimited)", async ({
apiCallers,
diff --git a/packages/trpc/routers/bookmarks.ts b/packages/trpc/routers/bookmarks.ts
index 058c7f37..3ab5b42b 100644
--- a/packages/trpc/routers/bookmarks.ts
+++ b/packages/trpc/routers/bookmarks.ts
@@ -28,6 +28,7 @@ import {
QuotaService,
SUPPORTED_BOOKMARK_ASSET_TYPES,
triggerSearchReindex,
+ VideoWorkerQueue,
} from "@karakeep/shared-server";
import serverConfig from "@karakeep/shared/config";
import {
@@ -848,6 +849,49 @@ export const bookmarksAppRouter = router({
.set({ crawlStatus: "pending" })
.where(eq(bookmarkLinks.id, input.bookmarkId));
}),
+ preserveVideo: bookmarksProcedure
+ .use(
+ createRateLimitMiddleware({
+ name: "bookmarks.preserveVideo",
+ windowMs: 30 * 60 * 1000,
+ maxRequests: 50,
+ }),
+ )
+ .input(
+ z.object({
+ bookmarkId: z.string(),
+ }),
+ )
+ .use(ensureBookmarkOwnership)
+ .mutation(async ({ input, ctx }) => {
+ if (!serverConfig.crawler.downloadVideoOnDemand) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "On-demand video downloads are disabled on this server",
+ });
+ }
+ const link = await ctx.db.query.bookmarkLinks.findFirst({
+ where: eq(bookmarkLinks.id, input.bookmarkId),
+ columns: { url: true },
+ });
+ if (!link) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Videos can only be preserved for link bookmarks",
+ });
+ }
+ await VideoWorkerQueue.enqueue(
+ {
+ bookmarkId: input.bookmarkId,
+ url: link.url,
+ onDemand: true,
+ },
+ {
+ groupId: ctx.user.id,
+ idempotencyKey: `video:${input.bookmarkId}`,
+ },
+ );
+ }),
updateReadingProgress: bookmarksProcedure
.input(
z.object({
diff --git a/packages/trpc/testUtils.ts b/packages/trpc/testUtils.ts
index 8b7a4598..6354ef20 100644
--- a/packages/trpc/testUtils.ts
+++ b/packages/trpc/testUtils.ts
@@ -18,6 +18,7 @@ const testQueueMocks = vi.hoisted(() => ({
ruleEngineEnqueue: vi.fn(),
searchIndexingEnqueue: vi.fn(),
triggerSearchReindex: vi.fn(),
+ videoWorkerEnqueue: vi.fn(),
}));
export function getTestQueueMocks() {
@@ -169,6 +170,9 @@ export function defaultBeforeEach(seedDB = true) {
RuleEngineQueue: {
enqueue: testQueueMocks.ruleEngineEnqueue,
},
+ VideoWorkerQueue: {
+ enqueue: testQueueMocks.videoWorkerEnqueue,
+ },
triggerSearchReindex: testQueueMocks.triggerSearchReindex,
};
});