接入原生壳文本文件导入能力
新增 file.importText HostBridge 契约和 H5 facade 移动端通过 Expo DocumentPicker 读取受控文本文件 桌面端通过 Tauri 文件选择框读取受控文本文件 更新壳能力检查、测试、方案文档和共享决策记录
This commit is contained in:
@@ -145,6 +145,7 @@ const requiredMainSnippets = [
|
||||
'"clipboard.writeText"',
|
||||
'"clipboard.readText"',
|
||||
'"file.exportText"',
|
||||
'"file.importText"',
|
||||
'"file.exportImage"',
|
||||
'"file.importImage"',
|
||||
'"file.imageDropped"',
|
||||
@@ -157,6 +158,7 @@ const requiredMainSnippets = [
|
||||
'"file import cancelled"',
|
||||
'BASE64_STANDARD.decode',
|
||||
'blocking_pick_file',
|
||||
'import_text_file_payload',
|
||||
'import_image_file_payload',
|
||||
'set_title',
|
||||
'set_badge_count',
|
||||
|
||||
@@ -23,6 +23,7 @@ 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 IMPORT_TEXT_MAX_BYTES: u64 = 5 * 1024 * 1024;
|
||||
const IMPORT_IMAGE_MAX_BYTES: u64 = 10 * 1024 * 1024;
|
||||
const EXPORT_FILE_NAME_FALLBACK: &str = "genarrative-export.txt";
|
||||
const EXPORT_FILE_NAME_MAX_LENGTH: usize = 120;
|
||||
@@ -104,6 +105,7 @@ fn capabilities() -> Vec<&'static str> {
|
||||
"clipboard.writeText",
|
||||
"clipboard.readText",
|
||||
"file.exportText",
|
||||
"file.importText",
|
||||
"file.exportImage",
|
||||
"file.importImage",
|
||||
"file.imageDropped",
|
||||
@@ -383,6 +385,54 @@ fn write_export_text_file(path: PathBuf, content: String) -> Result<usize, Strin
|
||||
Ok(content.len())
|
||||
}
|
||||
|
||||
fn import_text_mime_type(path: &Path) -> Option<&'static str> {
|
||||
match path
|
||||
.extension()
|
||||
.and_then(|extension| extension.to_str())
|
||||
.map(|extension| extension.to_ascii_lowercase())
|
||||
.as_deref()
|
||||
{
|
||||
Some("txt") => Some("text/plain"),
|
||||
Some("md") | Some("markdown") => Some("text/markdown"),
|
||||
Some("csv") => Some("text/csv"),
|
||||
Some("json") => Some("application/json"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn import_text_file_payload(path: PathBuf) -> Result<Value, String> {
|
||||
if !path.is_file() {
|
||||
return Err("text file is required".to_string());
|
||||
}
|
||||
|
||||
let mime_type =
|
||||
import_text_mime_type(&path).ok_or_else(|| "text MIME must be allowed".to_string())?;
|
||||
let metadata = fs::metadata(&path).map_err(|error| error.to_string())?;
|
||||
let byte_count = metadata.len();
|
||||
if byte_count == 0 || byte_count > IMPORT_TEXT_MAX_BYTES {
|
||||
return Err("text exceeds import size limit".to_string());
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(&path).map_err(|error| error.to_string())?;
|
||||
let byte_count = content.len() as u64;
|
||||
if byte_count == 0 || byte_count > IMPORT_TEXT_MAX_BYTES {
|
||||
return Err("text exceeds import size limit".to_string());
|
||||
}
|
||||
let file_name = path
|
||||
.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.map(normalize_export_file_name)
|
||||
.unwrap_or_else(|| "genarrative-import.txt".to_string());
|
||||
|
||||
Ok(json!({
|
||||
"action": "selected",
|
||||
"fileName": file_name,
|
||||
"content": content,
|
||||
"mimeType": mime_type,
|
||||
"bytes": byte_count,
|
||||
}))
|
||||
}
|
||||
|
||||
fn export_image_extension(mime_type: &str) -> Option<&'static str> {
|
||||
match mime_type {
|
||||
"image/png" => Some("png"),
|
||||
@@ -910,6 +960,27 @@ async fn host_bridge_request(
|
||||
}),
|
||||
)
|
||||
}
|
||||
"file.importText" => {
|
||||
let file_path = app
|
||||
.dialog()
|
||||
.file()
|
||||
.add_filter("Text", &["txt", "md", "markdown", "csv", "json"])
|
||||
.blocking_pick_file();
|
||||
let Some(file_path) = file_path else {
|
||||
return failed(request.id, "cancelled", "file import cancelled");
|
||||
};
|
||||
let path = match file_path.into_path() {
|
||||
Ok(path) => path,
|
||||
Err(error) => return failed(request.id, "host_error", error.to_string()),
|
||||
};
|
||||
let import_result =
|
||||
tauri::async_runtime::spawn_blocking(move || import_text_file_payload(path)).await;
|
||||
match import_result {
|
||||
Ok(Ok(payload)) => ok(request.id, payload),
|
||||
Ok(Err(error)) => failed(request.id, "invalid_request", error),
|
||||
Err(error) => failed(request.id, "host_error", error.to_string()),
|
||||
}
|
||||
}
|
||||
"file.exportImage" => {
|
||||
let (file_name, bytes) = match export_image_payload(&request) {
|
||||
Ok(payload) => payload,
|
||||
@@ -1153,6 +1224,10 @@ mod tests {
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("file.exportText")));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.contains(&json!("file.importText")));
|
||||
assert!(result["capabilities"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
@@ -1457,6 +1532,57 @@ mod tests {
|
||||
fs::remove_file(path).expect("remove export file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_text_file_payload_reads_allowed_text_without_exposing_path() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"genarrative-host-bridge-import-text-{}.md",
|
||||
std::process::id()
|
||||
));
|
||||
fs::write(&path, "暖灯猫街").expect("write import text");
|
||||
|
||||
let payload = import_text_file_payload(path.clone()).expect("payload");
|
||||
|
||||
assert_eq!(payload["action"], "selected");
|
||||
assert_eq!(
|
||||
payload["fileName"],
|
||||
path.file_name().unwrap().to_str().unwrap()
|
||||
);
|
||||
assert_eq!(payload["content"], "暖灯猫街");
|
||||
assert_eq!(payload["mimeType"], "text/markdown");
|
||||
assert_eq!(payload["bytes"], "暖灯猫街".len() as u64);
|
||||
assert!(!payload
|
||||
.to_string()
|
||||
.contains(path.to_string_lossy().as_ref()));
|
||||
|
||||
fs::remove_file(path).expect("remove import text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_text_file_payload_rejects_invalid_or_oversized_text() {
|
||||
let image_path = std::env::temp_dir().join(format!(
|
||||
"genarrative-host-bridge-import-text-{}.png",
|
||||
std::process::id()
|
||||
));
|
||||
fs::write(&image_path, "text").expect("write image-like text");
|
||||
assert_eq!(
|
||||
import_text_file_payload(image_path.clone()).unwrap_err(),
|
||||
"text MIME must be allowed"
|
||||
);
|
||||
fs::remove_file(image_path).expect("remove image-like text");
|
||||
|
||||
let large_path = std::env::temp_dir().join(format!(
|
||||
"genarrative-host-bridge-import-text-large-{}.txt",
|
||||
std::process::id()
|
||||
));
|
||||
fs::write(&large_path, "a".repeat(IMPORT_TEXT_MAX_BYTES as usize + 1))
|
||||
.expect("write large text");
|
||||
assert_eq!(
|
||||
import_text_file_payload(large_path.clone()).unwrap_err(),
|
||||
"text exceeds import size limit"
|
||||
);
|
||||
fs::remove_file(large_path).expect("remove large text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_image_payload_decodes_allowed_image_base64() {
|
||||
let mut valid = request("file.exportImage");
|
||||
|
||||
@@ -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,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
|
||||
"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,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.importText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
|
||||
"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,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
|
||||
"url": "index.html?clientRuntime=native_app&clientType=native_app&hostShell=tauri_desktop&hostPlatform=unknown&hostVersion=0.1.0&bridgeVersion=1&hostCapabilities=host.getRuntime,appearance.getColorScheme,app.lifecycle,share.open,share.setTarget,navigation.openNativePage,app.openExternalUrl,app.setTitle,app.setBadgeCount,network.status,network.statusChanged,clipboard.writeText,clipboard.readText,file.exportText,file.importText,file.exportImage,file.importImage,file.imageDropped,notification.showLocal",
|
||||
"title": "Genarrative",
|
||||
"width": 1280,
|
||||
"height": 820,
|
||||
|
||||
Reference in New Issue
Block a user