271 lines
11 KiB
TypeScript
271 lines
11 KiB
TypeScript
// Installing the Android app on a Rabbit R1 (or any Android device) over adb,
|
|
// with the accounts, history and chat names copied into its private storage,
|
|
// so it opens signed in and with everything already there.
|
|
//
|
|
// Files go in through `adb shell -T "run-as <pkg> ..."`: run-as needs the APK
|
|
// to be debuggable (android/build.py builds it that way), and shell -T (no
|
|
// pty) passes stdin through byte for byte, waits for the command to finish and
|
|
// returns its exit code. (exec-in does none of the last two: it ends the
|
|
// remote command as soon as stdin runs out.) Nothing secret touches the desktop's disk on
|
|
// the way: the accounts JSON is piped straight in.
|
|
import Database from 'better-sqlite3'
|
|
import { app } from 'electron'
|
|
import { spawn } from 'node:child_process'
|
|
import fs from 'node:fs'
|
|
import os from 'node:os'
|
|
import path from 'node:path'
|
|
import type { MessageDb, NameChange, ReadState } from './db'
|
|
|
|
export interface RabbitConfig {
|
|
sandbox?: boolean
|
|
voipms: { username: string; password: string } | null
|
|
gvoice: { number: string; cookies: Record<string, string> } | null
|
|
dids: Array<{ did: string; description: string }>
|
|
defaultDid?: string
|
|
// The relay server (relay.ts): address, token, and the key that seals everything.
|
|
relay?: { url: string; token: string; key: string } | null
|
|
}
|
|
|
|
export interface RabbitTarget {
|
|
pkg: string
|
|
apk: string
|
|
}
|
|
|
|
export interface DeviceInfo {
|
|
serial: string
|
|
model: string
|
|
installedVersion?: string
|
|
}
|
|
|
|
const ADB_DIRS = ['/usr/local/sbin', '/usr/local/bin', '/usr/bin', path.join(os.homedir(), 'Android/Sdk/platform-tools')]
|
|
|
|
export function findAdb(): string | undefined {
|
|
const dirs = [...(process.env['PATH'] ?? '').split(':'), ...ADB_DIRS]
|
|
return dirs.map((d) => path.join(d, 'adb')).find((f) => f && fs.existsSync(f))
|
|
}
|
|
|
|
// The APK shipped with the desktop app (android/build.py --ship).
|
|
export function bundledApk(): { apk: string; version?: string } | undefined {
|
|
const packaged = path.join(process.resourcesPath ?? '', 'android', 'VoipMessages.apk')
|
|
const dev = path.join(app.getAppPath(), 'resources', 'android', 'VoipMessages.apk')
|
|
const apk = [packaged, dev].find((f) => fs.existsSync(f))
|
|
if (!apk) return undefined
|
|
try {
|
|
const meta = JSON.parse(fs.readFileSync(apk.replace(/\.apk$/, '.json'), 'utf8')) as { version_name: string }
|
|
return { apk, version: meta.version_name }
|
|
} catch {
|
|
return { apk }
|
|
}
|
|
}
|
|
|
|
class Adb {
|
|
constructor(
|
|
readonly adb: string,
|
|
readonly serial: string
|
|
) {}
|
|
|
|
// Runs adb; resolves stdout. `input` is piped to stdin (a Buffer or a stream).
|
|
run(args: string[], input?: Buffer | NodeJS.ReadableStream, timeoutMs = 120_000): Promise<Buffer> {
|
|
return new Promise((resolve, reject) => {
|
|
const p = spawn(this.adb, this.serial ? ['-s', this.serial, ...args] : args)
|
|
const out: Buffer[] = []
|
|
const err: Buffer[] = []
|
|
const timer = setTimeout(() => p.kill(), timeoutMs)
|
|
p.stdout.on('data', (d: Buffer) => out.push(d))
|
|
p.stderr.on('data', (d: Buffer) => err.push(d))
|
|
p.on('error', reject)
|
|
p.on('close', (code) => {
|
|
clearTimeout(timer)
|
|
const stderr = Buffer.concat(err).toString().trim()
|
|
if (code === 0) resolve(Buffer.concat(out))
|
|
else reject(new Error(stderr.split('\n').pop() || `adb ${args[0]} failed (${code})`))
|
|
})
|
|
if (input instanceof Buffer) p.stdin.end(input)
|
|
else if (input) (input as NodeJS.ReadableStream).pipe(p.stdin)
|
|
else p.stdin.end()
|
|
})
|
|
}
|
|
|
|
async shell(cmd: string, timeoutMs?: number): Promise<string> {
|
|
return (await this.run(['shell', cmd], undefined, timeoutMs)).toString()
|
|
}
|
|
|
|
// A command run as the app (in its private data dir), fed `input`.
|
|
asApp(pkg: string, cmd: string, input?: Buffer | NodeJS.ReadableStream, timeoutMs?: number): Promise<Buffer> {
|
|
return this.run(['shell', '-T', `run-as ${pkg} sh -c ${shq(cmd)}`], input, timeoutMs)
|
|
}
|
|
|
|
readAsApp(pkg: string, file: string): Promise<Buffer> {
|
|
return this.run(['exec-out', `run-as ${pkg} sh -c ${shq(`cat ${file} 2>/dev/null || true`)}`])
|
|
}
|
|
}
|
|
|
|
const shq = (s: string): string => `'${s.replace(/'/g, `'\\''`)}'`
|
|
|
|
async function listDevices(adb: string): Promise<Array<{ serial: string; state: string; model: string }>> {
|
|
const out = await new Adb(adb, '').run(['devices', '-l']).catch(() => Buffer.from(''))
|
|
return out
|
|
.toString()
|
|
.split('\n')
|
|
.slice(1)
|
|
.map((l) => l.trim())
|
|
.filter(Boolean)
|
|
.map((l) => {
|
|
const [serial, state] = l.split(/\s+/)
|
|
const model = /model:(\S+)/.exec(l)?.[1]?.replace(/_/g, ' ') ?? serial
|
|
return { serial, state, model }
|
|
})
|
|
}
|
|
|
|
export async function connect(): Promise<Adb> {
|
|
const adb = findAdb()
|
|
if (!adb) throw new Error("adb isn't installed on this computer.")
|
|
const devices = await listDevices(adb)
|
|
const ready = devices.find((d) => d.state === 'device')
|
|
if (ready) return new Adb(adb, ready.serial)
|
|
if (devices.some((d) => d.state === 'unauthorized')) throw new Error('Unlock the Rabbit and allow USB debugging for this computer.')
|
|
throw new Error('No Rabbit connected. Plug it in over USB (with USB debugging on).')
|
|
}
|
|
|
|
export async function status(pkg: string): Promise<DeviceInfo | undefined> {
|
|
const adb = findAdb()
|
|
if (!adb) return undefined
|
|
const ready = (await listDevices(adb)).find((d) => d.state === 'device')
|
|
if (!ready) return undefined
|
|
const a = new Adb(adb, ready.serial)
|
|
const info = await a.shell(`dumpsys package ${pkg} | grep -m1 versionName`).catch(() => '')
|
|
const version = /versionName=(\S+)/.exec(info)?.[1]
|
|
return { serial: ready.serial, model: ready.model, ...(version ? { installedVersion: version } : {}) }
|
|
}
|
|
|
|
// A copy of the history the Android app can open: its SQLite has no FTS5,
|
|
// so the search index (and the triggers that feed it) come out.
|
|
async function historyCopy(db: MessageDb): Promise<string> {
|
|
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'voip-rabbit-'))
|
|
const file = path.join(dir, 'messages.db')
|
|
await db.db.backup(file)
|
|
const copy = new Database(file)
|
|
copy.exec(`
|
|
DROP TRIGGER IF EXISTS messages_ai; DROP TRIGGER IF EXISTS messages_ad; DROP TRIGGER IF EXISTS messages_au;
|
|
DROP TABLE IF EXISTS messages_fts;
|
|
DROP TABLE IF EXISTS relay_outbox;
|
|
DELETE FROM kv WHERE key LIKE 'relay%';
|
|
`)
|
|
copy.pragma('journal_mode = DELETE')
|
|
copy.exec('VACUUM')
|
|
copy.close()
|
|
return file
|
|
}
|
|
|
|
// Merge chat names and read/unread/archived state both ways: the Rabbit's
|
|
// (files/state.json, which the app keeps current) into the desktop, then the
|
|
// combined result back (files/state-in.json, applied by the app on its next
|
|
// start or check). Newest change wins on each side. Returns how many
|
|
// conversations changed here.
|
|
interface SyncState {
|
|
names: NameChange[]
|
|
read: ReadState[]
|
|
}
|
|
|
|
async function syncState(a: Adb, pkg: string, db: MessageDb): Promise<number> {
|
|
const raw = (await a.readAsApp(pkg, 'files/state.json')).toString().trim()
|
|
let theirs: SyncState = { names: [], read: [] }
|
|
try {
|
|
if (raw) theirs = { names: [], read: [], ...(JSON.parse(raw) as Partial<SyncState>) }
|
|
} catch {
|
|
/* a half-written file: skip this round */
|
|
}
|
|
const changed = db.namesImport(theirs.names) + db.readStateImport(theirs.read)
|
|
const ours: SyncState = { names: db.namesExport(), read: db.readStateExport() }
|
|
await a.asApp(pkg, 'umask 077 && cat > files/state-in.json.tmp && mv files/state-in.json.tmp files/state-in.json', Buffer.from(JSON.stringify(ours)))
|
|
return changed
|
|
}
|
|
|
|
export type Progress = (step: string) => void
|
|
|
|
export interface InstallDeps {
|
|
db: MessageDb
|
|
mediaDir: string
|
|
target: RabbitTarget
|
|
config: () => Promise<RabbitConfig>
|
|
progress: Progress
|
|
}
|
|
|
|
async function pushConfig(a: Adb, pkg: string, cfg: RabbitConfig): Promise<void> {
|
|
// Straight from memory into the app's private files: no temp file.
|
|
await a.asApp(pkg, 'mkdir -p files && umask 077 && cat > files/config.json.tmp && mv files/config.json.tmp files/config.json', Buffer.from(JSON.stringify(cfg)))
|
|
}
|
|
|
|
async function lockDown(a: Adb, pkg: string): Promise<void> {
|
|
await a.asApp(pkg, 'chmod -R go-rwx files')
|
|
}
|
|
|
|
// Fresh install (or reinstall): app, permissions, accounts, history, photos, names.
|
|
// Photos the Rabbit doesn't have yet (files are named by content hash, so a
|
|
// name it already has is the same file). Returns how many were sent.
|
|
async function copyMedia(a: Adb, pkg: string, mediaDir: string, progress: Progress): Promise<number> {
|
|
if (!fs.existsSync(mediaDir)) return 0
|
|
const have = new Set((await a.asApp(pkg, 'mkdir -p files/media && ls files/media')).toString().split('\n').map((l) => l.trim()))
|
|
const missing = fs.readdirSync(mediaDir).filter((f) => !have.has(f) && fs.statSync(path.join(mediaDir, f)).isFile())
|
|
if (!missing.length) return 0
|
|
progress(`Copying ${missing.length.toLocaleString()} photo${missing.length === 1 ? '' : 's'} and attachments…`)
|
|
const tar = spawn('tar', ['-C', mediaDir, '-cf', '-', '-T', '-'])
|
|
tar.stdin.end(missing.join('\n') + '\n')
|
|
await a.asApp(pkg, 'cd files/media && tar xf -', tar.stdout, 1_800_000)
|
|
return missing.length
|
|
}
|
|
|
|
// 'full': the app plus history and photos (first install, or starting over;
|
|
// only photos the Rabbit lacks are sent). 'update': just the new app version
|
|
// -- Android keeps the app's data across an update -- plus accounts and the
|
|
// names / read-status merge.
|
|
export async function install({ db, mediaDir, target, config, progress, mode = 'full' }: InstallDeps & { mode?: 'full' | 'update' }): Promise<number> {
|
|
const { pkg, apk } = target
|
|
progress('Connecting to the Rabbit…')
|
|
const a = await connect()
|
|
progress('Installing the app…')
|
|
await a.run(['install', '-r', '-g', apk], undefined, 300_000)
|
|
// Background checks: exempt from Doze and background limits.
|
|
await a.shell(`dumpsys deviceidle whitelist +${pkg}`).catch(() => undefined)
|
|
await a.shell(`cmd appops set ${pkg} RUN_ANY_IN_BACKGROUND allow`).catch(() => undefined)
|
|
await a.shell(`am force-stop ${pkg}`)
|
|
|
|
progress('Copying your accounts…')
|
|
await pushConfig(a, pkg, await config())
|
|
|
|
if (mode === 'full') {
|
|
progress('Copying your message history…')
|
|
const history = await historyCopy(db)
|
|
try {
|
|
await a.asApp(pkg, 'rm -f files/messages.db files/messages.db-wal files/messages.db-shm files/messages.db-journal')
|
|
await a.asApp(pkg, 'umask 077 && cat > files/messages.db', fs.createReadStream(history), 600_000)
|
|
} finally {
|
|
fs.rmSync(path.dirname(history), { recursive: true, force: true })
|
|
}
|
|
await copyMedia(a, pkg, mediaDir, progress)
|
|
}
|
|
|
|
progress('Syncing chat names and read status…')
|
|
const names = await syncState(a, pkg, db)
|
|
await lockDown(a, pkg)
|
|
progress('Opening it on the Rabbit…')
|
|
await a.shell(`am start -n ${pkg}/me.teafry.voipmessages.MainActivity`)
|
|
return names
|
|
}
|
|
|
|
// Accounts and chat names again (e.g. after reconnecting Google Voice), without
|
|
// touching the app or its history. Returns how many names changed here.
|
|
export async function sync({ db, target, config, progress }: Omit<InstallDeps, 'mediaDir'>): Promise<number> {
|
|
const { pkg } = target
|
|
progress('Connecting to the Rabbit…')
|
|
const a = await connect()
|
|
const installed = await a.shell(`pm path ${pkg}`).catch(() => '')
|
|
if (!installed.trim()) throw new Error("The app isn't on the Rabbit yet. Use Install to Rabbit first.")
|
|
progress('Copying your accounts…')
|
|
await pushConfig(a, pkg, await config())
|
|
progress('Syncing chat names and read status…')
|
|
const names = await syncState(a, pkg, db)
|
|
await lockDown(a, pkg)
|
|
return names
|
|
}
|