Skip to content

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

feat(mobile): add offline download preferences and manager (#3176)

Mohamed Bassem1846890d7667
diff --git a/apps/mobile/components/bookmarks/useOfflineAvailability.ts b/apps/mobile/components/bookmarks/useOfflineAvailability.ts
index e54f096b..034e8f08 100644
--- a/apps/mobile/components/bookmarks/useOfflineAvailability.ts
+++ b/apps/mobile/components/bookmarks/useOfflineAvailability.ts
@@ -5,6 +5,10 @@ import { onlineManager, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@karakeep/shared-react/trpc";
import { useToast } from "../ui/Toast";
+import {
+ excludeFromOfflineDownloads,
+ includeInOfflineDownloads,
+} from "../../lib/offlineDownloadPrefs";
import {
getOfflineLibraryScope,
OFFLINE_LIBRARY_SCHEMA_VERSION,
@@ -55,6 +59,7 @@ export function useOfflineAvailability(bookmarkId: string) {
savedAt: Date.now(),
bookmark,
});
+ includeInOfflineDownloads(scope, bookmarkId);
toast({
message: isAvailableOffline
? "Offline copy updated"
@@ -77,13 +82,14 @@ export function useOfflineAvailability(bookmarkId: string) {
const confirmRemove = () => {
Alert.alert(
"Remove offline copy?",
- "The article may remain temporarily cached, but it will no longer be kept for offline reading.",
+ "It will no longer be kept for offline reading, and automatic downloads will skip it. The article may remain temporarily cached.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Remove",
style: "destructive",
onPress: () => {
+ excludeFromOfflineDownloads(scope, bookmarkId);
removeOfflineArticle(scope, bookmarkId);
toast({ message: "Offline copy removed" });
},
diff --git a/apps/mobile/lib/offlineDownloadPrefs.ts b/apps/mobile/lib/offlineDownloadPrefs.ts
new file mode 100644
index 00000000..db23eb2d
--- /dev/null
+++ b/apps/mobile/lib/offlineDownloadPrefs.ts
@@ -0,0 +1,140 @@
+import { useMemo } from "react";
+import { createMMKV, useMMKVString } from "react-native-mmkv";
+import { z } from "zod";
+
+export const RECENT_LIMIT_OPTIONS = [50, 100, 200, 500] as const;
+export const BUDGET_MB_OPTIONS = [100, 250, 500, 1024, 2048] as const;
+
+const zOfflineDownloadPrefs = z.object({
+ recentEnabled: z.boolean().default(false),
+ recentLimit: z.number().int().positive().default(200),
+ listIds: z.array(z.string()).default([]),
+ budgetMb: z.number().positive().default(500),
+ wifiOnly: z.boolean().default(true),
+ // Articles the user removed by hand. Automatic downloads must not bring them
+ // back; saving one manually lifts the exclusion.
+ excludedIds: z.array(z.string()).default([]),
+});
+
+export type OfflineDownloadPrefs = z.infer<typeof zOfflineDownloadPrefs>;
+
+// Download prefs and status live apart from the library so that wiping the
+// articles never loses the user's choices (and vice versa).
+export const offlineDownloadStorage = createMMKV({
+ id: "karakeep-offline-downloads",
+});
+
+function prefsKey(scope: string) {
+ return `prefs:${encodeURIComponent(scope)}`;
+}
+
+export function parseOfflineDownloadPrefs(
+ raw: string | undefined,
+): OfflineDownloadPrefs {
+ let value: unknown = {};
+ if (raw) {
+ try {
+ value = JSON.parse(raw);
+ } catch {
+ value = {};
+ }
+ }
+ const result = zOfflineDownloadPrefs.safeParse(value);
+ return result.success ? result.data : zOfflineDownloadPrefs.parse({});
+}
+
+export function getOfflineDownloadPrefs(scope: string) {
+ return parseOfflineDownloadPrefs(
+ offlineDownloadStorage.getString(prefsKey(scope)),
+ );
+}
+
+export function updateOfflineDownloadPrefs(
+ scope: string,
+ update: (current: OfflineDownloadPrefs) => OfflineDownloadPrefs,
+) {
+ offlineDownloadStorage.set(
+ prefsKey(scope),
+ JSON.stringify(update(getOfflineDownloadPrefs(scope))),
+ );
+}
+
+export function isAutoDownloadEnabled(prefs: OfflineDownloadPrefs) {
+ return prefs.recentEnabled || prefs.listIds.length > 0;
+}
+
+export function setListKeptOffline(
+ scope: string,
+ listId: string,
+ keep: boolean,
+) {
+ updateOfflineDownloadPrefs(scope, (prefs) => ({
+ ...prefs,
+ listIds: keep
+ ? [...new Set([...prefs.listIds, listId])]
+ : prefs.listIds.filter((id) => id !== listId),
+ }));
+}
+
+export function excludeFromOfflineDownloads(scope: string, bookmarkId: string) {
+ updateOfflineDownloadPrefs(scope, (prefs) =>
+ prefs.excludedIds.includes(bookmarkId)
+ ? prefs
+ : { ...prefs, excludedIds: [...prefs.excludedIds, bookmarkId] },
+ );
+}
+
+export function includeInOfflineDownloads(scope: string, bookmarkId: string) {
+ const prefs = getOfflineDownloadPrefs(scope);
+ if (prefs.excludedIds.includes(bookmarkId)) {
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ excludedIds: current.excludedIds.filter((id) => id !== bookmarkId),
+ }));
+ }
+}
+
+// Mirrors clearOfflineLibrary: logging out forgets every account's downloads.
+export function clearOfflineDownloadStorage() {
+ offlineDownloadStorage.clearAll();
+}
+
+// Everything except exclusions: those only ever shrink the selection, and the
+// download pass itself rewrites them.
+function selectionSignature(prefs: OfflineDownloadPrefs) {
+ return JSON.stringify([
+ prefs.recentEnabled,
+ prefs.recentLimit,
+ prefs.listIds,
+ prefs.budgetMb,
+ prefs.wifiOnly,
+ ]);
+}
+
+/** Calls `onChange` when a change affects what should be downloaded, or how. */
+export function subscribeToOfflineDownloadPrefs(
+ scope: string,
+ onChange: (prefs: OfflineDownloadPrefs) => void,
+) {
+ const key = prefsKey(scope);
+ let signature = selectionSignature(getOfflineDownloadPrefs(scope));
+ const listener = offlineDownloadStorage.addOnValueChangedListener(
+ (changedKey) => {
+ if (changedKey !== key) {
+ return;
+ }
+ const prefs = getOfflineDownloadPrefs(scope);
+ const next = selectionSignature(prefs);
+ if (next !== signature) {
+ signature = next;
+ onChange(prefs);
+ }
+ },
+ );
+ return () => listener.remove();
+}
+
+export function useOfflineDownloadPrefs(scope: string) {
+ const [raw] = useMMKVString(prefsKey(scope), offlineDownloadStorage);
+ return useMemo(() => parseOfflineDownloadPrefs(raw), [raw]);
+}
diff --git a/apps/mobile/lib/offlineSync.test.ts b/apps/mobile/lib/offlineSync.test.ts
new file mode 100644
index 00000000..1c0de41f
--- /dev/null
+++ b/apps/mobile/lib/offlineSync.test.ts
@@ -0,0 +1,420 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { ZBookmark } from "@karakeep/shared/types/bookmarks";
+
+import { assetBookmark, linkBookmark } from "./testing/bookmarks";
+
+interface Page {
+ bookmarks: ZBookmark[];
+ nextCursor: { createdAt: Date; id: string } | null;
+}
+
+interface TestState {
+ settings: {
+ address: string;
+ apiKey: string | undefined;
+ apiKeyId: string;
+ customHeaders: Record<string, string>;
+ };
+ network: { isConnected: boolean; isInternetReachable: boolean; type: string };
+ lists: Map<string, ZBookmark[] | Error>;
+ recent: ZBookmark[];
+ repeatCursor: boolean;
+ pageRequests: { listId?: string; archived?: boolean }[];
+ contentRequests: string[];
+ onContentRequest: (() => void) | undefined;
+}
+
+const state = vi.hoisted((): TestState => ({
+ settings: {
+ address: "https://keep.example.com",
+ apiKey: "key",
+ apiKeyId: "key-id",
+ customHeaders: {},
+ },
+ network: { isConnected: true, isInternetReachable: true, type: "WIFI" },
+ lists: new Map(),
+ recent: [],
+ repeatCursor: false,
+ pageRequests: [],
+ contentRequests: [],
+ onContentRequest: undefined,
+}));
+
+vi.mock("react-native-mmkv", async () => {
+ const { createFakeMMKV } = await import("./testing/fakeMmkv");
+ return { createMMKV: createFakeMMKV, useMMKVString: vi.fn() };
+});
+
+vi.mock("expo-network", () => ({
+ getNetworkStateAsync: async () => state.network,
+ NetworkStateType: {
+ WIFI: "WIFI",
+ ETHERNET: "ETHERNET",
+ CELLULAR: "CELLULAR",
+ },
+}));
+
+vi.mock("expo/fetch", () => ({
+ fetch: () => Promise.reject(new Error("no images in these tests")),
+}));
+
+vi.mock("./settings", () => ({
+ useSettings: {
+ getState: () => ({ settings: { settings: state.settings } }),
+ },
+}));
+
+function page(
+ all: ZBookmark[],
+ cursor: { id: string } | null | undefined,
+ limit: number,
+): Page {
+ const start = cursor ? Number(cursor.id) : 0;
+ const end = start + limit;
+ return {
+ bookmarks: all.slice(start, end),
+ nextCursor:
+ end < all.length || state.repeatCursor
+ ? { createdAt: new Date(0), id: state.repeatCursor ? "1" : String(end) }
+ : null,
+ };
+}
+
+vi.mock("@karakeep/shared-react/providers/trpc-provider", () => ({
+ getTRPCClient: () => ({
+ bookmarks: {
+ getBookmarks: {
+ query: async (input: {
+ listId?: string;
+ archived?: boolean;
+ cursor?: { id: string } | null;
+ limit: number;
+ }) => {
+ state.pageRequests.push({
+ listId: input.listId,
+ archived: input.archived,
+ });
+ if (input.listId !== undefined) {
+ const list = state.lists.get(input.listId);
+ if (list === undefined || list instanceof Error) {
+ throw list ?? new Error("unknown list");
+ }
+ return page(list, input.cursor, input.limit);
+ }
+ return page(state.recent, input.cursor, input.limit);
+ },
+ },
+ getBookmark: {
+ query: async ({ bookmarkId }: { bookmarkId: string }) => {
+ state.contentRequests.push(bookmarkId);
+ state.onContentRequest?.();
+ const bookmark = [
+ ...state.recent,
+ ...[...state.lists.values()].flat(),
+ ]
+ .filter((item): item is ZBookmark => !(item instanceof Error))
+ .find((item) => item.id === bookmarkId);
+ if (!bookmark) {
+ throw new Error("not found");
+ }
+ return bookmark;
+ },
+ },
+ },
+ }),
+}));
+
+function trpcError(code: string) {
+ return Object.assign(new Error(code), { data: { code } });
+}
+
+const SCOPE = "https://keep.example.com|key-id";
+const OTHER_SCOPE = "https://keep.example.com|other-key-id";
+
+async function load() {
+ vi.resetModules();
+ return {
+ sync: await import("./offlineSync"),
+ library: await import("./offlineLibrary"),
+ prefs: await import("./offlineDownloadPrefs"),
+ };
+}
+
+type Modules = Awaited<ReturnType<typeof load>>;
+
+function storedIds(modules: Modules) {
+ return modules.library
+ .getOfflineLibraryItems(SCOPE)
+ .map((item) => `${item.bookmarkId}:${item.source}`)
+ .sort();
+}
+
+function seed(
+ modules: Modules,
+ bookmark: ZBookmark,
+ source: "manual" | "auto",
+) {
+ modules.library.saveOfflineArticle(
+ SCOPE,
+ {
+ schemaVersion: modules.library.OFFLINE_LIBRARY_SCHEMA_VERSION,
+ bookmarkId: bookmark.id,
+ savedAt: Date.now(),
+ bookmark,
+ },
+ source,
+ );
+}
+
+function setPrefs(
+ modules: Modules,
+ prefs: Partial<ReturnType<Modules["prefs"]["getOfflineDownloadPrefs"]>>,
+) {
+ modules.prefs.updateOfflineDownloadPrefs(SCOPE, (current) => ({
+ ...current,
+ ...prefs,
+ }));
+}
+
+beforeEach(() => {
+ state.settings.apiKey = "key";
+ state.settings.apiKeyId = "key-id";
+ state.network = {
+ isConnected: true,
+ isInternetReachable: true,
+ type: "WIFI",
+ };
+ state.lists = new Map();
+ state.recent = [];
+ state.repeatCursor = false;
+ state.pageRequests = [];
+ state.contentRequests = [];
+ state.onContentRequest = undefined;
+});
+
+describe("refreshOfflineDownloads", () => {
+ it("waits for Wi-Fi unless cellular is allowed", async () => {
+ const modules = await load();
+ state.network = {
+ isConnected: true,
+ isInternetReachable: true,
+ type: "CELLULAR",
+ };
+ state.recent = [linkBookmark("a")];
+ setPrefs(modules, { recentEnabled: true });
+
+ const waiting = await modules.sync.refreshOfflineDownloads({ force: true });
+ expect(waiting?.phase).toBe("wifi");
+ expect(state.pageRequests).toEqual([]);
+
+ setPrefs(modules, { wifiOnly: false });
+ const done = await modules.sync.refreshOfflineDownloads({ force: true });
+ expect(done).toMatchObject({ phase: "ready", ready: 1, total: 1 });
+ expect(storedIds(modules)).toEqual(["a:auto"]);
+ });
+
+ it("doesn't wait for the OS to call the internet reachable", async () => {
+ const modules = await load();
+ state.network = {
+ isConnected: true,
+ isInternetReachable: false,
+ type: "WIFI",
+ };
+ state.recent = [linkBookmark("a")];
+ setPrefs(modules, { recentEnabled: true });
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status?.phase).toBe("ready");
+ expect(storedIds(modules)).toEqual(["a:auto"]);
+ });
+
+ it("downloads every page of a list, and shared articles once", async () => {
+ const modules = await load();
+ const list = Array.from({ length: 150 }, (_, index) =>
+ linkBookmark(`l${index}`, { createdAt: index }),
+ );
+ state.lists.set("list", list);
+ state.recent = [list[149], linkBookmark("r", { createdAt: 500 })];
+ setPrefs(modules, { recentEnabled: true, listIds: ["list"] });
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status).toMatchObject({ phase: "ready", ready: 151, total: 151 });
+ expect(state.pageRequests.filter((request) => request.listId)).toHaveLength(
+ 2,
+ );
+ expect(state.contentRequests).toHaveLength(151);
+ // Lists come first even though the recent article is newer.
+ expect(state.contentRequests[0]).toBe("l149");
+ expect(state.contentRequests.at(-1)).toBe("r");
+ });
+
+ it("treats a deleted list as empty", async () => {
+ const modules = await load();
+ seed(modules, linkBookmark("from-list"), "auto");
+ seed(modules, linkBookmark("saved"), "manual");
+ state.lists.set("gone", trpcError("NOT_FOUND"));
+ setPrefs(modules, { listIds: ["gone"] });
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status?.phase).toBe("ready");
+ expect(storedIds(modules)).toEqual(["saved:manual"]);
+ // Deselected too, since settings can't show it any more.
+ expect(modules.prefs.getOfflineDownloadPrefs(SCOPE).listIds).toEqual([]);
+ });
+
+ it("keeps everything when a list can't be fetched", async () => {
+ const modules = await load();
+ seed(modules, linkBookmark("from-list"), "auto");
+ state.lists.set("list", trpcError("INTERNAL_SERVER_ERROR"));
+ setPrefs(modules, { listIds: ["list"] });
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status?.phase).toBe("error");
+ expect(storedIds(modules)).toEqual(["from-list:auto"]);
+ });
+
+ it("stops on a repeated page without removing anything", async () => {
+ const modules = await load();
+ seed(modules, linkBookmark("old"), "auto");
+ state.repeatCursor = true;
+ state.recent = [linkBookmark("a"), linkBookmark("b")];
+ setPrefs(modules, { recentEnabled: true });
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status?.phase).toBe("error");
+ expect(storedIds(modules)).toEqual(["old:auto"]);
+ });
+
+ it("counts only downloadable articles towards the recent limit", async () => {
+ const modules = await load();
+ state.recent = [
+ assetBookmark("pdf", 9),
+ linkBookmark("broken", {
+ createdAt: 8,
+ crawlStatus: "failure",
+ htmlContent: null,
+ }),
+ linkBookmark("removed", { createdAt: 7.5 }),
+ linkBookmark("a", { createdAt: 7 }),
+ linkBookmark("b", { createdAt: 6 }),
+ linkBookmark("c", { createdAt: 5 }),
+ ];
+ setPrefs(modules, {
+ recentEnabled: true,
+ recentLimit: 2,
+ excludedIds: ["removed"],
+ });
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status).toMatchObject({ phase: "ready", ready: 2, total: 2 });
+ expect(storedIds(modules)).toEqual(["a:auto", "b:auto"]);
+ });
+
+ it("doesn't count an article without reader content as failed", async () => {
+ const modules = await load();
+ state.recent = [linkBookmark("empty", { htmlContent: null })];
+ setPrefs(modules, { recentEnabled: true });
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status).toMatchObject({ phase: "ready", total: 0, failed: 0 });
+ });
+
+ it("runs a refresh requested during a pass once it ends", async () => {
+ const modules = await load();
+ state.recent = [linkBookmark("a")];
+ setPrefs(modules, { recentEnabled: true });
+ state.onContentRequest = () => {
+ state.onContentRequest = undefined;
+ // Logged out and into another account while the pass ran.
+ state.settings.apiKey = undefined;
+ modules.library.clearOfflineLibrary();
+ modules.prefs.clearOfflineDownloadStorage();
+ modules.sync.resetOfflineDownloads();
+ state.settings.apiKey = "other-key";
+ state.settings.apiKeyId = "other-key-id";
+ modules.prefs.updateOfflineDownloadPrefs(OTHER_SCOPE, (current) => ({
+ ...current,
+ recentEnabled: true,
+ }));
+ void modules.sync.refreshOfflineDownloads();
+ };
+
+ await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(
+ modules.library
+ .getOfflineLibraryItems(OTHER_SCOPE)
+ .map((item) => item.bookmarkId),
+ ).toEqual(["a"]);
+ // The interrupted pass didn't save its download for the old account.
+ expect(storedIds(modules)).toEqual([]);
+ });
+
+ it("throttles automatic refreshes but not forced ones", async () => {
+ const modules = await load();
+ state.recent = [linkBookmark("a")];
+ setPrefs(modules, { recentEnabled: true });
+
+ await modules.sync.refreshOfflineDownloads();
+ await modules.sync.refreshOfflineDownloads();
+ expect(state.pageRequests).toHaveLength(1);
+
+ await modules.sync.refreshOfflineDownloads({ force: true });
+ expect(state.pageRequests).toHaveLength(2);
+ });
+
+ it("removes automatic copies when turned off", async () => {
+ const modules = await load();
+ seed(modules, linkBookmark("auto"), "auto");
+ seed(modules, linkBookmark("saved"), "manual");
+
+ const status = await modules.sync.refreshOfflineDownloads();
+
+ expect(status?.phase).toBe("disabled");
+ expect(storedIds(modules)).toEqual(["saved:manual"]);
+ });
+
+ it("forgets exclusions that no longer match anything", async () => {
+ const modules = await load();
+ state.recent = [linkBookmark("kept-out"), linkBookmark("a")];
+ setPrefs(modules, {
+ recentEnabled: true,
+ excludedIds: ["kept-out", "long-gone"],
+ });
+
+ await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(modules.prefs.getOfflineDownloadPrefs(SCOPE).excludedIds).toEqual([
+ "kept-out",
+ ]);
+ expect(storedIds(modules)).toEqual(["a:auto"]);
+ });
+
+ it("writes nothing after logging out mid-download", async () => {
+ const modules = await load();
+ state.recent = [linkBookmark("a"), linkBookmark("b")];
+ setPrefs(modules, { recentEnabled: true });
+ state.onContentRequest = () => {
+ state.onContentRequest = undefined;
+ // What useSession().logout does.
+ state.settings.apiKey = undefined;
+ modules.library.clearOfflineLibrary();
+ modules.prefs.clearOfflineDownloadStorage();
+ modules.sync.resetOfflineDownloads();
+ };
+
+ const status = await modules.sync.refreshOfflineDownloads({ force: true });
+
+ expect(status).toBeUndefined();
+ expect(storedIds(modules)).toEqual([]);
+ expect(modules.prefs.offlineDownloadStorage.getAllKeys()).toEqual([]);
+ });
+});
diff --git a/apps/mobile/lib/offlineSync.ts b/apps/mobile/lib/offlineSync.ts
new file mode 100644
index 00000000..8bdc3369
--- /dev/null
+++ b/apps/mobile/lib/offlineSync.ts
@@ -0,0 +1,518 @@
+import { useSyncExternalStore } from "react";
+import * as Network from "expo-network";
+import { z } from "zod";
+
+import type {
+ ZBookmark,
+ ZGetBookmarksResponse,
+} from "@karakeep/shared/types/bookmarks";
+import { getTRPCClient } from "@karakeep/shared-react/providers/trpc-provider";
+import {
+ BookmarkTypes,
+ MAX_NUM_BOOKMARKS_PER_PAGE,
+} from "@karakeep/shared/types/bookmarks";
+
+import type { OfflineDownloadPrefs } from "./offlineDownloadPrefs";
+import type { Settings } from "./settings";
+import type { SyncCandidate, SyncProgress } from "./offlineSyncEngine";
+import {
+ getOfflineDownloadPrefs,
+ isAutoDownloadEnabled,
+ offlineDownloadStorage,
+ updateOfflineDownloadPrefs,
+} from "./offlineDownloadPrefs";
+import {
+ estimateOfflineArticleSize,
+ getOfflineLibraryItems,
+ getOfflineLibraryScope,
+ OFFLINE_LIBRARY_SCHEMA_VERSION,
+ removeOfflineArticle,
+ saveOfflineArticle,
+} from "./offlineLibrary";
+import {
+ ContentUnavailable,
+ isDownloadable,
+ selectCandidates,
+ synchronizeOfflineCopies,
+ SyncInterrupted,
+} from "./offlineSyncEngine";
+import { useSettings } from "./settings";
+import { megabytesToBytes } from "./storageSize";
+
+// Foreground triggers (app open, timer) back off for this long after a pass.
+export const REFRESH_THROTTLE = 5 * 60 * 1000;
+
+const zPhase = z.enum([
+ "idle",
+ "checking",
+ "downloading",
+ "ready",
+ "wifi",
+ "offline",
+ "paused",
+ "error",
+ "disabled",
+]);
+export type OfflineSyncPhase = z.infer<typeof zPhase>;
+
+const zStatus = z.object({
+ phase: zPhase,
+ total: z.number(),
+ ready: z.number(),
+ failed: z.number(),
+ budgetReached: z.boolean(),
+ lastAttemptAt: z.number().optional(),
+ lastCheckedAt: z.number().optional(),
+});
+export type OfflineSyncStatus = z.infer<typeof zStatus>;
+
+const INITIAL_STATUS: OfflineSyncStatus = {
+ phase: "idle",
+ total: 0,
+ ready: 0,
+ failed: 0,
+ budgetReached: false,
+};
+
+// A pass that ended in one of these didn't finish; retry without waiting out
+// the throttle once conditions change.
+const INTERRUPTED_PHASES = new Set<OfflineSyncPhase>([
+ "paused",
+ "wifi",
+ "offline",
+ "error",
+]);
+
+function statusKey(scope: string) {
+ return `status:${encodeURIComponent(scope)}`;
+}
+
+let statusState: { scope: string; status: OfflineSyncStatus } | undefined;
+const statusListeners = new Set<() => void>();
+
+function loadStatus(scope: string): OfflineSyncStatus {
+ const raw = offlineDownloadStorage.getString(statusKey(scope));
+ if (!raw) {
+ return INITIAL_STATUS;
+ }
+ try {
+ const result = zStatus.safeParse(JSON.parse(raw));
+ if (!result.success) {
+ return INITIAL_STATUS;
+ }
+ // Persisted mid-pass: the app was killed or suspended before it finished.
+ return result.data.phase === "checking" ||
+ result.data.phase === "downloading"
+ ? { ...result.data, phase: "paused" }
+ : result.data;
+ } catch {
+ return INITIAL_STATUS;
+ }
+}
+
+function getOfflineSyncStatus(scope: string) {
+ if (statusState?.scope !== scope) {
+ statusState = { scope, status: loadStatus(scope) };
+ }
+ return statusState.status;
+}
+
+function updateStatus(scope: string, patch: Partial<OfflineSyncStatus>) {
+ const status = { ...getOfflineSyncStatus(scope), ...patch };
+ statusState = { scope, status };
+ offlineDownloadStorage.set(statusKey(scope), JSON.stringify(status));
+ for (const listener of statusListeners) {
+ listener();
+ }
+}
+
+function subscribeToStatus(listener: () => void) {
+ statusListeners.add(listener);
+ return () => {
+ statusListeners.delete(listener);
+ };
+}
+
+export function useOfflineSyncStatus(scope: string) {
+ const getSnapshot = () => getOfflineSyncStatus(scope);
+ return useSyncExternalStore(subscribeToStatus, getSnapshot, getSnapshot);
+}
+
+interface ActiveRun {
+ controller: AbortController;
+ // Set on logout: whatever the run was doing must not touch storage again.
+ discarded: boolean;
+}
+
+let activeRun: ActiveRun | undefined;
+let running: Promise<OfflineSyncStatus | undefined> | undefined;
+let queuedRefresh: RefreshOptions | undefined;
+// Sizes of articles seen on earlier passes (see SyncDeps.knownSizes).
+const knownSizes = new Map<string, number>();
+
+export interface RefreshOptions {
+ // Skip the throttle ("Download now", settings changed…).
+ force?: boolean;
+}
+
+type TRPCClient = ReturnType<typeof getTRPCClient>;
+
+function currentSettings(): Settings {
+ return useSettings.getState().settings.settings;
+}
+
+function errorCode(error: unknown) {
+ if (
+ typeof error === "object" &&
+ error !== null &&
+ "data" in error &&
+ typeof error.data === "object" &&
+ error.data !== null &&
+ "code" in error.data &&
+ typeof error.data.code === "string"
+ ) {
+ return error.data.code;
+ }
+ return undefined;
+}
+
+async function fetchBookmarks(
+ client: TRPCClient,
+ filter: { listId?: string; archived?: boolean },
+ limit: number,
+ signal: AbortSignal,
+ checkpoint: () => Promise<void>,
+ // Which bookmarks count towards the limit.
+ counts: (bookmark: ZBookmark) => boolean = () => true,
+) {
+ const bookmarks: ZBookmark[] = [];
+ let counted = 0;
+ const seenCursors = new Set<string>();
+ let cursor: ZGetBookmarksResponse["nextCursor"] = null;
+ do {
+ await checkpoint();
+ const page = await client.bookmarks.getBookmarks.query(
+ {
+ ...filter,
+ cursor,
+ limit: Math.min(MAX_NUM_BOOKMARKS_PER_PAGE, limit - counted),
+ sortOrder: "desc",
+ includeContent: false,
+ useCursorV2: true,
+ },
+ { signal },
+ );
+ bookmarks.push(...page.bookmarks);
+ counted += page.bookmarks.filter(counts).length;
+ cursor = page.nextCursor;
+ if (cursor) {
+ const cursorKey = `${cursor.createdAt.getTime()}|${cursor.id}`;
+ if (seenCursors.has(cursorKey)) {
+ throw new Error("The server returned a repeated page.");
+ }
+ seenCursors.add(cursorKey);
+ }
+ } while (cursor && counted < limit);
+ return bookmarks;
+}
+
+async function fetchSelection(
+ client: TRPCClient,
+ prefs: OfflineDownloadPrefs,
+ signal: AbortSignal,
+ checkpoint: () => Promise<void>,
+) {
+ const listBookmarks: ZBookmark[] = [];
+ const goneListIds: string[] = [];
+ for (const listId of prefs.listIds) {
+ try {
+ listBookmarks.push(
+ ...(await fetchBookmarks(
+ client,
+ { listId },
+ Number.POSITIVE_INFINITY,
+ signal,
+ checkpoint,
+ )),
+ );
+ } catch (error) {
+ // The list was deleted or is no longer shared with us: nothing in it is
+ // wanted any more. Anything else leaves the selection unknown.
+ const code = errorCode(error);
+ if (code !== "NOT_FOUND" && code !== "FORBIDDEN") {
+ throw error;
+ }
+ goneListIds.push(listId);
+ }
+ }
+ const excluded = new Set(prefs.excludedIds);
+ const recentBookmarks = prefs.recentEnabled
+ ? await fetchBookmarks(
+ client,
+ { archived: false },
+ prefs.recentLimit,
+ signal,
+ checkpoint,
+ // Only articles that will be downloaded use up the count: not
+ // attachments, failed crawls or the ones the user removed.
+ (bookmark) => isDownloadable(bookmark) && !excluded.has(bookmark.id),
+ )
+ : [];
+ return {
+ candidates: selectCandidates(
+ listBookmarks,
+ recentBookmarks,
+ prefs.excludedIds,
+ ),
+ selectedIds: new Set(
+ [...listBookmarks, ...recentBookmarks].map((bookmark) => bookmark.id),
+ ),
+ goneListIds,
+ };
+}
+
+// An exclusion only matters while the article would otherwise be selected;
+// dropping the rest keeps the list from growing forever.
+function forgetStaleExclusions(scope: string, selectedIds: Set<string>) {
+ if (
+ getOfflineDownloadPrefs(scope).excludedIds.every((id) =>
+ selectedIds.has(id),
+ )
+ ) {
+ return;
+ }
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ excludedIds: current.excludedIds.filter((id) => selectedIds.has(id)),
+ }));
+}
+
+// A list that is gone can't be picked in settings any more, so it would stay
+// selected for good.
+function forgetGoneLists(scope: string, goneListIds: string[]) {
+ if (goneListIds.length === 0) {
+ return;
+ }
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ listIds: current.listIds.filter((id) => !goneListIds.includes(id)),
+ }));
+}
+
+// Ignores isInternetReachable, like setupOnlineManager: Android reports it as
+// false behind VPNs and on LAN-only setups that reach the server just fine.
+function isAllowedNetwork(state: Network.NetworkState, wifiOnly: boolean) {
+ if (!state.isConnected) {
+ return "offline";
+ }
+ if (
+ wifiOnly &&
+ state.type !== Network.NetworkStateType.WIFI &&
+ state.type !== Network.NetworkStateType.ETHERNET
+ ) {
+ return "wifi";
+ }
+ return undefined;
+}
+
+function removeAutomaticCopies(scope: string) {
+ for (const item of getOfflineLibraryItems(scope)) {
+ if (item.source === "auto") {
+ removeOfflineArticle(scope, item.bookmarkId);
+ }
+ }
+}
+
+async function runOnce(
+ options: RefreshOptions,
+): Promise<OfflineSyncStatus | undefined> {
+ const settings = currentSettings();
+ if (!settings.apiKey) {
+ return undefined;
+ }
+ const scope = getOfflineLibraryScope(settings);
+ const prefs = getOfflineDownloadPrefs(scope);
+ const previous = getOfflineSyncStatus(scope);
+
+ if (!isAutoDownloadEnabled(prefs)) {
+ removeAutomaticCopies(scope);
+ updateStatus(scope, { ...INITIAL_STATUS, phase: "disabled" });
+ return getOfflineSyncStatus(scope);
+ }
+ if (
+ !options.force &&
+ previous.lastAttemptAt !== undefined &&
+ Date.now() - previous.lastAttemptAt < REFRESH_THROTTLE &&
+ !INTERRUPTED_PHASES.has(previous.phase)
+ ) {
+ return previous;
+ }
+
+ const run: ActiveRun = {
+ controller: new AbortController(),
+ discarded: false,
+ };
+ activeRun = run;
+ const { signal } = run.controller;
+
+ const checkpoint = async () => {
+ if (signal.aborted) {
+ throw new SyncInterrupted("cancelled");
+ }
+ const blocked = isAllowedNetwork(
+ await Network.getNetworkStateAsync(),
+ prefs.wifiOnly,
+ );
+ if (blocked) {
+ throw new SyncInterrupted(blocked);
+ }
+ };
+
+ updateStatus(scope, { phase: "checking", lastAttemptAt: Date.now() });
+ try {
+ await checkpoint();
+ const client = getTRPCClient(settings);
+ const { candidates, selectedIds, goneListIds } = await fetchSelection(
+ client,
+ prefs,
+ signal,
+ checkpoint,
+ );
+ if (run.discarded) {
+ return undefined;
+ }
+ forgetStaleExclusions(scope, selectedIds);
+ forgetGoneLists(scope, goneListIds);
+
+ updateStatus(scope, { phase: "downloading", total: candidates.length });
+ const result = await synchronizeOfflineCopies(candidates, {
+ budgetBytes: megabytesToBytes(prefs.budgetMb),
+ knownSizes,
+ checkpoint,
+ listStored: () => getOfflineLibraryItems(scope),
+ isExcluded: (bookmarkId) =>
+ getOfflineDownloadPrefs(scope).excludedIds.includes(bookmarkId),
+ prepare: async (candidate: SyncCandidate) => {
+ const bookmark = await client.bookmarks.getBookmark.query(
+ { bookmarkId: candidate.bookmarkId, includeContent: true },
+ { signal },
+ );
+ if (
+ bookmark.content.type === BookmarkTypes.LINK &&
+ typeof bookmark.content.htmlContent !== "string"
+ ) {
+ throw new ContentUnavailable();
+ }
+ return {
+ byteSize: estimateOfflineArticleSize(bookmark),
+ save: () => {
+ if (run.discarded) {
+ throw new SyncInterrupted("cancelled");
+ }
+ saveOfflineArticle(
+ scope,
+ {
+ schemaVersion: OFFLINE_LIBRARY_SCHEMA_VERSION,
+ bookmarkId: bookmark.id,
+ savedAt: Date.now(),
+ bookmark,
+ },
+ "auto",
+ );
+ },
+ };
+ },
+ remove: (bookmarkId) => {
+ if (!run.discarded) {
+ removeOfflineArticle(scope, bookmarkId);
+ }
+ },
+ onProgress: (progress: SyncProgress) => {
+ if (!run.discarded) {
+ updateStatus(scope, { ...progress, phase: "downloading" });
+ }
+ },
+ });
+
+ if (run.discarded) {
+ return undefined;
+ }
+ updateStatus(scope, {
+ ...result,
+ phase: "ready",
+ lastCheckedAt: Date.now(),
+ });
+ } catch (error) {
+ if (run.discarded) {
+ return undefined;
+ }
+ // An aborted request fails with its own error, not SyncInterrupted.
+ if (error instanceof SyncInterrupted || signal.aborted) {
+ const reason =
+ error instanceof SyncInterrupted ? error.reason : undefined;
+ updateStatus(scope, {
+ phase: reason === "offline" || reason === "wifi" ? reason : "paused",
+ });
+ } else {
+ updateStatus(scope, { phase: "error" });
+ }
+ } finally {
+ if (activeRun === run) {
+ activeRun = undefined;
+ }
+ }
+ return getOfflineSyncStatus(scope);
+}
+
+/**
+ * Runs a download pass for the signed-in account. Only one pass runs at a
+ * time; a request made during a pass runs once it ends, throttled unless
+ * forced. Even an unforced one has to wait its turn rather than be dropped:
+ * the running pass may be for an account that was just signed out of.
+ */
+export function refreshOfflineDownloads(
+ options: RefreshOptions = {},
+): Promise<OfflineSyncStatus | undefined> {
+ if (running) {
+ if (!queuedRefresh?.force) {
+ queuedRefresh = options;
+ }
+ return running;
+ }
+ const pass = (async () => {
+ let status: OfflineSyncStatus | undefined;
+ let next: RefreshOptions | undefined = options;
+ try {
+ while (next) {
+ queuedRefresh = undefined;
+ status = await runOnce(next);
+ next = queuedRefresh;
+ }
+ } finally {
+ running = undefined;
+ }
+ return status;
+ })();
+ running = pass;
+ return pass;
+}
+
+export function cancelOfflineDownloads() {
+ queuedRefresh = undefined;
+ activeRun?.controller.abort();
+}
+
+// On logout: stop the current pass without letting it write anything, and
+// forget everything held in memory.
+export function resetOfflineDownloads() {
+ queuedRefresh = undefined;
+ if (activeRun) {
+ activeRun.discarded = true;
+ activeRun.controller.abort();
+ }
+ knownSizes.clear();
+ statusState = undefined;
+ for (const listener of statusListeners) {
+ listener();
+ }
+}
diff --git a/apps/mobile/lib/session.ts b/apps/mobile/lib/session.ts
index c87625be..f1629edb 100644
--- a/apps/mobile/lib/session.ts
+++ b/apps/mobile/lib/session.ts
@@ -4,7 +4,9 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@karakeep/shared-react/trpc";
import { clearPersistedCache } from "./offlineCache";
+import { clearOfflineDownloadStorage } from "./offlineDownloadPrefs";
import { clearOfflineLibrary } from "./offlineLibrary";
+import { resetOfflineDownloads } from "./offlineSync";
import useAppSettings from "./settings";
export function useSession() {
@@ -24,6 +26,10 @@ export function useSession() {
queryClient.clear();
clearPersistedCache();
clearOfflineLibrary();
+ clearOfflineDownloadStorage();
+ // After clearing: it notifies the download status screen, which reloads
+ // from storage.
+ resetOfflineDownloads();
}, [deleteKey, queryClient, settings, setSettings]);
return {
diff --git a/apps/mobile/lib/storageSize.ts b/apps/mobile/lib/storageSize.ts
new file mode 100644
index 00000000..01b0ad9f
--- /dev/null
+++ b/apps/mobile/lib/storageSize.ts
@@ -0,0 +1,3 @@
+export function megabytesToBytes(megabytes: number) {
+ return megabytes * 1024 * 1024;
+}
diff --git a/packages/shared-react/providers/trpc-provider.tsx b/packages/shared-react/providers/trpc-provider.tsx
index 853fb9ad..97ea7af4 100644
--- a/packages/shared-react/providers/trpc-provider.tsx
+++ b/packages/shared-react/providers/trpc-provider.tsx
@@ -39,7 +39,7 @@ function getQueryClient() {
}
}
-function getTRPCClient(settings: Settings) {
+export function getTRPCClient(settings: Settings) {
return createTRPCClient<AppRouter>({
links: [
httpBatchLink({