AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix(mobile): make resource download and export work on Android
tianma-if2f62a2448666
diff --git a/apps/mobile/src/components/MobileResourceActions.tsx b/apps/mobile/src/components/MobileResourceActions.tsxindex 5d01347c..f3f5ff6d 100644--- a/apps/mobile/src/components/MobileResourceActions.tsx+++ b/apps/mobile/src/components/MobileResourceActions.tsx@@ -2,7 +2,11 @@ import { useEffect, useRef, useState, type ReactNode } from "react";import { ActivityIndicator, Alert, Modal, StyleSheet, View } from "react-native";import { Download, FileText, HardDrive, MoreHorizontal, Pencil, Trash2, X } from "./icons";import { Pressable, Text, TextInput } from "./LocalizedText";-import type { MobileAttachmentTarget, MobileResourceTarget } from "../lib/mobile-attachments";+import {+ MobileResourceCancelledError,+ type MobileAttachmentTarget,+ type MobileResourceTarget,+} from "../lib/mobile-attachments";import { useMobileLocale } from "../lib/mobile-locale";import { useMobileTheme } from "../lib/mobile-theme";@@ -25,6 +29,7 @@ const copy = {attachmentDeleteConfirm: "附件会从存储空间和当前笔记中永久删除,此操作无法撤销。",attachmentDeleteTitle: "删除附件",download: "下载",+ exportFailed: "无法导出",failed: "资源操作失败,请重试。",filename: "文件名",rename: "重命名",@@ -44,6 +49,7 @@ const copy = {attachmentDeleteConfirm: "The attachment will be permanently removed from storage and this note. This cannot be undone.",attachmentDeleteTitle: "Delete attachment",download: "Download",+ exportFailed: "Unable to export",failed: "The resource action failed. Try again.",filename: "Filename",rename: "Rename",@@ -150,12 +156,41 @@ export const MobileResourceActions = ({await action();if (closeAfter) onClose();} catch (actionError) {+ if (actionError instanceof MobileResourceCancelledError) {+ return;+ }setError(actionError instanceof Error ? actionError.message : labels.failed);} finally {setPending(false);}};+ /**+ * Download / export open Android system UI (share sheet or SAF folder picker).+ * Dismiss our Modal first so the activity-result channel is free — otherwise SAF+ * often never appears and the tap looks like a dead button.+ */+ const runSystemUiAction = async (+ action: (current: MobileResourceTarget) => Promise<void>,+ failureTitle: string+ ) => {+ const current = target;+ if (!current || pending) return;+ onClose();+ try {+ await new Promise((resolve) => setTimeout(resolve, 120));+ await action(current);+ } catch (actionError) {+ if (actionError instanceof MobileResourceCancelledError) {+ return;+ }+ Alert.alert(+ failureTitle,+ actionError instanceof Error ? actionError.message : labels.failed+ );+ }+ };+const confirmDelete = () => {Alert.alert(deleteTitle, deleteConfirm, [{ text: labels.cancel, style: "cancel" },@@ -180,8 +215,18 @@ export const MobileResourceActions = ({{mode === "actions" ? (<View style={styles.actions}>- <ResourceActionRow icon={<Download color="#0f172a" size={19} />} label={labels.download} onPress={() => void run(() => onDownload(target))} pending={pending} />- <ResourceActionRow icon={<HardDrive color="#0f172a" size={19} />} label={labels.saveAs} onPress={() => void run(() => onSaveAs(target))} pending={pending} />+ <ResourceActionRow+ icon={<Download color="#0f172a" size={19} />}+ label={labels.download}+ onPress={() => void runSystemUiAction((current) => onDownload(current), labels.failed)}+ pending={pending}+ />+ <ResourceActionRow+ icon={<HardDrive color="#0f172a" size={19} />}+ label={labels.saveAs}+ onPress={() => void runSystemUiAction((current) => onSaveAs(current), labels.exportFailed)}+ pending={pending}+ /><ResourceActionRow disabled={!canMutate} icon={<Pencil color={canMutate ? "#0f172a" : "#94a3b8"} size={19} />} label={labels.rename} onPress={() => setMode("rename")} pending={pending} /><View style={styles.divider} /><ResourceActionRow danger disabled={!canMutate} icon={<Trash2 color={canMutate ? "#be123c" : "#94a3b8"} size={19} />} label={labels.delete} onPress={confirmDelete} pending={pending} />diff --git a/apps/mobile/src/lib/mobile-attachments.test.mjs b/apps/mobile/src/lib/mobile-attachments.test.mjsindex aadc2297..f83d42d3 100644--- a/apps/mobile/src/lib/mobile-attachments.test.mjs+++ b/apps/mobile/src/lib/mobile-attachments.test.mjs@@ -7,8 +7,11 @@ import {getParagraphAttachmentTarget,parseMobileAttachmentTargetJson,parseMobileResourceTargetJson,+ readBlobAsUint8Array,renameMobileAttachmentInDoc,renameMobileResourceInDoc,+ resolveExportFilename,+ resolveResourceMimeType,} from "./mobile-attachments.ts";const href = "/api/v1/resources/res_123/blob";@@ -74,4 +77,43 @@ describe("mobile attachments", () => {content: [{ type: "paragraph" }],});});++ test("resolves export mime types and filenames for SAF", () => {+ expect(resolveResourceMimeType("photo.webp", "")).toBe("image/webp");+ expect(resolveResourceMimeType("EdgeEver 极客猫猫", "image/svg+xml")).toBe("image/svg+xml");+ expect(resolveExportFilename("EdgeEver 极客猫猫", "image/svg+xml")).toBe("EdgeEver 极客猫猫.svg");+ expect(resolveExportFilename("report.pdf", "application/pdf")).toBe("report.pdf");+ });++ test("reads blob bytes via FileReader when Blob.arrayBuffer is missing (React Native)", async () => {+ const payload = new Uint8Array([1, 2, 3, 250]);+ const standard = new Blob([payload], { type: "image/webp" });+ expect([...await readBlobAsUint8Array(standard)]).toEqual([1, 2, 3, 250]);++ // RN Blob has no arrayBuffer(); previously openMobileResource threw+ // "undefined is not a function" at blob.arrayBuffer().+ const rnLike = { type: "image/webp", size: payload.byteLength };+ expect(rnLike.arrayBuffer).toBeUndefined();++ const OriginalFileReader = globalThis.FileReader;+ class FakeFileReader {+ result = null;+ error = null;+ onerror = null;+ onloadend = null;+ readAsArrayBuffer(blob) {+ expect(blob).toBe(rnLike);+ void Promise.resolve().then(() => {+ this.result = payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength);+ this.onloadend?.();+ });+ }+ }+ globalThis.FileReader = FakeFileReader;+ try {+ expect([...await readBlobAsUint8Array(/** @type {any} */ (rnLike))]).toEqual([1, 2, 3, 250]);+ } finally {+ globalThis.FileReader = OriginalFileReader;+ }+ });});diff --git a/apps/mobile/src/lib/mobile-attachments.ts b/apps/mobile/src/lib/mobile-attachments.tsindex e2383715..decba72f 100644--- a/apps/mobile/src/lib/mobile-attachments.ts+++ b/apps/mobile/src/lib/mobile-attachments.ts@@ -13,6 +13,29 @@ export type MobileImageTarget = MobileResourceTarget & { kind: "image" };type AttachmentClient = Pick<ReturnType<typeof createEdgeEverClient>, "getResourceBlob">;+/**+ * Convert a Blob to bytes. React Native's Blob polyfill has no arrayBuffer(),+ * so calling blob.arrayBuffer() throws "undefined is not a function".+ */+export const readBlobAsUint8Array = async (blob: Blob): Promise<Uint8Array> => {+ if (typeof blob.arrayBuffer === "function") {+ return new Uint8Array(await blob.arrayBuffer());+ }++ return await new Promise<Uint8Array>((resolve, reject) => {+ const reader = new FileReader();+ reader.onerror = () => reject(reader.error ?? new Error("资源读取失败"));+ reader.onloadend = () => {+ if (reader.result instanceof ArrayBuffer) {+ resolve(new Uint8Array(reader.result));+ return;+ }+ reject(new Error("资源读取失败"));+ };+ reader.readAsArrayBuffer(blob);+ });+};+type MarkdownNodeLike = {attributes?: Record<string, unknown>;children?: MarkdownNodeLike[];@@ -173,63 +196,147 @@ export const getMobileResourceUpdatePayload = getMobileAttachmentUpdatePayload;const safeCacheFilename = (filename: string) =>filename.trim().replace(/[\\/]/g, "-").replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 160) || "attachment";+const EXT_BY_MIME: Record<string, string> = {+ "application/pdf": ".pdf",+ "application/zip": ".zip",+ "image/gif": ".gif",+ "image/jpeg": ".jpg",+ "image/png": ".png",+ "image/svg+xml": ".svg",+ "image/webp": ".webp",+ "text/csv": ".csv",+ "text/plain": ".txt",+};++const MIME_BY_EXT: Record<string, string> = {+ csv: "text/csv",+ gif: "image/gif",+ jpeg: "image/jpeg",+ jpg: "image/jpeg",+ pdf: "application/pdf",+ png: "image/png",+ svg: "image/svg+xml",+ txt: "text/plain",+ webp: "image/webp",+ zip: "application/zip",+};++/** Infer a usable MIME type — empty blob.type is common for RN fetch results. */+export const resolveResourceMimeType = (filename: string, blobType?: string | null) => {+ const normalized = blobType?.trim().toLowerCase() ?? "";+ if (normalized && normalized !== "application/octet-stream") {+ return normalized;+ }+ const ext = filename.split(".").pop()?.toLowerCase() ?? "";+ return MIME_BY_EXT[ext] || "application/octet-stream";+};++/** SAF createFileAsync is unreliable without a file extension. */+export const resolveExportFilename = (filename: string, mimeType: string) => {+ const safe = safeCacheFilename(filename);+ if (/\.[a-z0-9]{1,8}$/i.test(safe)) {+ return safe;+ }+ return `${safe}${EXT_BY_MIME[mimeType] || ""}`;+};++export class MobileResourceCancelledError extends Error {+ readonly code = "cancelled" as const;++ constructor(message = "已取消导出") {+ super(message);+ this.name = "MobileResourceCancelledError";+ }+}+const cacheMobileResource = async (client: AttachmentClient, target: MobileResourceTarget) => {- const [{ Directory, File, Paths }, Sharing] = await Promise.all([- import("expo-file-system"),- import("expo-sharing"),- ]);+ const { Directory, File, Paths } = await import("expo-file-system");// The DOM editor resolves relative links against the instance URL for display.// The client itself prefixes the instance base URL, so always give it the// canonical relative resource path here.const blob = await client.getResourceBlob(`/api/v1/resources/${encodeURIComponent(target.resourceId)}/blob`);+ const bytes = await readBlobAsUint8Array(blob);const directory = new Directory(Paths.cache, "edgeever-attachments");if (!directory.exists) directory.create({ idempotent: true, intermediates: true });const file = new File(directory, `${target.resourceId}-${safeCacheFilename(target.filename)}`);if (file.exists) file.delete();file.create({ overwrite: true, intermediates: true });- file.write(new Uint8Array(await blob.arrayBuffer()));+ file.write(bytes);- return { blob, file, Sharing };+ return { blob, file };};-export const openMobileResource = async (client: AttachmentClient, target: MobileResourceTarget) => {- const { blob, file, Sharing } = await cacheMobileResource(client, target);-+const shareCachedResource = async (+ fileUri: string,+ options: { dialogTitle: string; mimeType: string }+) => {+ const Sharing = await import("expo-sharing");if (!(await Sharing.isAvailableAsync())) {- throw new Error("当前设备无法打开系统文件面板");+ throw new Error("当前设备无法打开系统分享面板");}- await Sharing.shareAsync(file.uri, {+ await Sharing.shareAsync(fileUri, {+ dialogTitle: options.dialogTitle,+ mimeType: options.mimeType,+ });+ return fileUri;+};++export const openMobileResource = async (client: AttachmentClient, target: MobileResourceTarget) => {+ const { blob, file } = await cacheMobileResource(client, target);+ const mimeType = resolveResourceMimeType(target.filename, blob.type);+ return shareCachedResource(file.uri, {dialogTitle: target.filename,- mimeType: blob.type || "application/octet-stream",+ mimeType,});- return file.uri;};+/**+ * Export resource to a user-chosen folder (Android SAF) or the system share sheet.+ * Android: the action sheet Modal must be closed first — SAF needs a free activity+ * result channel; otherwise the folder picker never appears and it looks like a no-op.+ */export const saveMobileResourceAs = async (client: AttachmentClient, target: MobileResourceTarget) => {- const { blob, file, Sharing } = await cacheMobileResource(client, target);const { Platform } = await import("react-native");+ const { blob, file } = await cacheMobileResource(client, target);+ const mimeType = resolveResourceMimeType(target.filename, blob.type);+ const exportName = resolveExportFilename(target.filename, mimeType);+if (Platform.OS === "android") {- const FileSystem = await import("expo-file-system/legacy");- const permission = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();- if (!permission.granted) return null;- const destination = await FileSystem.StorageAccessFramework.createFileAsync(- permission.directoryUri,- target.filename,- blob.type || "application/octet-stream"- );- await FileSystem.StorageAccessFramework.writeAsStringAsync(destination, await file.base64(), {- encoding: FileSystem.EncodingType.Base64,- });- return destination;- }- if (!(await Sharing.isAvailableAsync())) {- throw new Error("当前设备无法打开系统导出面板");+ try {+ const FileSystem = await import("expo-file-system/legacy");+ const permission = await FileSystem.StorageAccessFramework.requestDirectoryPermissionsAsync();+ if (!permission.granted) {+ // Do not return null — callers treated that as success and closed the sheet.+ throw new MobileResourceCancelledError("已取消导出");+ }+ const destination = await FileSystem.StorageAccessFramework.createFileAsync(+ permission.directoryUri,+ exportName,+ mimeType+ );+ const base64 = await file.base64();+ await FileSystem.StorageAccessFramework.writeAsStringAsync(destination, base64, {+ encoding: FileSystem.EncodingType.Base64,+ });+ return { kind: "saf" as const, uri: destination, filename: exportName };+ } catch (error) {+ if (error instanceof MobileResourceCancelledError) {+ throw error;+ }+ // SAF is flaky on some OEM builds — fall back to the share sheet so export still works.+ await shareCachedResource(file.uri, {+ dialogTitle: `导出 ${exportName}`,+ mimeType,+ });+ return { kind: "share" as const, uri: file.uri, filename: exportName };+ }}- await Sharing.shareAsync(file.uri, {- dialogTitle: `导出 ${target.filename}`,- mimeType: blob.type || "application/octet-stream",++ await shareCachedResource(file.uri, {+ dialogTitle: `导出 ${exportName}`,+ mimeType,});- return file.uri;+ return { kind: "share" as const, uri: file.uri, filename: exportName };};export const openMobileAttachment = openMobileResource;diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsxindex 1bb5d6ea..b6bfd6ed 100644--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx@@ -364,7 +364,13 @@ export const MemoDetailModal = ({}, [client, resolvedLocale]);const saveResourceAs = useCallback(async (target: MobileResourceTarget) => {if (!client) throw new Error(resolvedLocale === "en-US" ? "The resource client is unavailable." : "当前无法读取资源。");- await saveMobileResourceAs(client, target);+ const result = await saveMobileResourceAs(client, target);+ if (result.kind === "saf") {+ Alert.alert(+ resolvedLocale === "en-US" ? "Exported" : "导出成功",+ resolvedLocale === "en-US" ? `Saved ${result.filename}` : `已保存:${result.filename}`+ );+ }}, [client, resolvedLocale]);const loadViewerResource = useCallback((source: string) => {diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsxindex b66c63ad..ca2d7232 100644--- a/apps/mobile/src/screens/WorkspaceScreen.tsx+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx@@ -1911,7 +1911,13 @@ const CreateMemoModal = ({const saveResourceAs = useCallback(async (target: MobileResourceTarget) => {if (!client) throw new Error(resolvedLocale === "en-US" ? "The resource client is unavailable." : "当前无法读取资源。");- await saveMobileResourceAs(client, target);+ const result = await saveMobileResourceAs(client, target);+ if (result.kind === "saf") {+ Alert.alert(+ resolvedLocale === "en-US" ? "Exported" : "导出成功",+ resolvedLocale === "en-US" ? `Saved ${result.filename}` : `已保存:${result.filename}`+ );+ }}, [client, resolvedLocale]);const renameResource = useCallback(async (target: MobileResourceTarget, filename: string) => {@@ -2457,7 +2463,13 @@ const RichEditorModal = ({const saveResourceAs = useCallback(async (target: MobileResourceTarget) => {if (!client) throw new Error(resolvedLocale === "en-US" ? "The resource client is unavailable." : "当前无法读取资源。");- await saveMobileResourceAs(client, target);+ const result = await saveMobileResourceAs(client, target);+ if (result.kind === "saf") {+ Alert.alert(+ resolvedLocale === "en-US" ? "Exported" : "导出成功",+ resolvedLocale === "en-US" ? `Saved ${result.filename}` : `已保存:${result.filename}`+ );+ }}, [client, resolvedLocale]);const renameResource = useCallback(async (target: MobileResourceTarget, filename: string) => {