| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- #!/usr/bin/env node
- /** 安装真实数据包;不填充localStorage、不发送验证码、不操作业务数据。 */
- import fs from 'node:fs';
- import {spawnSync,spawn} from 'node:child_process';
- import {createHash} from 'node:crypto';
- import {captureNativeScreenshot} from './android-webview-cdp.mjs';
- import {connectRealAccountWebView} from './lib/real-account-webview.mjs';
- import {readRealReview,beginRealAction,finishRealAction,failRealAction,updateRealReview,realCheck} from './lib/real-account-review-ledger.mjs';
- const revision=process.argv.find(x=>x.startsWith('--revision='))?.split('=')[1]||'r1';
- const attempt=Number(process.argv.find(x=>x.startsWith('--attempt='))?.split('=')[1]||'1');
- if(!/^r[1-9][0-9]*$/.test(revision)||!Number.isInteger(attempt)||attempt<1||attempt>9)throw Error('非法修订或尝试编号');
- const state=readRealReview(),receipt=state.actions['build_'+revision]?.receipt,serial=state.device.serial,pkg=state.packageId;
- if(!receipt||state.actions['build_'+revision].status!=='confirmed'||receipt.sourceMode!=='production-real'||receipt.packageId!==pkg||pkg!=='cn.fmode.app')throw Error('没有已确认的真实数据构建');
- const hash=value=>createHash('sha256').update(value).digest('hex');
- if(hash(fs.readFileSync(receipt.apk))!==receipt.sha256)throw Error('安装包摘要不一致');
- const adb=args=>{const r=spawnSync('adb',['-s',serial,...args],{encoding:'utf8',timeout:120000,windowsHide:true});if(r.status!==0)throw Error('adb '+args.slice(0,3).join(' ')+' 失败:'+(r.stderr||r.stdout||r.error?.message||'').trim());return r.stdout.trim()};
- const sleep=ms=>new Promise(r=>setTimeout(r,ms));
- const suffix=attempt===1?'':'-attempt'+attempt;
- let active,cdp,recording;
- try{
- const installed=adb(['shell','pm','list','packages',pkg]).split(/\r?\n/).includes('package:'+pkg);
- let installedPath=installed?adb(['shell','pm','path',pkg]).split(/\r?\n/).find(x=>x.startsWith('package:'))?.slice(8):null;
- const installedHash=installedPath?adb(['shell','sha256sum',installedPath]).split(/\s+/)[0]:null;
- const key='install_'+revision+suffix,prior=readRealReview().actions[key];
- const unresolved=Object.entries(readRealReview().actions).filter(([name,action])=>name.startsWith('install_')&&action.target?.packageId===pkg&&['registered','uncertain'].includes(action.status));
- for(const [name,action]of unresolved){
- if(installedHash&&installedHash===action.target.sha256){
- updateRealReview(s=>{const current=s.actions[name];if(!['registered','uncertain'].includes(current?.status))throw Error('安装状态已变化,停止恢复');s.actions[name]={...current,status:'confirmed',result:{readOnlyReconciliation:true,installedSha256:installedHash,installedPath,previousStatus:current.status},completedAt:new Date().toISOString()}});
- }else throw Error('同包既往安装动作仍未决,不能通过更换attempt重试:'+name);
- }
- if(prior&&installedHash!==receipt.sha256)throw Error('已有安装动作与当前设备状态不一致;先核实,不重试');
- if(!prior){
- if(installedHash&&installedHash!==receipt.sha256&&!Object.values(state.actions).some(a=>a.status==='confirmed'&&a.receipt?.sha256===installedHash))throw Error('手机有未知版本原包,不覆盖或卸载');
- beginRealAction(key,{serial,packageId:pkg,sha256:receipt.sha256,apk:receipt.apk,updateKnownPackage:!!installedHash,realData:true});active=key;
- const output=installedHash===receipt.sha256?'只读核对:已安装目标摘要':adb(['install','-r',receipt.apk]);
- if(installedHash!==receipt.sha256&&!/Success/.test(output))throw Error('安装未确认成功');
- installedPath=adb(['shell','pm','path',pkg]).split(/\r?\n/).find(x=>x.startsWith('package:'))?.slice(8);
- if(!installedPath||adb(['shell','sha256sum',installedPath]).split(/\s+/)[0]!==receipt.sha256)throw Error('安装后摘要未回读一致');
- const version=adb(['shell','dumpsys','package',pkg]).split(/\r?\n/).filter(x=>/versionCode=|versionName=|lastUpdateTime=/.test(x));
- finishRealAction(key,{output,installedPath,sha256:receipt.sha256,version});active=null;
- }
- if(prior&&readRealReview().actions[key]?.status!=='confirmed')throw Error('原安装动作尚未确认;先核实并登记只读恢复回执');
- const launch='launch_'+revision+suffix;
- if(readRealReview().actions[launch])throw Error('启动已有记录;不重复录制或启动,使用原会话继续');
- if(!/mWakefulness=Awake/.test(adb(['shell','dumpsys','power']))){beginRealAction('wake_'+revision+suffix,{serial,purpose:'仅唤醒屏幕'});adb(['shell','input','keyevent','KEYCODE_WAKEUP']);finishRealAction('wake_'+revision+suffix,{awake:/mWakefulness=Awake/.test(adb(['shell','dumpsys','power']))})}
- const policy=adb(['shell','dumpsys','window','policy']);
- if(/showing=true/.test(policy)){
- if(!/secure=false/.test(policy))throw Error('手机有凭据锁,请在手机解锁后继续');
- const unlock='dismiss_nonsecure_'+revision+suffix;beginRealAction(unlock,{serial,secure:false});adb(['shell','wm','dismiss-keyguard']);finishRealAction(unlock,{dismissed:true});
- }
- const component=adb(['shell','cmd','package','resolve-activity','--brief',pkg]).split(/\r?\n/).find(x=>x.startsWith(pkg+'/'));if(!component)throw Error('启动组件未确认');
- const deviceVideo='/sdcard/Movies/fmode-real-'+revision+suffix+'-startup.mp4';
- const probe=spawnSync('adb',['-s',serial,'shell','ls',deviceVideo],{encoding:'utf8',windowsHide:true});if(probe.status===0)throw Error('启动录屏已存在,不覆盖');
- beginRealAction(launch,{serial,component,deviceVideo,purpose:'真实包首次启动,录屏只包含启动和登录页'});active=launch;
- recording=spawn('adb',['-s',serial,'shell','screenrecord','--time-limit','12','--bit-rate','10000000',deviceVideo],{stdio:['ignore','ignore','pipe'],windowsHide:true});
- const recordDone=new Promise(resolve=>{recording.once('error',error=>resolve({error:error.message}));recording.once('close',code=>resolve({code}))});
- await sleep(400);const output=adb(['shell','am','start','-W','-n',component]);
- let pid,socket;const deadline=Date.now()+30000;
- while(Date.now()<deadline){try{pid=adb(['shell','pidof',pkg]);socket=adb(['shell','cat','/proc/net/unix']).split(/\r?\n/).find(x=>x.endsWith('@webview_devtools_remote_'+pid));if(pid&&socket)break}catch{}await sleep(250)}
- if(!socket)throw Error('原包WebView未就绪');
- const forward='forward_'+revision+'_'+pid+suffix;beginRealAction(forward,{serial,packageId:pkg,pid});const port=Number(adb(['forward','tcp:0','localabstract:webview_devtools_remote_'+pid]));finishRealAction(forward,{port});
- updateRealReview(s=>{s.reviewSession={revision,pid,port,serial,packageId:pkg,sourceMode:'production-real',at:new Date().toISOString()}});
- cdp=(await connectRealAccountWebView()).cdp;await cdp.waitFor(()=>document.querySelector('app-root')?.innerText.trim());await sleep(4000);
- const file='test-results/real-account-20261130/real-'+revision+suffix+'-installed.png';captureNativeScreenshot(file,serial);
- const metrics=await cdp.evaluate(()=>({path:location.pathname,visible:document.visibilityState,width:innerWidth,height:innerHeight,scrollWidth:document.documentElement.scrollWidth,title:document.querySelector('h1,h2,.m-title-main')?.textContent.trim(),inputs:[...document.querySelectorAll('input')].map(x=>({type:x.type,label:x.getAttribute('aria-label'),placeholder:x.placeholder})),buttons:[...document.querySelectorAll('button')].filter(x=>{const r=x.getBoundingClientRect();return r.width>0&&r.height>0}).map(x=>({text:x.textContent.trim().slice(0,70),label:x.getAttribute('aria-label'),class:x.className}))}));
- const recordResult=await recordDone;
- if(recordResult.code!==0)throw Error('启动录屏未确认成功:'+JSON.stringify(recordResult));
- const video='test-results/real-account-20261130/real-'+revision+suffix+'-startup.mp4';if(fs.existsSync(video))throw Error('本地录屏已存在,不覆盖');adb(['pull',deviceVideo,video]);
- const startupLog=adb(['logcat','-d','-s','FmodeStartup:I','*:S']);fs.writeFileSync('test-results/real-account-20261130/real-'+revision+suffix+'-startup.log',startupLog,{flag:'wx'});
- finishRealAction(launch,{output,metrics,file,video,videoBytes:fs.statSync(video).size});active=null;
- realCheck('真实数据包首屏可见且无横向溢出',metrics.visible==='visible'&&metrics.width===metrics.scrollWidth,{metrics,file});
- updateRealReview(s=>{s.stage='awaiting_real_account_login';s.firstScreen=metrics});
- console.log(JSON.stringify({session:readRealReview().reviewSession,metrics,file,video},null,2));
- }catch(error){if(active)failRealAction(active,error);else updateRealReview(s=>s.failures.push({stage:'setup_real_'+revision,message:error.message,at:new Date().toISOString()}));console.error(error.message);process.exitCode=1}finally{cdp?.close()}
|