| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- #!/usr/bin/env node
- /**
- * 推送链路测试脚本(AI 自动测试用)
- *
- * 配套手册:docs/05-operations/推送链路测试手册-AI自动测试用.md
- *
- * 子命令:
- * --status 汇总设备/App/权限/游标/最近推送
- * --check-room 看 lj-test 房间最新事件(含 turn_status)
- * --trigger 调监听函数并打印结果
- * --notify '<json>' 直接推一条(验证通知链路本身)
- * --cdp '<expr>' 在 WebView 里执行表达式
- * --watch [秒] 循环调监听函数,直到 pushed>0 或超时
- *
- * 用法:
- * node scripts/test-push.mjs --status
- * node scripts/test-push.mjs --trigger
- * node scripts/test-push.mjs --notify '{"title":"测试","body":"内容"}'
- * node scripts/test-push.mjs --watch 180
- *
- * 设计说明:
- * · 所有判据都打印原始数据,不替使用者下结论(避免脚本自己误判)
- * · 任何一步失败都给出**可执行的下一步建议**,而不是只报错
- */
- import { execFileSync } from 'node:child_process';
- const ADB = process.env.ADB_PATH || 'E:/coding-environment/adb/adb.exe';
- const APP_ID = 'ncloudmaster';
- const MASTER_KEY = 'SnkK12*&sunq2#@20!';
- const SERVER_TOKEN = 'fmpush-srv-2026-11-c33a9e71';
- const PUSH_FN_ID = 'oCRJCCdiAx';
- const WATCH_FN_ID = 'KMmY5DxKzs';
- const PARSE = 'https://server.fmode.cn/parse';
- const FUNCTIONS = 'https://server.fmode.cn/api/functions';
- const TEST_USER = 'xhVRjTMwQH';
- const TEST_TOKEN = 'r:b64c5748a5be24fda063b5466851c01e';
- const LJ_AGENT = 'agent-node-lj-test';
- const HS = 'https://matrix.fmode.cn';
- const argv = process.argv.slice(2);
- const has = (f) => argv.includes(f);
- const val = (f) => {
- const i = argv.indexOf(f);
- return i >= 0 ? argv[i + 1] : undefined;
- };
- // ---------- 基础工具 ----------
- function adb(args, { allowFail = false } = {}) {
- try {
- return execFileSync(ADB, args, {
- encoding: 'utf8',
- timeout: 30000,
- env: { ...process.env, MSYS_NO_PATHCONV: '1' },
- }).trim();
- } catch (e) {
- if (allowFail) return '';
- throw e;
- }
- }
- /**
- * 调 Parse REST。
- *
- * 🔴 这个平台的 Function / FmodePush* 表禁止 GET(返回 403),
- * 必须用 `POST` + body 里带 `_method: 'GET'` 的变通写法。
- */
- async function parseQuery(cls, body) {
- const res = await fetch(`${PARSE}/classes/${cls}`, {
- method: 'POST',
- headers: {
- 'X-Parse-Application-Id': APP_ID,
- 'X-Parse-Master-Key': MASTER_KEY,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({ ...body, _method: 'GET' }),
- });
- return res.json();
- }
- async function callFunction(id, params, headers = {}) {
- const res = await fetch(FUNCTIONS, {
- method: 'POST',
- headers: {
- 'X-Parse-Application-Id': APP_ID,
- 'Content-Type': 'application/json',
- ...headers,
- },
- body: JSON.stringify({ id, params }),
- });
- const text = await res.text();
- try { return { status: res.status, json: JSON.parse(text) }; }
- catch { return { status: res.status, raw: text.slice(0, 300) }; }
- }
- // ---------- 子命令 ----------
- /** 设备与 App 状态 */
- async function cmdStatus() {
- console.log('=== 设备 ===');
- const dev = adb(['devices'], { allowFail: true });
- const connected = /device\s*$/.test(dev.split('\n').filter((l) => l.includes('\tdevice')).join(''));
- console.log(dev.split('\n').slice(1).filter(Boolean).join('\n') || '(未连接)');
- if (!connected) {
- /*
- * 🔴 设备断开时**不要继续输出「已解锁 / 权限正常」这类肯定结论**。
- * 之前这里在 adb 失败时读不到锁屏字段,被误判成「已解锁」,
- * 会把排查方向带偏。
- */
- console.log('\n❌ 没有可用设备 —— 后续检查全部跳过。');
- console.log(' 请确认数据线连接、USB 调试已开启。');
- await dumpServerSide();
- return;
- }
- const pid = adb(['shell', 'pidof', 'cn.fmode.app'], { allowFail: true });
- console.log('\n=== App 进程 ===');
- console.log(pid ? `运行中 pid=${pid}` : '❌ 未运行 → 先执行 adb shell am start -n cn.fmode.app/.MainActivity');
- const lock = adb(['shell', 'dumpsys', 'window'], { allowFail: true });
- console.log('\n=== 锁屏 ===');
- if (/mDreamingLockscreen=true/.test(lock)) console.log('❌ 已锁屏 → adb 无法解锁,需用户手动解锁');
- else if (/mDreamingLockscreen=false/.test(lock)) console.log('✅ 已解锁');
- else console.log('⚠️ 读不到锁屏状态(adb 异常)');
- const appops = adb(['shell', 'cmd', 'appops', 'get', 'cn.fmode.app', 'POST_NOTIFICATION'], { allowFail: true });
- console.log('\n=== 通知权限 ===');
- console.log(appops || '(读取失败)');
- if (!appops.includes('allow')) {
- console.log('❌ 通知权限未开 → 去「设置 → 应用 → Fmode → 允许通知」手动打开(pm grant 不够)');
- }
- const imp = adb(['shell', 'dumpsys', 'notification'], { allowFail: true });
- const m = imp.match(/AppSettings: cn\.fmode\.app[^\n]*importance=(\w+)/);
- console.log('\n=== 通知重要性 ===');
- console.log(m ? m[1] : '(未读到)');
- const notifCount = adb(['shell', 'dumpsys', 'notification', '--noredact'], { allowFail: true })
- .split('\n').filter((l) => l.includes('pkg=cn.fmode.app')).length;
- console.log('\n=== 通知栏基线 ===');
- console.log(`${notifCount} 条(记录这个数字,推送后应增加)`);
- console.log('\n=== 最近推送记录 ===');
- await dumpServerSide();
- }
- /** 服务端侧信息(不依赖设备),设备断开时也能查 */
- async function dumpServerSide() {
- const logs = await parseQuery('FmodePushLog', {
- where: { eventId: { $regex: 'turn:' } },
- limit: 3,
- order: '-pushedAt',
- });
- console.log('\n=== 最近推送记录(服务端) ===');
- for (const o of logs.results || []) {
- console.log(` ${o.pushedAt?.iso ?? '?'} ${o.eventId} msgId=${o.msgId || '(空)'}`);
- }
- if (!(logs.results || []).length) console.log(' (无记录)');
- const cursors = await parseQuery('FmodePushCursor', { where: { userId: TEST_USER }, limit: 1000 });
- console.log(`\n=== 游标 ===\n 该用户游标数:${(cursors.results || []).length}`);
- }
- /** 看 lj-test 房间最新事件 */
- async function cmdCheckRoom() {
- const bindings = await parseQuery('FmodeMatrixBinding', {
- where: {
- userPointer: { __type: 'Pointer', className: '_User', objectId: TEST_USER },
- agentId: LJ_AGENT,
- status: 'active',
- },
- limit: 1,
- });
- const b = (bindings.results || [])[0];
- if (!b) {
- console.log('❌ 找不到 lj-test 的 Matrix 绑定记录');
- console.log(' 检查 FmodeMatrixBinding 表里是否有 userPointer=' + TEST_USER + ' 且 agentId=' + LJ_AGENT);
- return;
- }
- console.log('房间:', b.roomId);
- const res = await fetch(
- `${HS}/_matrix/client/v3/rooms/${encodeURIComponent(b.roomId)}/messages?dir=b&limit=10&access_token=${b.accessToken}`,
- );
- const data = await res.json();
- if (!data.chunk) {
- console.log('❌ 读取房间失败:', JSON.stringify(data).slice(0, 200));
- return;
- }
- console.log('\n最新 10 条事件(倒序):');
- for (const ev of data.chunk) {
- const c = ev.content || {};
- const kind = ev.type === 'com.fmode.turn_status' ? `TURN ${c.status}` : ev.type.replace('m.room.', '');
- const text = c.body ? String(c.body).replace(/\s+/g, ' ').slice(0, 40) : '';
- const ts = new Date(ev.origin_server_ts).toISOString().slice(11, 19);
- console.log(` ${ts} ${kind.padEnd(18)} ${text}`);
- }
- const idle = data.chunk.find((e) => e.type === 'com.fmode.turn_status' && e.content?.status === 'idle');
- console.log('\n最新 idle 事件:', idle ? idle.event_id : '❌ 没有(任务可能还在执行)');
- }
- /** 调监听函数 */
- async function cmdTrigger() {
- const r = await callFunction(WATCH_FN_ID, { userId: TEST_USER }, {
- 'X-Fmode-Push-Token': SERVER_TOKEN,
- });
- console.log(JSON.stringify(r.json ?? r, null, 1));
- if (r.json?.pushed > 0) {
- console.log('\n✅ 已推送,接下来验证通知栏:node scripts/test-push.mjs --status');
- } else if (r.json?.errors?.length) {
- console.log('\n⚠️ errors 非空,按内容排查:');
- for (const e of r.json.errors.slice(0, 5)) console.log(' -', e);
- }
- }
- /** 直接推一条(验证通知链路本身,不经过回合判定) */
- async function cmdNotify(json) {
- let payload;
- try { payload = JSON.parse(json || '{}'); }
- catch { console.log('❌ --notify 后面必须是 JSON,如 \'{"title":"测试","body":"内容"}\''); return; }
- const r = await callFunction(PUSH_FN_ID, {
- alias: TEST_USER,
- title: payload.title || 'Fmode 测试',
- alert: payload.body || payload.alert || '测试推送',
- deepLink: payload.deepLink,
- }, { 'X-Parse-Session-Token': TEST_TOKEN });
- console.log(JSON.stringify(r.json ?? r, null, 1));
- if (r.json?.msgId) {
- console.log('\nmsgId:', r.json.msgId);
- console.log('查回执:curl -u "c3904d49d3c95e976d8576e3:27c168d11f61a4c083f9c8c6" "https://report.jpush.cn/v3/received?msg_ids=' + r.json.msgId + '"');
- }
- }
- /** 在 WebView 里执行表达式 */
- async function cmdCdp(expr) {
- const pid = adb(['shell', 'pidof', 'cn.fmode.app'], { allowFail: true });
- if (!pid) { console.log('❌ App 未运行'); return; }
- adb(['forward', '--remove-all'], { allowFail: true });
- adb(['forward', 'tcp:9222', `localabstract:webview_devtools_remote_${pid}`], { allowFail: true });
- await new Promise((r) => setTimeout(r, 800));
- try {
- const list = await (await fetch('http://localhost:9222/json/list')).json();
- const page = list.find((p) => p.type === 'page');
- if (!page) { console.log('❌ 没有可调试的 WebView 页面'); return; }
- const ws = new WebSocket(page.webSocketDebuggerUrl);
- let id = 0;
- const pending = new Map();
- ws.onmessage = (e) => {
- const m = JSON.parse(e.data);
- if (m.id && pending.has(m.id)) { pending.get(m.id)(m); pending.delete(m.id); }
- };
- await new Promise((r) => { ws.onopen = r; });
- const send = (method, params) =>
- new Promise((res) => { const i = ++id; pending.set(i, res); ws.send(JSON.stringify({ id: i, method, params })); });
- const out = await send('Runtime.evaluate', {
- expression: expr || '({url: location.href, vis: document.visibilityState})',
- returnByValue: true,
- awaitPromise: true,
- });
- console.log(JSON.stringify(out.result?.result?.value ?? out.result, null, 1));
- ws.close();
- } catch (e) {
- console.log('❌ CDP 连接失败:', String(e).slice(0, 150));
- }
- }
- /** 循环调用直到推出去 */
- async function cmdWatch(seconds) {
- const total = Number(seconds) || 180;
- const step = 20;
- const t0 = Date.now();
- while (Date.now() - t0 < total * 1000) {
- const r = await callFunction(WATCH_FN_ID, { userId: TEST_USER }, { 'X-Fmode-Push-Token': SERVER_TOKEN });
- const j = r.json || {};
- console.log(`${new Date().toISOString().slice(11, 19)} rooms=${j.rooms} turns=${j.turnsFound} pushed=${j.pushed}`);
- if (j.pushed > 0) { console.log('\n✅ 推送成功'); return; }
- await new Promise((res) => setTimeout(res, step * 1000));
- }
- console.log('\n⏱ 超时仍未推送。可能原因:');
- console.log(' · 任务还没执行完(容器没有发 idle 事件)→ node scripts/test-push.mjs --check-room');
- console.log(' · 该回合此前已推过(去重)→ 看 FmodePushLog');
- console.log(' · 游标判定异常 → node scripts/test-push.mjs --status');
- }
- // ---------- 入口 ----------
- const USAGE = `推送链路测试脚本
- 用法:
- node scripts/test-push.mjs --status
- node scripts/test-push.mjs --check-room
- node scripts/test-push.mjs --trigger
- node scripts/test-push.mjs --notify '{"title":"测试","body":"内容"}'
- node scripts/test-push.mjs --cdp '({url:location.href})'
- node scripts/test-push.mjs --watch 180
- 手册:docs/05-operations/推送链路测试手册-AI自动测试用.md`;
- (async () => {
- if (has('--status')) return cmdStatus();
- if (has('--check-room')) return cmdCheckRoom();
- if (has('--trigger')) return cmdTrigger();
- if (has('--notify')) return cmdNotify(val('--notify'));
- if (has('--cdp')) return cmdCdp(val('--cdp'));
- if (has('--watch')) return cmdWatch(val('--watch'));
- console.log(USAGE);
- })().catch((e) => {
- console.error('执行失败:', e.message);
- process.exit(1);
- });
|