import React,{useCallback,useEffect,useRef,useState} from 'react'; import {AppState,Modal,NativeModules,Platform,ScrollView,View} from 'react-native'; import Constants from 'expo-constants'; import * as Application from 'expo-application'; import {Directory,File,FileMode,Paths} from 'expo-file-system'; import {fetch as expoFetch} from 'expo/fetch'; import type {ApiClient} from './core/network'; import {newerPackage,packageVerifier,verifyInstalledPackage,type PackageRelease} from './core/package-update'; import {Button,Card,Heading,Icon,Note,s,useTheme} from './ui'; import {Text} from './typography'; export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){ const [release,setRelease]=useState(null),[visible,setVisible]=useState(false),[phase,setPhase]=useState<'idle'|'checking'|'downloading'|'ready'>('idle'),[progress,setProgress]=useState(0),[error,setError]=useState(''); const file=useRef(null),fileHash=useRef(''),ctl=useRef(null),generation=useRef(0),busy=useRef(false),last=useRef(0),shown=useRef(''); // Read the installed native build, never the OTA manifest's version. const current=Number(Application.nativeBuildVersion),environment=String(Constants.expoConfig?.extra?.environment||'dev'); const available=enabled&&Platform.OS==='android'&&Number.isInteger(current)&¤t>0; const check=useCallback(async(force=false)=>{if(!available||busy.current||!force&&Date.now()-last.current<15*60*1000)return;const run=generation.current,valid=()=>generation.current===run;busy.current=true;last.current=Date.now();const checkCtl=new AbortController();ctl.current=checkCtl;setPhase('checking');if(force)setError('');try{const data=await api.request('/system/mobile-release',{signal:checkCtl.signal});const next=newerPackage(data.data,current,environment);if(!valid()||checkCtl.signal.aborted)return;if(fileHash.current!==next?.sha256){file.current=null;fileHash.current='';}setRelease(next);if(next&&(force||shown.current!==next.sha256)){setVisible(true);shown.current=next.sha256;}if(!next&&force)setError('安装包已是当前版本');}catch(e){if(valid()&&!checkCtl.signal.aborted){last.current=Date.now()-14*60*1000;if(force)setError((e as Error).message);}}finally{if(valid()){busy.current=false;setPhase(file.current?'ready':'idle');}}},[api,available,current,environment]); useEffect(()=>{generation.current++;busy.current=false;shown.current='';last.current=0;file.current=null;fileHash.current='';setRelease(null);setVisible(false);setPhase('idle');setError('');void check();const listener=AppState.addEventListener('change',state=>{if(state==='active')void check();});return()=>{generation.current++;ctl.current?.abort();listener.remove();};},[scope,check]); async function download(){if(!release||busy.current)return;const run=generation.current,valid=()=>generation.current===run;busy.current=true;setError('');setPhase('downloading');setProgress(0);const abort=new AbortController();ctl.current=abort;let output:File|null=null; try{const dir=new Directory(Paths.cache,'app-updates');dir.create({idempotent:true,intermediates:true});output=new File(dir,release.sha256+'-'+Date.now()+'-'+Math.random().toString(16).slice(2)+'.apk');output.create();const handle=output.open(FileMode.WriteOnly),verify=packageVerifier(release); try{await api.download(release.downloadPath,async bytes=>{verify.write(bytes);handle.writeBytes(bytes);},{signal:abort.signal,maxBytes:release.size,transport:expoFetch as typeof fetch,onProgress:n=>{if(valid())setProgress(Math.min(99,Math.round(n/release.size*100)));}});verify.finish();}finally{handle.close();} if(abort.signal.aborted||!valid())throw new Error('下载已取消');file.current=output;fileHash.current=release.sha256;setPhase('ready');setProgress(100); }catch(e){try{if(output?.exists)output.delete();}catch{}if(valid()){file.current=null;fileHash.current='';setPhase('idle');setError(abort.signal.aborted?'下载已取消,可重新下载':(e as Error).message);}} finally{if(valid())busy.current=false;} } async function install(){if(!file.current||!release||busy.current)return;busy.current=true;try{await verifyInstalledPackage(NativeModules.CmvrApkVerification,file.current.uri,release.versionCode);}catch{setError('安装包的包名、签名或版本不匹配,请联系管理员。');busy.current=false;return;}try{await file.current.preview({mimeType:'application/vnd.android.package-archive'});}catch{setError('未能打开安装界面,请在手机设置中允许本应用安装未知应用,再点击安装。');}finally{busy.current=false;}} function later(){if(phase==='downloading')ctl.current?.abort();setVisible(false);} return {release,visible,phase,progress,error,available,check:()=>void check(true),download:()=>void download(),install:()=>void install(),later}; } export type PackageControls=ReturnType; export function PackageUpdateStatus({control:c}:{control:PackageControls}){return c.available?安装包更新{c.release?`新安装包 ${c.release.versionName}(${c.release.versionCode})`:'检查需要重新安装的新版本'}{c.phase==='downloading'?` · ${c.progress}%`:''}{!!c.error&&{c.error}}