dsh-dot-life 0.10.3 → 0.10.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/phone/phone.js +37 -11
- package/src/qq/qq.js +117 -17
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-dot-life",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.16",
|
|
4
4
|
"description": "dot — a character who lives on her own phone, for DeepSeek Harness (dsh): an Android phone the plugin installs and runs, her own QQ, memory and a diary from real events, a life between conversations (幕间, after HDS-Interlude), an optional microVM computer with approval gates. One plugin, six components.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
package/src/phone/phone.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// live view; state (apps, logins) lives in the AVD's data partition and survives dsh restarts.
|
|
7
7
|
import { PHONE_SERVER, PHONE_TOOL_PREFIX } from '../tool-prefixes.js';
|
|
8
8
|
import { spawn, execFile } from 'node:child_process';
|
|
9
|
-
import { chmodSync, closeSync, createWriteStream, existsSync, openSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
9
|
+
import { chmodSync, closeSync, readdirSync, createWriteStream, existsSync, openSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, appendFileSync } from 'node:fs';
|
|
10
10
|
import { homedir, platform, arch as osArch } from 'node:os';
|
|
11
11
|
import { join, dirname } from 'node:path';
|
|
12
12
|
import { createRequire } from 'node:module';
|
|
@@ -18,6 +18,9 @@ import { mountLiveView, LIVE_VIEW_PATH } from './live-view.js';
|
|
|
18
18
|
import { localUrl, publicUrlOf } from '../web-auth.js';
|
|
19
19
|
import { createShadeWatch, createPolicy, parseShade } from './notifications.js';
|
|
20
20
|
|
|
21
|
+
/** The virtual scene's "wall" poster, moved to 1.5 m straight in front of the camera's start pose (1 m square). */
|
|
22
|
+
const WALL_POSTER = ['poster wall', 'size 1 1', 'position 0 0 -1.5', 'rotation 0 0 0', 'default poster.png', ''].join('\n');
|
|
23
|
+
|
|
21
24
|
/** @deprecated name kept for callers; see notifications.js */
|
|
22
25
|
export const parseNotifications = parseShade;
|
|
23
26
|
|
|
@@ -266,19 +269,28 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
266
269
|
/** PNG of the screen right now. */
|
|
267
270
|
phone.screenshot = async () => Buffer.from((await phone.adbExec(['exec-out', 'screencap', '-p'], { encoding: 'buffer' })).stdout);
|
|
268
271
|
/**
|
|
269
|
-
* Put a PNG in front of her camera:
|
|
270
|
-
* the
|
|
271
|
-
* poster
|
|
272
|
+
* Put a PNG in front of her camera, live: the emulator console's `virtualscene-image wall <png>`
|
|
273
|
+
* swaps the "wall" poster's picture while the phone runs, and ensureCameraScene (before launch) has
|
|
274
|
+
* moved that poster to 1.5 m straight in front of the camera's start pose. After this, QQ → 扫一扫
|
|
275
|
+
* sees the image filling the view. Returns the image path.
|
|
272
276
|
*/
|
|
273
|
-
phone.showToCamera = (png) => {
|
|
277
|
+
phone.showToCamera = async (png) => {
|
|
274
278
|
const f = posterFiles();
|
|
275
279
|
mkdirSync(f.dir, { recursive: true });
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
writeFileSync(
|
|
279
|
-
|
|
280
|
+
// A new file name every time too, so no cached picture is ever taken for the new one.
|
|
281
|
+
const file = join(f.dir, `dsh-dot-poster-${Date.now()}.png`);
|
|
282
|
+
writeFileSync(file, png);
|
|
283
|
+
// The emulator ignores a poster change while an app has the camera open: go to the home screen
|
|
284
|
+
// first (the scanner releases the camera when paused); the next 扫一扫 then shows the new picture.
|
|
285
|
+
try { await phone.adbExec(['shell', 'input', 'keyevent', 'KEYCODE_HOME']); await new Promise((r) => setTimeout(r, 1500)); } catch {}
|
|
286
|
+
// Clear first: after the first picture an emulator process takes a new one only from a cleared poster.
|
|
287
|
+
try { await phone.adbExec(['emu', 'virtualscene-image', 'wall']); } catch {}
|
|
288
|
+
const out = String((await phone.adbExec(['emu', 'virtualscene-image', 'wall', file])).stdout ?? '');
|
|
289
|
+
if (/\bKO\b/.test(out)) throw new Error(`the emulator refused the camera image: ${out.trim()}`);
|
|
290
|
+
for (const n of readdirSync(f.dir)) if (/^dsh-dot-poster(-\d+)?\.png$/.test(n) && join(f.dir, n) !== file) { try { rmSync(join(f.dir, n), { force: true }); } catch {} }
|
|
291
|
+
return file;
|
|
280
292
|
};
|
|
281
|
-
phone.clearCamera = () => {
|
|
293
|
+
phone.clearCamera = async () => { try { await phone.adbExec(['emu', 'virtualscene-image', 'wall']); } catch {} };
|
|
282
294
|
// Notifications: what her phone shows her (see notifications.js). Listeners get posted and
|
|
283
295
|
// updated ones once each; the policy decides which apps count.
|
|
284
296
|
const notifyListeners = new Set();
|
|
@@ -347,7 +359,20 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
347
359
|
}
|
|
348
360
|
|
|
349
361
|
/** The poster file of the virtual-scene camera (read when an app opens the camera) and the PNG it shows. */
|
|
350
|
-
|
|
362
|
+
/** The emulator's scene poster list (resources/Toren1BD.posters, read at launch) and the image dsh-dot shows her camera. */
|
|
363
|
+
const posterFiles = () => { const dir = join(dirname(paths.emulator), 'resources'); return { dir, posters: join(dir, 'Toren1BD.posters'), png: join(dir, 'dsh-dot-poster.png') }; };
|
|
364
|
+
/** Before launch: the stock "wall" poster (behind the camera's start pose) moves in front of it; "table" stays. The original is kept as .orig. */
|
|
365
|
+
function ensureCameraScene() {
|
|
366
|
+
try {
|
|
367
|
+
const f = posterFiles();
|
|
368
|
+
if (!existsSync(f.posters)) return;
|
|
369
|
+
if (!existsSync(`${f.posters}.orig`)) writeFileSync(`${f.posters}.orig`, readFileSync(f.posters));
|
|
370
|
+
const stock = readFileSync(`${f.posters}.orig`, 'utf8');
|
|
371
|
+
const table = /poster table[\s\S]*?(?=\n\s*\n|\n?$)/.exec(stock)?.[0];
|
|
372
|
+
const want = `${WALL_POSTER}${table ? `\n${table.trimEnd()}\n` : ''}`;
|
|
373
|
+
if (readFileSync(f.posters, 'utf8') !== want) writeFileSync(f.posters, want);
|
|
374
|
+
} catch (err) { logger.warn(`camera scene: ${err.message}`); }
|
|
375
|
+
}
|
|
351
376
|
function ensureAvd() {
|
|
352
377
|
const dir = join(paths.avdHome, `${cfg.avd}.avd`);
|
|
353
378
|
if (existsSync(join(dir, 'config.ini'))) {
|
|
@@ -428,6 +453,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
428
453
|
if (await alreadyRunning()) {
|
|
429
454
|
logger.info(`${serial} is already running; attaching`);
|
|
430
455
|
} else {
|
|
456
|
+
ensureCameraScene();
|
|
431
457
|
const args = ['-avd', cfg.avd, '-port', String(cfg.port), '-no-boot-anim', '-gpu', cfg.gpu, '-netdelay', 'none', '-netspeed', 'full', ...(cfg.locale ? ['-change-locale', cfg.locale] : []), ...(cfg.timezone ? ['-timezone', cfg.timezone] : []), ...(cfg.window ? [] : ['-no-window'])];
|
|
432
458
|
// The phone outlives dsh (see the lifecycle effect), so it must not hold dsh's event loop:
|
|
433
459
|
// no pipes back to us (output goes to emulator.log), its own process group, and unref'd.
|
package/src/qq/qq.js
CHANGED
|
@@ -89,10 +89,20 @@ const SL_QQ_PIN = {
|
|
|
89
89
|
// The VM desktop's X display, as ":N": the one the VNC server shows (that is what the 虚拟机 tab and
|
|
90
90
|
// the QR screenshot see), else any live X server, else :99. Not "first socket in /tmp/.X11-unix":
|
|
91
91
|
// NapCat's xvfb-run leaves sockets of dead servers there (:101, :102), and QQ exits on one of those.
|
|
92
|
-
const SL_DISPLAY = String.raw`D=$(ps -eo args | awk '$1 ~ /(^|\/)(Xvnc|Xtigervnc|x11vnc)$/ { for (i = 2; i <= NF; i++) if ($i ~ /^:[0-9]
|
|
93
|
-
String.raw`[ -n "$D" ] || D=$(ps -eo args | awk '$1 ~ /(^|\/)X[A-Za-z]*$/ { for (i = 2; i <= NF; i++) if ($i ~ /^:[0-9]
|
|
92
|
+
const SL_DISPLAY = String.raw`D=$(ps -eo args | awk '$1 ~ /(^|\/)(Xvnc|Xtigervnc|x11vnc)$/ { for (i = 2; i <= NF; i++) if ($i ~ /^:[0-9]+(\.[0-9]+)?$/) { sub(/\.[0-9]+$/, "", $i); print $i; exit } }'); ` +
|
|
93
|
+
String.raw`[ -n "$D" ] || D=$(ps -eo args | awk '$1 ~ /(^|\/)X[A-Za-z]*$/ && !/ -auth / { for (i = 2; i <= NF; i++) if ($i ~ /^:[0-9]+(\.[0-9]+)?$/) { sub(/\.[0-9]+$/, "", $i); print $i; exit } }'); ` + 'D="${D:-:99}"';
|
|
94
94
|
// "[s]" keeps pgrep/pkill from matching their own shell, as "[o]pt" does for QQ.
|
|
95
95
|
const SL_PGREP = '[s]nowluma/index.mjs';
|
|
96
|
+
// How often /qq qr puts a fresh code in front of her camera, and for how long.
|
|
97
|
+
const QR_REFRESH_MS = 40_000;
|
|
98
|
+
const QR_REFRESH_FOR_MS = 4 * 60_000;
|
|
99
|
+
// Reads the first barcode in an image (argv[1]) with zxing-cpp; exits non-zero when the module is missing.
|
|
100
|
+
const ZXING_PY = 'import sys, zxingcpp; from PIL import Image; r = zxingcpp.read_barcodes(Image.open(sys.argv[1])); print(r[0].text if r else "")';
|
|
101
|
+
// SnowLuma's own Node (its SQLite store needs Node >= 24; the image ships 22): a checksum-verified
|
|
102
|
+
// latest-v24.x, or a symlink to the system node when that is already new enough.
|
|
103
|
+
const SL_NODE_DIR = '/root/snowluma-node';
|
|
104
|
+
const SL_NODE = `${SL_NODE_DIR}/bin/node`;
|
|
105
|
+
const SL_NODE_MIRRORS = ['https://npmmirror.com/mirrors/node', 'https://nodejs.org/dist'];
|
|
96
106
|
|
|
97
107
|
/** OneBot 11 message segments → plain text the way a person would read them. */
|
|
98
108
|
export function segmentsToText(message, selfId = '') {
|
|
@@ -271,6 +281,17 @@ export function onebotConfig({ port, token }) {
|
|
|
271
281
|
* Bearer`, the gateway checks it and passes it through unchanged, and SnowLuma checks the same
|
|
272
282
|
* header — so both sides must expect the same value. The WS keeps cfg.token (key in its own header).
|
|
273
283
|
*/
|
|
284
|
+
/**
|
|
285
|
+
* Why the QQ that connected must not be used, or null. Her account is the configured one; your own
|
|
286
|
+
* number is never hers, even when no account is configured.
|
|
287
|
+
*/
|
|
288
|
+
export function wrongAccount(selfId, { qq, owner }) {
|
|
289
|
+
if (!selfId) return null;
|
|
290
|
+
if (owner && selfId === String(owner)) return `QQ in the computer is logged into the owner's account ${selfId}, not hers — disconnected so she cannot speak as you. Log out there (or /qq stop), log in ${qq || 'her account'}, then /qq start`;
|
|
291
|
+
if (qq && selfId !== String(qq)) return `QQ in the computer is logged into ${selfId}, not her account ${qq} — disconnected. Log in ${qq}, then /qq start`;
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
|
|
274
295
|
export function snowlumaConfig({ port, token, httpToken = token, httpPort = SL_HTTP_PORT }) {
|
|
275
296
|
const common = { enabled: true, host: '127.0.0.1', path: '/', messageFormat: 'array', reportSelfMessage: false };
|
|
276
297
|
return {
|
|
@@ -400,7 +421,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
400
421
|
/** Is the given backend (default: the configured one) installed in the computer? */
|
|
401
422
|
qq.installed = async (which = cfg.backend) => {
|
|
402
423
|
// SnowLuma needs both its own files and a Linux QQ to hook.
|
|
403
|
-
const probe = which === 'snowluma' ? `${SL_QQ}; test -x "$QQ" && test -f ${SL_DIR}/index.mjs && echo yes || echo no` : `test -x ${QQ_BIN} && echo yes || echo no`;
|
|
424
|
+
const probe = which === 'snowluma' ? `${SL_QQ}; test -x "$QQ" && test -f ${SL_DIR}/index.mjs && test -x ${SL_NODE} && echo yes || echo no` : `test -x ${QQ_BIN} && echo yes || echo no`;
|
|
404
425
|
try { return (await vmShell(probe)).trim() === 'yes'; } catch { return false; }
|
|
405
426
|
};
|
|
406
427
|
const INSTALL_LOG = `${VM_HOME}/napcat-install.log`;
|
|
@@ -440,8 +461,27 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
440
461
|
`test -x ${QQ_BIN} && rc=0; echo $rc > ${INSTALL_DONE}`,
|
|
441
462
|
].join('\n');
|
|
442
463
|
}
|
|
464
|
+
/** Shell lines that leave a Node >= 24 at SL_NODE (the system one if new enough, else latest-v24.x, sha256-checked). Needs $arch (x64|arm64). */
|
|
465
|
+
function snowlumaNodeScript(failure) {
|
|
466
|
+
return [
|
|
467
|
+
'nodeok() { [ -x "$1" ] && "$1" -e \'process.exit(+process.versions.node.split(".")[0] >= 24 ? 0 : 1)\' 2>/dev/null; }',
|
|
468
|
+
`if ! nodeok ${SL_NODE}; then`,
|
|
469
|
+
` if nodeok "$(command -v node)"; then mkdir -p ${SL_NODE_DIR}/bin && ln -sf "$(command -v node)" ${SL_NODE};`,
|
|
470
|
+
' else ok=;',
|
|
471
|
+
` for base in ${SL_NODE_MIRRORS.join(' ')}; do`,
|
|
472
|
+
' line=$(curl -fsSL --connect-timeout 15 --max-time 60 "$base/latest-v24.x/SHASUMS256.txt" | grep -E " node-v24\\.[0-9.]+-linux-$arch\\.tar\\.xz$" | head -1); [ -n "$line" ] || continue',
|
|
473
|
+
' f=${line##* }; curl -fSL --connect-timeout 15 --max-time 900 -o "/tmp/$f" "$base/latest-v24.x/$f" || continue',
|
|
474
|
+
' ( cd /tmp && echo "$line" | sha256sum -c - >/dev/null ) || { rm -f "/tmp/$f"; continue; }',
|
|
475
|
+
` rm -rf ${SL_NODE_DIR} && mkdir -p ${SL_NODE_DIR} && tar -xJf "/tmp/$f" -C ${SL_NODE_DIR} --strip-components=1 && rm -f "/tmp/$f" && ok=1 && break`,
|
|
476
|
+
' done',
|
|
477
|
+
` [ -n "$ok" ] || ${failure}`,
|
|
478
|
+
' fi',
|
|
479
|
+
'fi',
|
|
480
|
+
`nodeok ${SL_NODE} || ${failure}; echo "SnowLuma node $(${SL_NODE} -v)"`,
|
|
481
|
+
];
|
|
482
|
+
}
|
|
443
483
|
/**
|
|
444
|
-
* The SnowLuma installer script: the lite release for the VM's arch (
|
|
484
|
+
* The SnowLuma installer script: the lite release for the VM's arch (run by its own Node ≥ 24, see snowlumaNodeScript),
|
|
445
485
|
* unpacked so index.mjs sits in SL_DIR, our config written before its first start, and QQ's hot
|
|
446
486
|
* update host blocked (an updated QQ may no longer match the hook). QQ is a clean, pinned system
|
|
447
487
|
* linuxqq at /opt/QQ — separate from NapCat's patched copy. SnowLuma reads config/ from its working
|
|
@@ -453,10 +493,10 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
453
493
|
const fetch = prefixes.map((pre) => `curl -fSL --connect-timeout 15 --max-time 600 -o snowluma.tgz "${pre}$asset"`).join(' || ');
|
|
454
494
|
return [
|
|
455
495
|
`cd ${VM_HOME}; export HOME=${VM_HOME}; rm -f ${SL_INSTALL_DONE} snowluma.tgz; rm -rf ${SL_DIR}.tmp`,
|
|
456
|
-
`node -e 'process.exit(+process.versions.node.split(".")[0] >= 22 ? 0 : 1)' || ${fail(4, 'SnowLuma needs Node >= 22 in the computer')}`,
|
|
457
496
|
`case "$(uname -m)" in aarch64|arm64) arch=arm64; qarch=arm64; qsum=${SL_QQ_PIN.sha256.arm64};; x86_64|amd64) arch=x64; qarch=amd64; qsum=${SL_QQ_PIN.sha256.amd64};; *) ${fail(4, 'unsupported CPU for SnowLuma')};; esac`,
|
|
497
|
+
...snowlumaNodeScript(fail(4, 'cannot install Node 24 for SnowLuma (npmmirror and nodejs.org both failed)')),
|
|
458
498
|
// A clean system linuxqq (the pinned build, checksum-verified) plus what QQ and the QR screenshot need.
|
|
459
|
-
`export DEBIAN_FRONTEND=noninteractive; apt-get update -qq || true; apt-get install -y -qq libgbm1 libnss3 libgtk-3-0 libxshmfence1 libxdamage1 libdrm2 libxkbcommon0 fontconfig fonts-noto-cjk dbus-x11 imagemagick >/dev/null || apt-get install -y -qq libasound2t64 || apt-get install -y -qq libasound2 || true`,
|
|
499
|
+
`export DEBIAN_FRONTEND=noninteractive; apt-get update -qq || true; apt-get install -y -qq libgbm1 libnss3 libgtk-3-0 libxshmfence1 libxdamage1 libdrm2 libxkbcommon0 fontconfig fonts-noto-cjk dbus-x11 imagemagick xz-utils zbar-tools qrencode >/dev/null || apt-get install -y -qq libasound2t64 || apt-get install -y -qq libasound2 || true`,
|
|
460
500
|
`if [ ! -x /opt/QQ/qq ]; then q="QQ_${SL_QQ_PIN.version}_\${qarch}_01.deb"; { curl -fSL --connect-timeout 15 --max-time 900 -o "/tmp/$q" "${SL_QQ_PIN.base}/$q" || curl -fSL --connect-timeout 15 --max-time 900 -o "/tmp/$q" "${(cfg.githubProxy || '')}${SL_QQ_PIN.mirror}/$q"; } || ${fail(3, 'cannot download Linux QQ')}; echo "$qsum /tmp/$q" | sha256sum -c - >/dev/null || ${fail(3, 'Linux QQ package checksum mismatch — not installing it')}; apt-get install -y -qq "/tmp/$q" >/dev/null || apt-get -f install -y -qq >/dev/null; rm -f "/tmp/$q"; fi`,
|
|
461
501
|
`[ -x /opt/QQ/qq ] || ${fail(3, 'Linux QQ did not install to /opt/QQ/qq')}`,
|
|
462
502
|
`tag=${JSON.stringify(cfg.snowlumaVersion)}`,
|
|
@@ -516,7 +556,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
516
556
|
// One account, one desktop client: NapCat and SnowLuma's QQ are both "the computer"; never both.
|
|
517
557
|
// Always its own shell call: pkill -f matches whole command lines, and a start script names the QQ
|
|
518
558
|
// path it launches, so a script that kills and then starts would kill itself first.
|
|
519
|
-
const KILL_ALL = `pkill -f "${SL_PGREP}" || true; pkill -f "[o]pt/QQ/qq" || true; sleep 1`;
|
|
559
|
+
const KILL_ALL = `pkill -f "${SL_PGREP}" || true; pkill -f "[o]pt/QQ/qq" || true; pkill -f "^Xvfb .*xvfb-run" || true; sleep 1`;
|
|
520
560
|
/** The GUI QQ on the VM desktop, then SnowLuma hooking it (as root: no setcap needed for ptrace). */
|
|
521
561
|
const snowlumaStartScript = () => [
|
|
522
562
|
`cd ${VM_HOME}; export HOME=${VM_HOME}`,
|
|
@@ -527,7 +567,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
527
567
|
'sleep 5',
|
|
528
568
|
// By absolute path, so pgrep -f sees "snowluma/index.mjs"; spelled through $SL so this shell's own
|
|
529
569
|
// command line does not match it (a later KILL_ALL or running() probe sees only the real process).
|
|
530
|
-
`SL=${SL_DIR}; cd "$SL" && setsid nohup
|
|
570
|
+
`SL=${SL_DIR}; cd "$SL" && setsid nohup ${SL_NODE} "$SL"/index.mjs >> ${SL_LOG} 2>&1 < /dev/null & disown`,
|
|
531
571
|
'sleep 1; echo "started on $D"',
|
|
532
572
|
].join('\n');
|
|
533
573
|
qq.start = async () => {
|
|
@@ -538,7 +578,12 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
538
578
|
if (!(await qq.running())) {
|
|
539
579
|
if (sl()) {
|
|
540
580
|
await vmShell(KILL_ALL);
|
|
541
|
-
|
|
581
|
+
let out = '';
|
|
582
|
+
try { out = String(await vmShell(snowlumaStartScript())); } catch (err) {
|
|
583
|
+
// msb exec sometimes reports failure after both launches went off; trust the processes, not the exit.
|
|
584
|
+
if (!(await qq.running())) throw err;
|
|
585
|
+
logger.warn(`SnowLuma start shell: ${err.message.split('\n')[0]} (QQ and SnowLuma are running)`);
|
|
586
|
+
}
|
|
542
587
|
if (out.includes('ptrace-blocked')) { setState('error', 'the computer forbids ptrace (kernel.yama.ptrace_scope = 3); SnowLuma cannot hook QQ — use the napcat backend'); return false; }
|
|
543
588
|
audit({ kind: 'snowluma-started' });
|
|
544
589
|
logger.info('SnowLuma started (QQ on the computer desktop; log in by QR there)');
|
|
@@ -553,20 +598,60 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
553
598
|
connect();
|
|
554
599
|
return true;
|
|
555
600
|
};
|
|
556
|
-
qq.stop = async () => { closeWs(); unmountMcp(); try { await vmShell(KILL_ALL); } catch {} setState('stopped'); audit({ kind: `${cfg.backend}-stopped` }); };
|
|
601
|
+
qq.stop = async () => { if (qrFreshTimer) { clearInterval(qrFreshTimer); qrFreshTimer = null; } closeWs(); unmountMcp(); try { await vmShell(KILL_ALL); } catch {} setState('stopped'); audit({ kind: `${cfg.backend}-stopped` }); };
|
|
557
602
|
/** SnowLuma's login QR is drawn by the QQ GUI: a picture of the VM screen, with whichever tool exists. */
|
|
603
|
+
/** SnowLuma: keep a live code in front of her camera while she scans (QQ's codes last about a minute). */
|
|
604
|
+
let qrFreshTimer = null;
|
|
605
|
+
function keepCameraFresh(phone, firstCode) {
|
|
606
|
+
if (qrFreshTimer) clearInterval(qrFreshTimer);
|
|
607
|
+
let lastCode = firstCode;
|
|
608
|
+
const until = Date.now() + QR_REFRESH_FOR_MS;
|
|
609
|
+
qrFreshTimer = setInterval(async () => {
|
|
610
|
+
if (qq.connected || Date.now() > until || !phone?.isReady) { clearInterval(qrFreshTimer); qrFreshTimer = null; return; }
|
|
611
|
+
const got = await screenQr();
|
|
612
|
+
if (got?.redrawn && got.code !== lastCode) {
|
|
613
|
+
lastCode = got.code;
|
|
614
|
+
try { await phone.showToCamera(got.png); logger.info('qr: a new login code is in front of her camera (close and reopen 扫一扫 to see it)'); } catch (err) { logger.debug(`qr refresh: ${err.message}`); }
|
|
615
|
+
}
|
|
616
|
+
}, QR_REFRESH_MS);
|
|
617
|
+
qrFreshTimer.unref?.();
|
|
618
|
+
}
|
|
558
619
|
async function screenQr() {
|
|
559
620
|
try {
|
|
560
621
|
const out = String(await vmShell([
|
|
561
622
|
`${SL_DISPLAY}`,
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
'
|
|
565
|
-
'
|
|
623
|
+
// Just the QQ window when it can be found, else the whole screen.
|
|
624
|
+
`W=$(xwininfo -display $D -root -tree 2>/dev/null | awk '/ "QQ": / { print $1; exit }'); W=\${W:-root}`,
|
|
625
|
+
'f=/tmp/dot-screen.png; q=/tmp/dot-qr.png; rm -f $f $q',
|
|
626
|
+
'shot() { if command -v import >/dev/null; then DISPLAY=$D import -window "$W" $f; elif command -v xwd >/dev/null && command -v convert >/dev/null; then xwd -root -display $D | convert xwd:- $f; elif command -v scrot >/dev/null; then DISPLAY=$D scrot -o $f; fi; }',
|
|
627
|
+
'shot',
|
|
628
|
+
'[ -s $f ] || { echo no-screenshot-tool; exit 0; }',
|
|
629
|
+
// The code itself, redrawn large and sharp: a small code inside a window, rendered through the
|
|
630
|
+
// phone camera's virtual room, is too soft for QQ's scanner. Decoded from the screen, re-encoded.
|
|
631
|
+
// QQ draws its code with round dots and round finders: zbar and OpenCV miss it, zxing-cpp reads it.
|
|
632
|
+
`dec() { python3 -I -c ${JSON.stringify(ZXING_PY)} "$1" 2>/dev/null; }`,
|
|
633
|
+
// Older pip (Ubuntu 22.04's) has no --break-system-packages and refuses the whole command with it.
|
|
634
|
+
'if ! dec $f >/dev/null; then bsp=; python3 -m pip install --help 2>/dev/null | grep -q break-system-packages && bsp=--break-system-packages; for idx in https://pypi.tuna.tsinghua.edu.cn/simple https://pypi.org/simple; do timeout 180 python3 -m pip install -q $bsp -i $idx zxing-cpp pillow >/tmp/dot-pip.log 2>&1 && break; done; dec $f >/dev/null || echo "note: zxing-cpp unavailable: $(tail -1 /tmp/dot-pip.log 2>/dev/null)"; fi',
|
|
635
|
+
'command -v qrencode >/dev/null || DEBIAN_FRONTEND=noninteractive timeout 120 apt-get install -y -qq qrencode zbar-tools >/dev/null 2>&1',
|
|
636
|
+
'read_code() { t=$(dec $f | head -1); [ -n "$t" ] || t=$(zbarimg -q --raw $f 2>/dev/null | head -1); }',
|
|
637
|
+
'read_code',
|
|
638
|
+
// No code readable: it has expired (QQ greys it out under 刷新). Click 刷新 then — and only then:
|
|
639
|
+
// clicking a live code replaces it, which voids the one already in front of her camera.
|
|
640
|
+
// The login window is 680×440 with the code centred at (540, 182).
|
|
641
|
+
'if [ -z "$t" ] && [ "$W" != root ]; then command -v xdotool >/dev/null || DEBIAN_FRONTEND=noninteractive timeout 120 apt-get install -y -qq xdotool >/dev/null 2>&1; g=$(xwininfo -display $D -id $W | awk \'/Width:/ { w = $2 } /Height:/ { h = $2 } END { print w "x" h }\'); if [ "$g" = 680x440 ] && command -v xdotool >/dev/null; then DISPLAY=$D xdotool mousemove --window $W 540 182 click 1 2>/dev/null; sleep 3; shot; read_code; echo "note: the code had expired; clicked 刷新"; fi; fi',
|
|
642
|
+
'[ -n "$t" ] && echo "code: $(printf %s "$t" | sha1sum | cut -c1-12)"',
|
|
643
|
+
'[ -n "$t" ] || echo "note: no code read off the screen"',
|
|
644
|
+
// Redrawn on a square twice its size, a quarter of its width right of centre: QQ's scanner shows
|
|
645
|
+
// the poster cropped tighter than the camera app and shifted, and cut off the left finder pattern.
|
|
646
|
+
'if [ -n "$t" ] && qrencode -s 16 -m 4 -o $q "$t" 2>/dev/null; then w=$(identify -format %w $q 2>/dev/null); [ -n "$w" ] && convert -size $((w*2))x$((w*2)) xc:white $q -gravity center -geometry +$((w/4))+0 -composite $q 2>/dev/null; echo redrawn; base64 -w0 $q; else base64 -w0 $f; fi',
|
|
647
|
+
'rm -f $f $q',
|
|
566
648
|
].join('\n'))).trim();
|
|
567
649
|
if (!out || out.includes('no-screenshot-tool')) { logger.warn('qr: no screenshot tool in the computer (ImageMagick import, xwd+convert or scrot); open the 虚拟机 tab instead'); return null; }
|
|
568
650
|
const png = Buffer.from(out.split('\n').pop(), 'base64');
|
|
569
|
-
|
|
651
|
+
const notes = out.split('\n').filter((l) => l.startsWith('note: ')).map((l) => l.slice(6));
|
|
652
|
+
if (!out.includes('redrawn')) logger.info(`qr: showing the window as it is (${notes.join('; ') || 'code not read'})`);
|
|
653
|
+
const code = /^code: (\w+)$/m.exec(out)?.[1] ?? '';
|
|
654
|
+
return png.length ? { png, ageS: 0, redrawn: out.includes('redrawn'), notes, code } : null;
|
|
570
655
|
} catch (err) { logger.warn(`qr: ${err.message}`); return null; }
|
|
571
656
|
}
|
|
572
657
|
/**
|
|
@@ -691,6 +776,15 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
691
776
|
if (ev.status === 'ok' || ev.retcode === 0) p.resolve(ev.data); else p.reject(new Error(ev.message || ev.wording || `retcode ${ev.retcode}`));
|
|
692
777
|
return;
|
|
693
778
|
}
|
|
779
|
+
// Logged into some other account (a cached quick login can pick yours): she must never speak as
|
|
780
|
+
// it. Drop the socket, unmount her QQ tools, and say so; /qq start after logging in the right one.
|
|
781
|
+
if (ev.self_id !== undefined && ev.self_id !== null) {
|
|
782
|
+
const why = wrongAccount(String(ev.self_id), { qq: qq.qq, owner: qq.owner });
|
|
783
|
+
if (why) {
|
|
784
|
+
if (qq.state !== 'wrong-account') { closeWs(); unmountMcp(); setState('wrong-account', why); audit({ kind: 'wrong-account', selfId: String(ev.self_id) }); logger.warn(`qq: ${why}`); }
|
|
785
|
+
return;
|
|
786
|
+
}
|
|
787
|
+
}
|
|
694
788
|
if (ev.post_type === 'meta_event') {
|
|
695
789
|
if (ev.meta_event_type === 'lifecycle' && ev.sub_type === 'connect') { qq.connected = true; qq.selfId = String(ev.self_id ?? ''); setState('connected'); audit({ kind: 'connected', selfId: qq.selfId }); }
|
|
696
790
|
if (ev.meta_event_type === 'heartbeat') { qq.connected = true; qq.selfId ||= String(ev.self_id ?? ''); if (qq.state !== 'connected') setState('connected'); }
|
|
@@ -905,7 +999,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
905
999
|
const file = join(dshHome(), 'phone', `qq-login-${stamp}.png`);
|
|
906
1000
|
mkdirSync(dirname(file), { recursive: true });
|
|
907
1001
|
writeFileSync(file, got.png);
|
|
908
|
-
extra = sl() ? `\
|
|
1002
|
+
extra = sl() ? `\n${got.redrawn ? 'login code read off the QQ window and redrawn large' : `the QQ window as it is — the code itself was not read (${(got.notes ?? []).join('; ') || 'unknown'})`}: ${file}` : `\nQR saved: ${file} (drawn ${got.ageS}s ago; valid about a minute)`;
|
|
909
1003
|
const phone = ctx.get('dshPhone');
|
|
910
1004
|
if (phone?.isReady) {
|
|
911
1005
|
try {
|
|
@@ -916,7 +1010,13 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
916
1010
|
} catch (err) { extra += `\n(could not push to the phone: ${err.message})`; }
|
|
917
1011
|
// QQ's login codes refuse album imports; the camera is the way. The code becomes the poster the
|
|
918
1012
|
// phone's virtual-scene camera looks at, so QQ → 扫一扫 (camera) sees it directly.
|
|
919
|
-
try {
|
|
1013
|
+
try {
|
|
1014
|
+
if (phone.showToCamera) {
|
|
1015
|
+
await phone.showToCamera(got.png);
|
|
1016
|
+
extra += `\nand in front of her camera: on the phone open QQ → 扫一扫: the code fills the camera view → confirm. If QQ says the code expired, close 扫一扫, wait a few seconds and open it again. If the camera shows a room with a checkerboard TV and no code, /phone restart once (the code's frame moves in front of the camera at launch).`;
|
|
1017
|
+
if (sl()) { keepCameraFresh(phone, got.code); extra += `\nfor ${Math.round(QR_REFRESH_FOR_MS / 60000)} minutes (or until QQ connects) an expired code is renewed and put in front of her camera; each new code sends her phone to the home screen (the camera only takes a new picture while closed), so she reopens 扫一扫`; }
|
|
1018
|
+
}
|
|
1019
|
+
} catch (err) { extra += `\n(camera: ${err.message})`; }
|
|
920
1020
|
}
|
|
921
1021
|
}
|
|
922
1022
|
}
|