接入原生壳分享卡图片导出
新增 file.exportImage 宿主能力契约 分享卡下载在原生壳中优先走宿主图片导出 Expo 壳写入缓存图片并调用系统分享保存 Tauri 壳通过保存对话框写入图片字节 补齐能力漂移检查、测试和架构文档
This commit is contained in:
@@ -139,9 +139,11 @@ const requiredMainSnippets = [
|
||||
'"app.setTitle"',
|
||||
'"clipboard.writeText"',
|
||||
'"file.exportText"',
|
||||
'"file.exportImage"',
|
||||
'tauri_plugin_dialog::init()',
|
||||
'"copied_to_clipboard"',
|
||||
'"file export cancelled"',
|
||||
'BASE64_STANDARD.decode',
|
||||
'set_title',
|
||||
];
|
||||
|
||||
|
||||
1
apps/desktop-shell/src-tauri/Cargo.lock
generated
1
apps/desktop-shell/src-tauri/Cargo.lock
generated
@@ -1277,6 +1277,7 @@ dependencies = [
|
||||
name = "genarrative-desktop-shell"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tauri",
|
||||
|
||||
@@ -8,6 +8,7 @@ publish = false
|
||||
tauri-build = { version = "2.6.2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
base64 = "0.22"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tauri = { version = "2.11.2", features = [] }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine as _};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
use std::fs;
|
||||
@@ -14,6 +15,7 @@ const HOST_BRIDGE_VERSION: u8 = 1;
|
||||
const WEB_APP_ORIGIN: &str = "https://app.genarrative.world";
|
||||
const EXTERNAL_URL_PROTOCOLS: [&str; 4] = ["http:", "https:", "mailto:", "tel:"];
|
||||
const EXPORT_TEXT_MAX_BYTES: usize = 5 * 1024 * 1024;
|
||||
const EXPORT_IMAGE_MAX_BYTES: usize = 5 * 1024 * 1024;
|
||||
const EXPORT_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
|
||||
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
|
||||
|
||||
@@ -83,6 +85,7 @@ fn capabilities() -> Vec<&'static str> {
|
||||
"app.setTitle",
|
||||
"clipboard.writeText",
|
||||
"file.exportText",
|
||||
"file.exportImage",
|
||||
]
|
||||
}
|
||||
|
||||
@@ -271,6 +274,83 @@ fn write_export_text_file(path: PathBuf, content: String) -> Result<usize, Strin
|
||||
Ok(content.len())
|
||||
}
|
||||
|
||||
fn export_image_extension(mime_type: &str) -> Option<&'static str> {
|
||||
match mime_type {
|
||||
"image/png" => Some("png"),
|
||||
"image/jpeg" => Some("jpg"),
|
||||
"image/webp" => Some("webp"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_export_image_file_name(raw_file_name: &str, mime_type: &str) -> String {
|
||||
let mut file_name = normalize_export_file_name(raw_file_name);
|
||||
let extension = export_image_extension(mime_type).unwrap_or("png");
|
||||
if !file_name.to_ascii_lowercase().ends_with(&format!(".{}", extension)) {
|
||||
file_name.push('.');
|
||||
file_name.push_str(extension);
|
||||
}
|
||||
file_name
|
||||
}
|
||||
|
||||
fn export_image_payload(
|
||||
request: &HostBridgeRequest,
|
||||
) -> Result<(String, Vec<u8>), HostBridgeResponse> {
|
||||
let payload = request.payload.as_ref().ok_or_else(|| {
|
||||
failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"fileName, mimeType and base64Data are required",
|
||||
)
|
||||
})?;
|
||||
let mime_type = payload
|
||||
.get("mimeType")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "mimeType is required"))?;
|
||||
if export_image_extension(mime_type).is_none() {
|
||||
return Err(failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"mimeType must be an allowed image type",
|
||||
));
|
||||
}
|
||||
|
||||
let base64_data = payload
|
||||
.get("base64Data")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| failed(request.id.clone(), "invalid_request", "base64Data is required"))?;
|
||||
let bytes = BASE64_STANDARD.decode(base64_data).map_err(|_| {
|
||||
failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"base64Data is invalid",
|
||||
)
|
||||
})?;
|
||||
if bytes.len() > EXPORT_IMAGE_MAX_BYTES {
|
||||
return Err(failed(
|
||||
request.id.clone(),
|
||||
"invalid_request",
|
||||
"image exceeds file export size limit",
|
||||
));
|
||||
}
|
||||
|
||||
let file_name = payload
|
||||
.get("fileName")
|
||||
.and_then(Value::as_str)
|
||||
.map(|file_name| normalize_export_image_file_name(file_name, mime_type))
|
||||
.unwrap_or_else(|| normalize_export_image_file_name("genarrative-share-card", mime_type));
|
||||
|
||||
Ok((file_name, bytes))
|
||||
}
|
||||
|
||||
fn write_export_bytes_file(path: PathBuf, bytes: Vec<u8>) -> Result<usize, String> {
|
||||
let byte_count = bytes.len();
|
||||
fs::write(path, bytes).map_err(|error| error.to_string())?;
|
||||
Ok(byte_count)
|
||||
}
|
||||
|
||||
fn payload_string<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
|
||||
value
|
||||
.get(field)
|
||||
@@ -468,6 +548,41 @@ async fn host_bridge_request(
|
||||
}),
|
||||
)
|
||||
}
|
||||
"file.exportImage" => {
|
||||
let (file_name, bytes) = match export_image_payload(&request) {
|
||||
Ok(payload) => payload,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let file_path = app
|
||||
.dialog()
|
||||
.file()
|
||||
.add_filter("Image", &["png", "jpg", "jpeg", "webp"])
|
||||
.set_file_name(file_name.clone())
|
||||
.blocking_save_file();
|
||||
let Some(file_path) = file_path else {
|
||||
return failed(request.id, "cancelled", "file export cancelled");
|
||||
};
|
||||
let path = match file_path.into_path() {
|
||||
Ok(path) => path,
|
||||
Err(error) => return failed(request.id, "host_error", error.to_string()),
|
||||
};
|
||||
let export_result =
|
||||
tauri::async_runtime::spawn_blocking(move || write_export_bytes_file(path, bytes))
|
||||
.await;
|
||||
let byte_count = match export_result {
|
||||
Ok(Ok(byte_count)) => byte_count,
|
||||
Ok(Err(error)) => return failed(request.id, "host_error", error),
|
||||
Err(error) => return failed(request.id, "host_error", error.to_string()),
|
||||
};
|
||||
ok(
|
||||
request.id,
|
||||
json!({
|
||||
"action": "saved",
|
||||
"fileName": file_name,
|
||||
"bytes": byte_count,
|
||||
}),
|
||||
)
|
||||
}
|
||||
"app.setTitle" => {
|
||||
let title = match required_string_payload(&request, "title")
|
||||
.ok()
|
||||
@@ -586,6 +701,10 @@ mod tests {
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("file.exportText")));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("file.exportImage")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -756,6 +875,71 @@ mod tests {
|
||||
fs::remove_file(path).expect("remove export file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_image_payload_decodes_allowed_image_base64() {
|
||||
let mut valid = request("file.exportImage");
|
||||
valid.payload = Some(json!({
|
||||
"fileName": "分享:卡?.png",
|
||||
"base64Data": "c2hhcmUtY2FyZA==",
|
||||
"mimeType": "image/png"
|
||||
}));
|
||||
|
||||
let (file_name, bytes) = export_image_payload(&valid).expect("image payload");
|
||||
|
||||
assert_eq!(file_name, "分享-卡-.png");
|
||||
assert_eq!(bytes, b"share-card");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_image_payload_rejects_invalid_mime_and_base64() {
|
||||
let mut invalid_mime = request("file.exportImage");
|
||||
invalid_mime.payload = Some(json!({
|
||||
"fileName": "分享卡.txt",
|
||||
"base64Data": "c2hhcmUtY2FyZA==",
|
||||
"mimeType": "text/plain"
|
||||
}));
|
||||
let response = export_image_payload(&invalid_mime).expect_err("invalid mime");
|
||||
assert_eq!(response.error.expect("error").code, "invalid_request");
|
||||
|
||||
let mut invalid_base64 = request("file.exportImage");
|
||||
invalid_base64.payload = Some(json!({
|
||||
"fileName": "分享卡.png",
|
||||
"base64Data": "not base64!",
|
||||
"mimeType": "image/png"
|
||||
}));
|
||||
let response = export_image_payload(&invalid_base64).expect_err("invalid base64");
|
||||
assert_eq!(response.error.expect("error").message, "base64Data is invalid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_image_payload_rejects_oversized_image() {
|
||||
let mut invalid = request("file.exportImage");
|
||||
invalid.payload = Some(json!({
|
||||
"fileName": "分享卡.png",
|
||||
"base64Data": BASE64_STANDARD.encode(vec![1u8; EXPORT_IMAGE_MAX_BYTES + 1]),
|
||||
"mimeType": "image/png"
|
||||
}));
|
||||
|
||||
let response = export_image_payload(&invalid).expect_err("oversized image");
|
||||
|
||||
assert_eq!(response.error.expect("error").message, "image exceeds file export size limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_export_bytes_file_persists_binary_content() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"genarrative-host-bridge-share-card-{}.png",
|
||||
std::process::id()
|
||||
));
|
||||
|
||||
let bytes = write_export_bytes_file(path.clone(), vec![0x89, b'P', b'N', b'G'])
|
||||
.expect("write image file");
|
||||
|
||||
assert_eq!(bytes, 4);
|
||||
assert_eq!(fs::read(&path).expect("read image file"), vec![0x89, b'P', b'N', b'G']);
|
||||
fs::remove_file(path).expect("remove image file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_text_uses_direct_share_payload() {
|
||||
let state = DesktopShareState::default();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"build": {
|
||||
"beforeDevCommand": "npm --prefix ../.. run dev:web",
|
||||
"beforeBuildCommand": "npm --prefix ../.. run build:raw && npm run typecheck",
|
||||
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText",
|
||||
"devUrl": "http://127.0.0.1:3000/?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"frontendDist": "../../../dist"
|
||||
},
|
||||
"app": {
|
||||
@@ -14,7 +14,7 @@
|
||||
{
|
||||
"create": false,
|
||||
"label": "main",
|
||||
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText",
|
||||
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,clipboard.writeText,file.exportText,file.exportImage",
|
||||
"title": "Genarrative",
|
||||
"width": 1280,
|
||||
"height": 820,
|
||||
|
||||
@@ -118,8 +118,10 @@ for (const dependency of ['expo-file-system', 'expo-sharing']) {
|
||||
|
||||
for (const snippet of [
|
||||
'file.exportText',
|
||||
'file.exportImage',
|
||||
'Sharing.shareAsync',
|
||||
'normalizeHostBridgeExportFileName',
|
||||
'base64Data',
|
||||
]) {
|
||||
if (!bridgeSource.includes(snippet)) {
|
||||
throw new Error(`mobile shell HostBridge missing ${snippet}`);
|
||||
@@ -140,6 +142,7 @@ for (const capability of [
|
||||
'app.openExternalUrl',
|
||||
'clipboard.writeText',
|
||||
'file.exportText',
|
||||
'file.exportImage',
|
||||
'haptics.impact',
|
||||
]) {
|
||||
if (!mobileCapabilitySet.has(capability)) {
|
||||
|
||||
@@ -22,7 +22,12 @@ vi.mock('expo-clipboard', () => ({
|
||||
}));
|
||||
|
||||
const writtenFiles = vi.hoisted(
|
||||
() => [] as { uri: string; content: string }[],
|
||||
() =>
|
||||
[] as {
|
||||
uri: string;
|
||||
content: string;
|
||||
options?: { encoding?: 'utf8' | 'base64' };
|
||||
}[],
|
||||
);
|
||||
|
||||
vi.mock('expo-file-system', () => ({
|
||||
@@ -36,10 +41,11 @@ vi.mock('expo-file-system', () => ({
|
||||
this.uri = `file:///cache/${fileName}`;
|
||||
}
|
||||
|
||||
write(content: string) {
|
||||
write(content: string, options?: { encoding?: 'utf8' | 'base64' }) {
|
||||
writtenFiles.push({
|
||||
uri: this.uri,
|
||||
content,
|
||||
options,
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -309,6 +315,7 @@ describe('handleMobileHostBridgeMessage', () => {
|
||||
{
|
||||
uri: 'file:///cache/作品-记录-.txt',
|
||||
content: '暖灯猫街',
|
||||
options: undefined,
|
||||
},
|
||||
]);
|
||||
expect(Sharing.shareAsync).toHaveBeenCalledWith(
|
||||
@@ -352,4 +359,61 @@ describe('handleMobileHostBridgeMessage', () => {
|
||||
expect(writtenFiles).toEqual([]);
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('file.exportImage 写入缓存图片并调起系统分享', async () => {
|
||||
const response = await send(
|
||||
request('file.exportImage', {
|
||||
fileName: ' ../分享:卡?.png ',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
);
|
||||
|
||||
const okResponse = expectOk(response);
|
||||
|
||||
expect(okResponse.result).toEqual({
|
||||
action: 'saved',
|
||||
fileName: '分享-卡-.png',
|
||||
bytes: 10,
|
||||
});
|
||||
expect(writtenFiles).toEqual([
|
||||
{
|
||||
uri: 'file:///cache/分享-卡-.png',
|
||||
content: 'c2hhcmUtY2FyZA==',
|
||||
options: { encoding: 'base64' },
|
||||
},
|
||||
]);
|
||||
expect(Sharing.shareAsync).toHaveBeenCalledWith(
|
||||
'file:///cache/分享-卡-.png',
|
||||
{
|
||||
mimeType: 'image/png',
|
||||
UTI: 'public.png',
|
||||
dialogTitle: '分享-卡-.png',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('file.exportImage 拒绝非图片 MIME 与超限内容', async () => {
|
||||
const unsupportedMime = await send(
|
||||
request('file.exportImage', {
|
||||
fileName: '分享卡.txt',
|
||||
base64Data: 'c2hhcmUtY2FyZA==',
|
||||
mimeType: 'text/plain',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(expectFailed(unsupportedMime).error.code).toBe('invalid_request');
|
||||
|
||||
const oversized = await send(
|
||||
request('file.exportImage', {
|
||||
fileName: '分享卡.png',
|
||||
base64Data: `${'A'.repeat(7 * 1024 * 1024)}`,
|
||||
mimeType: 'image/png',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(expectFailed(oversized).error.code).toBe('invalid_request');
|
||||
expect(writtenFiles).toEqual([]);
|
||||
expect(Sharing.shareAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,8 @@ import { Platform, Share } from 'react-native';
|
||||
|
||||
import {
|
||||
type ClipboardWriteTextPayload,
|
||||
type FileExportImagePayload,
|
||||
type FileExportImageResult,
|
||||
type FileExportTextPayload,
|
||||
type FileExportTextResult,
|
||||
type HapticsImpactPayload,
|
||||
@@ -27,6 +29,12 @@ import { resolveMobileShellWebViewUrl } from './mobileShellNavigation';
|
||||
|
||||
const WEB_APP_ORIGIN = 'https://app.genarrative.world';
|
||||
const EXPORT_TEXT_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const EXPORT_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
|
||||
const EXPORT_IMAGE_MIME_TYPES = new Set([
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/webp',
|
||||
]);
|
||||
|
||||
export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
|
||||
'host.getRuntime',
|
||||
@@ -38,6 +46,7 @@ export const MOBILE_HOST_CAPABILITIES: HostBridgeCapability[] = [
|
||||
'app.openExternalUrl',
|
||||
'clipboard.writeText',
|
||||
'file.exportText',
|
||||
'file.exportImage',
|
||||
'haptics.impact',
|
||||
];
|
||||
|
||||
@@ -86,6 +95,28 @@ function utf8ByteLength(value: string) {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function normalizedBase64Data(value: unknown) {
|
||||
if (typeof value !== 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalizedValue = value.trim();
|
||||
if (
|
||||
!normalizedValue ||
|
||||
normalizedValue.length % 4 !== 0 ||
|
||||
!/^[A-Za-z0-9+/]+={0,2}$/u.test(normalizedValue)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizedValue;
|
||||
}
|
||||
|
||||
function base64DecodedByteLength(value: string) {
|
||||
const padding = value.endsWith('==') ? 2 : value.endsWith('=') ? 1 : 0;
|
||||
return Math.floor((value.length * 3) / 4) - padding;
|
||||
}
|
||||
|
||||
function isHostBridgeRequest(value: unknown): value is HostBridgeRequest {
|
||||
if (!value || typeof value !== 'object') {
|
||||
return false;
|
||||
@@ -193,6 +224,46 @@ async function exportTextFile(payload: unknown): Promise<FileExportTextResult> {
|
||||
};
|
||||
}
|
||||
|
||||
async function exportImageFile(payload: unknown): Promise<FileExportImageResult> {
|
||||
const exportPayload = payload as FileExportImagePayload | undefined;
|
||||
const mimeType = exportPayload?.mimeType;
|
||||
if (typeof mimeType !== 'string' || !EXPORT_IMAGE_MIME_TYPES.has(mimeType)) {
|
||||
throw invalidRequest('mimeType must be an allowed image type');
|
||||
}
|
||||
|
||||
const base64Data = normalizedBase64Data(exportPayload?.base64Data);
|
||||
if (!base64Data) {
|
||||
throw invalidRequest('base64Data is required');
|
||||
}
|
||||
const bytes = base64DecodedByteLength(base64Data);
|
||||
if (bytes > EXPORT_IMAGE_MAX_BYTES) {
|
||||
throw invalidRequest('image exceeds file export size limit');
|
||||
}
|
||||
|
||||
const isSharingAvailable = await Sharing.isAvailableAsync();
|
||||
if (!isSharingAvailable) {
|
||||
throw {
|
||||
code: 'unsupported_capability',
|
||||
message: 'file sharing is unavailable in mobile shell',
|
||||
} satisfies HostBridgeError;
|
||||
}
|
||||
|
||||
const fileName = normalizeHostBridgeExportFileName(exportPayload?.fileName);
|
||||
const file = new File(Paths.cache, fileName);
|
||||
file.write(base64Data, { encoding: 'base64' });
|
||||
await Sharing.shareAsync(file.uri, {
|
||||
mimeType,
|
||||
UTI: mimeType === 'image/png' ? 'public.png' : 'public.image',
|
||||
dialogTitle: fileName,
|
||||
});
|
||||
|
||||
return {
|
||||
action: 'saved',
|
||||
fileName,
|
||||
bytes,
|
||||
};
|
||||
}
|
||||
|
||||
async function runHaptics(payload: unknown) {
|
||||
const style = (payload as HapticsImpactPayload | undefined)?.style;
|
||||
const impactStyle =
|
||||
@@ -322,6 +393,8 @@ async function handleRequest(request: HostBridgeRequest) {
|
||||
return ok(request, await writeClipboard(request.payload));
|
||||
case 'file.exportText':
|
||||
return ok(request, await exportTextFile(request.payload));
|
||||
case 'file.exportImage':
|
||||
return ok(request, await exportImageFile(request.payload));
|
||||
case 'haptics.impact':
|
||||
return ok(request, await runHaptics(request.payload));
|
||||
case 'share.open':
|
||||
|
||||
Reference in New Issue
Block a user