Skip to content

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

feat(mobile): show and download bookmark attachments

Mohamed Bassem27774f977b76
diff --git a/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx b/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx
index f0e8b5d6..8a0b9cdb 100644
--- a/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx
+++ b/apps/mobile/app/dashboard/bookmarks/[slug]/info.tsx
@@ -13,6 +13,7 @@ import {
} from "react-native-keyboard-controller";
import * as Haptics from "expo-haptics";
import { router, Stack, useLocalSearchParams } from "expo-router";
+import AttachmentBox from "@/components/bookmarks/AttachmentBox";
import BookmarkTextMarkdown from "@/components/bookmarks/BookmarkTextMarkdown";
import TagPill from "@/components/bookmarks/TagPill";
import QueryPageState from "@/components/QueryPageState";
@@ -582,21 +583,20 @@ const ViewBookmarkPage = () => {
isPending={isEditPending}
disabled={!isOwner}
/>
+ {isOwner && <BookmarkActionsSection bookmark={bookmark} />}
+ <AttachmentBox bookmark={bookmark} />
{isOwner && (
- <>
- <BookmarkActionsSection bookmark={bookmark} />
- <GroupedSection>
- <Pressable
- onPress={handleDeleteBookmark}
- disabled={isDeletionPending}
- className="items-center px-4 py-3 active:opacity-70"
- >
- <Text className="text-destructive" numberOfLines={1}>
- {isDeletionPending ? "Deleting..." : "Delete Bookmark"}
- </Text>
- </Pressable>
- </GroupedSection>
- </>
+ <GroupedSection>
+ <Pressable
+ onPress={handleDeleteBookmark}
+ disabled={isDeletionPending}
+ className="items-center px-4 py-3 active:opacity-70"
+ >
+ <Text className="text-destructive" numberOfLines={1}>
+ {isDeletionPending ? "Deleting..." : "Delete Bookmark"}
+ </Text>
+ </Pressable>
+ </GroupedSection>
)}
<View className="items-center gap-1 pt-2">
<Text variant="caption1" color="tertiary" selectable>
diff --git a/apps/mobile/components/bookmarks/AttachmentBox.tsx b/apps/mobile/components/bookmarks/AttachmentBox.tsx
new file mode 100644
index 00000000..a46a3165
--- /dev/null
+++ b/apps/mobile/components/bookmarks/AttachmentBox.tsx
@@ -0,0 +1,125 @@
+import { Fragment, useRef, useState } from "react";
+import { ActivityIndicator, Pressable, View } from "react-native";
+import {
+ Archive,
+ Camera,
+ Download,
+ FileCode,
+ FileText,
+ Image,
+ Paperclip,
+ SquareUser,
+ Upload,
+ Video,
+} from "lucide-react-native";
+
+import type { ZAssetType, ZBookmark } from "@karakeep/shared/types/bookmarks";
+import { humanFriendlyNameForAssertType } from "@karakeep/shared/utils/assetUtils";
+
+import { GroupedSection, RowSeparator } from "@/components/ui/GroupedList";
+import { Text } from "@/components/ui/Text";
+import { useToast } from "@/components/ui/Toast";
+import { downloadAttachment } from "@/lib/downloadAttachment";
+import useAppSettings from "@/lib/settings";
+import { useColorScheme } from "@/lib/useColorScheme";
+
+const ASSET_ICONS: Record<ZAssetType, typeof Paperclip> = {
+ screenshot: Camera,
+ pdf: FileText,
+ assetScreenshot: Camera,
+ fullPageArchive: Archive,
+ precrawledArchive: Archive,
+ bannerImage: Image,
+ video: Video,
+ bookmarkAsset: Paperclip,
+ linkHtmlContent: FileCode,
+ userUploaded: Upload,
+ avatar: SquareUser,
+ unknown: Paperclip,
+};
+
+export default function AttachmentBox({ bookmark }: { bookmark: ZBookmark }) {
+ const { settings } = useAppSettings();
+ const { colors } = useColorScheme();
+ const { toast } = useToast();
+ const [downloadingId, setDownloadingId] = useState<string | null>(null);
+ const downloadInProgress = useRef(false);
+ const assets = [...bookmark.assets].sort((a, b) =>
+ a.assetType.localeCompare(b.assetType),
+ );
+
+ const download = async (asset: ZBookmark["assets"][number]) => {
+ if (downloadInProgress.current) return;
+ downloadInProgress.current = true;
+ setDownloadingId(asset.id);
+ try {
+ await downloadAttachment(asset, settings);
+ } catch (error) {
+ toast({
+ message:
+ error instanceof Error
+ ? error.message
+ : "Failed to download attachment",
+ variant: "destructive",
+ showProgress: false,
+ });
+ } finally {
+ downloadInProgress.current = false;
+ setDownloadingId(null);
+ }
+ };
+
+ return (
+ <GroupedSection header="Attachments">
+ {assets.length === 0 ? (
+ <Text color="tertiary" className="px-4 py-3">
+ No attachments
+ </Text>
+ ) : (
+ <>
+ {assets.map((asset, index) => {
+ const Icon = ASSET_ICONS[asset.assetType];
+ const name =
+ asset.assetType === "userUploaded" && asset.fileName
+ ? asset.fileName
+ : humanFriendlyNameForAssertType(asset.assetType);
+ const isDownloading = downloadingId === asset.id;
+ return (
+ <Fragment key={asset.id}>
+ {index > 0 && <RowSeparator />}
+ <Pressable
+ accessibilityRole="button"
+ accessibilityLabel={`Download ${name}`}
+ accessibilityHint="Opens options to save or share this attachment"
+ accessibilityState={{
+ disabled: downloadingId !== null,
+ busy: isDownloading,
+ }}
+ disabled={downloadingId !== null}
+ onPress={() => void download(asset)}
+ className="min-h-12 flex-row items-center gap-3 px-4 py-3 active:opacity-70"
+ >
+ <Icon size={20} color={colors.grey} />
+ <Text className="flex-1" numberOfLines={2}>
+ {name}
+ </Text>
+ <View className="h-6 w-6 items-center justify-center">
+ {isDownloading ? (
+ <ActivityIndicator size="small" color={colors.primary} />
+ ) : (
+ <Download size={20} color={colors.primary} />
+ )}
+ </View>
+ </Pressable>
+ </Fragment>
+ );
+ })}
+ <RowSeparator />
+ <Text variant="footnote" color="tertiary" className="px-4 py-3">
+ Tap an attachment to save or share it.
+ </Text>
+ </>
+ )}
+ </GroupedSection>
+ );
+}
diff --git a/apps/mobile/lib/downloadAttachment.ts b/apps/mobile/lib/downloadAttachment.ts
new file mode 100644
index 00000000..244954b4
--- /dev/null
+++ b/apps/mobile/lib/downloadAttachment.ts
@@ -0,0 +1,76 @@
+import * as FileSystem from "expo-file-system/legacy";
+import * as Sharing from "expo-sharing";
+
+import type { ZBookmark } from "@karakeep/shared/types/bookmarks";
+import {
+ getAssetUrl,
+ humanFriendlyNameForAssertType,
+} from "@karakeep/shared/utils/assetUtils";
+
+import type { Settings } from "@/lib/settings";
+import { buildApiHeaders } from "@/lib/utils";
+
+const MIME_EXTENSIONS: Record<string, string> = {
+ "application/pdf": "pdf",
+ "application/zip": "zip",
+ "image/jpeg": "jpg",
+ "image/png": "png",
+ "image/webp": "webp",
+ "image/gif": "gif",
+ "image/svg+xml": "svg",
+ "text/html": "html",
+ "text/plain": "txt",
+ "video/mp4": "mp4",
+ "video/webm": "webm",
+};
+
+export async function downloadAttachment(
+ asset: ZBookmark["assets"][number],
+ settings: Settings,
+) {
+ if (!(await Sharing.isAvailableAsync())) {
+ throw new Error("Saving attachments is not available on this device");
+ }
+ if (!FileSystem.cacheDirectory) {
+ throw new Error("Temporary storage is not available on this device");
+ }
+
+ const directory = `${FileSystem.cacheDirectory}attachment-${Date.now()}-${Math.random().toString(36).slice(2)}/`;
+ await FileSystem.makeDirectoryAsync(directory, { intermediates: true });
+
+ try {
+ const result = await FileSystem.downloadAsync(
+ `${settings.address.replace(/\/$/, "")}${getAssetUrl(asset.id)}`,
+ `${directory}download`,
+ { headers: buildApiHeaders(settings.apiKey, settings.customHeaders) },
+ );
+ if (result.status !== 200) {
+ throw new Error("Failed to download attachment. Please try again.");
+ }
+
+ const contentType =
+ result.mimeType ??
+ Object.entries(result.headers).find(
+ ([name]) => name.toLowerCase() === "content-type",
+ )?.[1];
+ const mimeType = contentType?.split(";")[0].trim().toLowerCase();
+ const extension = mimeType ? MIME_EXTENSIONS[mimeType] : undefined;
+ // Keep server-provided names inside the temporary directory.
+ let fileName = (
+ asset.fileName || humanFriendlyNameForAssertType(asset.assetType)
+ )
+ .replace(/[/\\:*?"<>|\p{Cc}]/gu, "_")
+ .replace(/^\.+/, "_");
+ if (!/\.[a-z0-9]+$/i.test(fileName) && extension) {
+ fileName += `.${extension}`;
+ }
+ const uri = `${directory}${encodeURIComponent(fileName)}`;
+ await FileSystem.moveAsync({ from: result.uri, to: uri });
+ await Sharing.shareAsync(uri, {
+ dialogTitle: "Save or share attachment",
+ ...(mimeType ? { mimeType } : {}),
+ });
+ } finally {
+ await FileSystem.deleteAsync(directory, { idempotent: true });
+ }
+}
diff --git a/packages/shared/utils/assetUtils.ts b/packages/shared/utils/assetUtils.ts
index 119451d9..61587fa5 100644
--- a/packages/shared/utils/assetUtils.ts
+++ b/packages/shared/utils/assetUtils.ts
@@ -1,3 +1,23 @@
+import type { ZAssetType } from "../types/bookmarks";
+
export function getAssetUrl(assetId: string) {
return `/api/assets/${assetId}`;
}
+
+export function humanFriendlyNameForAssertType(type: ZAssetType) {
+ const map: Record<ZAssetType, string> = {
+ screenshot: "Screenshot",
+ pdf: "PDF",
+ assetScreenshot: "Asset Screenshot",
+ fullPageArchive: "Full Page Archive",
+ precrawledArchive: "Precrawled Archive",
+ bannerImage: "Banner Image",
+ video: "Video",
+ bookmarkAsset: "Bookmark Asset",
+ linkHtmlContent: "HTML Content",
+ userUploaded: "User Uploaded File",
+ avatar: "Avatar",
+ unknown: "Unknown",
+ };
+ return map[type];
+}
diff --git a/packages/trpc/lib/attachments.ts b/packages/trpc/lib/attachments.ts
index f3170c22..c6af819a 100644
--- a/packages/trpc/lib/attachments.ts
+++ b/packages/trpc/lib/attachments.ts
@@ -45,23 +45,7 @@ export function mapSchemaAssetTypeToDB(
return map[assetType];
}
-export function humanFriendlyNameForAssertType(type: ZAssetType) {
- const map: Record<ZAssetType, string> = {
- screenshot: "Screenshot",
- pdf: "PDF",
- assetScreenshot: "Asset Screenshot",
- fullPageArchive: "Full Page Archive",
- precrawledArchive: "Precrawled Archive",
- bannerImage: "Banner Image",
- video: "Video",
- bookmarkAsset: "Bookmark Asset",
- linkHtmlContent: "HTML Content",
- userUploaded: "User Uploaded File",
- avatar: "Avatar",
- unknown: "Unknown",
- };
- return map[type];
-}
+export { humanFriendlyNameForAssertType } from "@karakeep/shared/utils/assetUtils";
export function isAllowedToAttachAsset(type: ZAssetType) {
const map: Record<ZAssetType, boolean> = {