import {Platform} from 'react-native'; import * as DocumentPicker from 'expo-document-picker'; import {File,FileMode,Paths,Directory} from 'expo-file-system'; import * as Sharing from 'expo-sharing'; import {fetch as expoFetch} from 'expo/fetch'; import type {ApiClient} from './core/network'; import type {Row} from './core/modules'; import type {UploadSource} from './core/managed-transfer'; export async function pickManagedFile():Promise{ const chosen=await DocumentPicker.getDocumentAsync({type:'*/*',multiple:false,copyToCacheDirectory:true});if(chosen.canceled)return null;const asset=chosen.assets[0]; if(Platform.OS==='web'){const blob=asset.file;if(!blob)throw new Error('无法读取选择的文件');return {name:asset.name,size:blob.size,read:async(start,length)=>new Uint8Array(await blob.slice(start,start+length).arrayBuffer()),close(){}};} const file=new File(asset.uri);if(file.size>1024**3||!file.size){try{if(file.uri.startsWith(Paths.cache.uri))file.delete();}catch{}throw new Error('请选择非空文件,单个最多1GB');}const handle=file.open(FileMode.ReadOnly),chunkFile=new File(Paths.cache,'upload-chunk-'+Date.now()+'-'+Math.random().toString(16).slice(2)+'.bin'); return {name:asset.name,size:file.size,read:async(start,length)=>{handle.offset=start;return handle.readBytes(length);},part:async bytes=>{chunkFile.write(bytes);return {uri:chunkFile.uri,name:'chunk.bin',type:'application/octet-stream'};},close(){handle.close();try{if(chunkFile.exists)chunkFile.delete();}catch{}try{if(file.uri.startsWith(Paths.cache.uri))file.delete();}catch{}}}; } export async function downloadManagedFile(api:ApiClient,file:Row,signal:AbortSignal,onProgress:(value:number)=>void,action:'open'|'save'='save'){ const path=`/system/files/${encodeURIComponent(file.id)}/content`,name=String(file.name||'file').replace(/[\\/:*?"<>|\x00-\x1f]/g,'_').slice(0,160); if(Platform.OS==='web'){ const picker=(globalThis as any).showSaveFilePicker;if(picker){const out=await(await picker({suggestedName:name})).createWritable();try{await api.download(path,b=>out.write(b),{signal,onProgress:(n,total)=>onProgress(total?Math.round(n/total*100):0)});await out.close();}catch(e){await out.abort();throw e;}return;} const chunks:Uint8Array[]=[];await api.download(path,async b=>{chunks.push(Uint8Array.from(b));},{signal,maxBytes:50*1024**2,onProgress:(n,total)=>onProgress(total?Math.round(n/total*100):0)});const url=URL.createObjectURL(new Blob(chunks)),a=document.createElement('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),10000);return; } const dir=new Directory(Paths.cache,'managed-downloads');dir.create({idempotent:true,intermediates:true});const output=new File(dir,Date.now()+'-'+name);output.create();const handle=output.open(FileMode.WriteOnly); try{await api.download(path,b=>handle.writeBytes(b),{signal,transport:expoFetch as typeof fetch,onProgress:(n,total)=>onProgress(total?Math.round(n/total*100):0)});handle.close();if(signal.aborted)throw new Error('下载已取消');if(action==='open'&&await output.canPreview())await output.preview();else if(await Sharing.isAvailableAsync())await Sharing.shareAsync(output.uri,{dialogTitle:'保存或打开文件'});else throw new Error('系统没有可用于打开文件的应用');} catch(error){try{handle.close();}catch{}try{output.delete();}catch{}throw error;} // Keep successful files in cache so the selected viewer can finish reading them. }