2026-10-29 09:58:51 +08:00
|
|
|
|
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';
|
2026-10-29 17:27:46 +08:00
|
|
|
|
import {newerPackage,packageVerifier,processPackageChunk,verifyInstalledPackage,type PackageRelease} from './core/package-update';
|
2026-10-29 09:58:51 +08:00
|
|
|
|
import {Button,Card,Heading,Icon,Note,s,useTheme} from './ui';
|
|
|
|
|
|
import {Text} from './typography';
|
|
|
|
|
|
export function usePackageUpdates(api:ApiClient,scope:string,enabled:boolean){
|
2026-10-29 17:27:46 +08:00
|
|
|
|
const [release,setRelease]=useState<PackageRelease|null>(null),[visible,setVisible]=useState(false),[phase,setPhase]=useState<'idle'|'checking'|'downloading'|'verifying'|'installing'|'ready'>('idle'),[progress,setProgress]=useState(0),[error,setError]=useState('');
|
2026-10-29 09:58:51 +08:00
|
|
|
|
const file=useRef<File|null>(null),fileHash=useRef(''),ctl=useRef<AbortController|null>(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<any>('/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);
|
2026-10-29 17:27:46 +08:00
|
|
|
|
let processed=0;try{await api.download(release.downloadPath,async bytes=>{await processPackageChunk(bytes,chunk=>{verify.write(chunk);handle.writeBytes(chunk);},length=>{processed+=length;if(valid())setProgress(Math.min(99,Math.floor(processed/release.size*100)));},abort.signal);},{signal:abort.signal,maxBytes:release.size,transport:expoFetch as typeof fetch});if(valid())setPhase('verifying');await new Promise<void>(resolve=>setTimeout(resolve,0));if(abort.signal.aborted||!valid())throw new Error('下载已取消');verify.finish();}finally{handle.close();}
|
2026-10-29 09:58:51 +08:00
|
|
|
|
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;}
|
|
|
|
|
|
}
|
2026-10-29 17:27:46 +08:00
|
|
|
|
async function install(){if(!file.current||!release||busy.current)return;busy.current=true;setError('');setPhase('installing');await new Promise<void>(resolve=>setTimeout(resolve,0));try{await verifyInstalledPackage(NativeModules.CmvrApkVerification,file.current.uri,release.versionCode);}catch{setError('安装包的包名、签名或版本不匹配,请联系管理员。');busy.current=false;setPhase('ready');return;}try{await file.current.preview({mimeType:'application/vnd.android.package-archive'});}catch{setError('未能打开安装界面,请在手机设置中允许本应用安装未知应用,再点击安装。');}finally{busy.current=false;setPhase('ready');}}
|
|
|
|
|
|
function later(){if(phase==='downloading'||phase==='verifying')ctl.current?.abort();setVisible(false);}
|
2026-10-29 09:58:51 +08:00
|
|
|
|
return {release,visible,phase,progress,error,available,check:()=>void check(true),download:()=>void download(),install:()=>void install(),later};
|
|
|
|
|
|
}
|
|
|
|
|
|
export type PackageControls=ReturnType<typeof usePackageUpdates>;
|
2026-10-29 17:27:46 +08:00
|
|
|
|
export function PackageUpdateStatus({control:c}:{control:PackageControls}){return c.available?<Card><Heading>安装包更新</Heading><Note>{c.release?`新安装包 ${c.release.versionName}(${c.release.versionCode})`:'检查需要重新安装的新版本'}{c.phase==='downloading'?` · ${c.progress}%`:''}</Note>{!!c.error&&<Note>{c.error}</Note>}<Button title="检查安装包更新" secondary busy={c.phase==='checking'} disabled={['downloading','verifying','installing'].includes(c.phase)} onPress={c.check}/></Card>:null;}
|
|
|
|
|
|
export function PackageUpdateDialog({control:c}:{control:PackageControls}){const t=useTheme();if(!c.visible||!c.release)return null;return <Modal transparent visible animationType="fade" onRequestClose={c.later}><View style={{flex:1,backgroundColor:'#0008',justifyContent:'center',padding:24}}><View style={{width:'100%',maxWidth:380,alignSelf:'center',maxHeight:'85%',backgroundColor:t.card,borderRadius:20,padding:22,gap:16}}><ScrollView contentContainerStyle={{gap:12}}><Icon name="cloud-download-outline" size={30}/><Heading>发现新版安装包</Heading><Note>版本 {c.release.versionName}({c.release.versionCode}) · {(c.release.size/1024**2).toFixed(1)} MB</Note>{!!c.release.notes&&<Text style={{color:t.text,fontSize:14,lineHeight:22}}>{c.release.notes}</Text>}<Note>请先保存当前内容。下载完成后由手机系统确认安装;首次安装可能需要允许本应用安装未知应用。</Note>{c.phase==='downloading'&&<><View style={{height:6,backgroundColor:t.soft,borderRadius:3,overflow:'hidden'}}><View style={{height:6,width:`${c.progress}%`,backgroundColor:t.accent}}/></View><Note>{c.progress===0?'正在连接并接收安装包…':`已接收并处理 ${c.progress}%`}</Note></>}{c.phase==='verifying'&&<Note>正在完成文件完整性校验…</Note>}{c.phase==='installing'&&<Note>正在验证安装包,请稍候…</Note>}{!!c.error&&<Text accessibilityRole="alert" style={{color:'#c74848',fontSize:13}}>{c.error}</Text>}</ScrollView><Button title={c.phase==='ready'?'安装新版':c.phase==='downloading'?'正在下载…':c.phase==='verifying'?'正在校验…':c.phase==='installing'?'正在验证…':'下载新版'} disabled={['downloading','verifying','installing'].includes(c.phase)} onPress={c.phase==='ready'?c.install:c.download}/><Button title={['downloading','verifying'].includes(c.phase)?'取消下载':'稍后再说'} secondary onPress={c.later}/></View></View></Modal>;}
|