-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·680 lines (585 loc) · 23.8 KB
/
server.js
File metadata and controls
executable file
·680 lines (585 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
#!/usr/bin/env node
'use strict';
const path = require('path');
const fs = require('fs');
const net = require('net');
const { networkInterfaces } = require('os');
const { initConfig, initSessions, saveConfig, saveSessions, pruneSessions, ROOT, CONFIG_PATH, ENV_PATH, DEFAULT_CONFIG } = require('./src/config');
const { createServer } = require('./src/connection/http');
const { createConnectionHandler } = require('./src/connection/handler');
const { createTUI } = require('./src/tui-react');
const { createPinSystem } = require('./src/tui/pin-prompt');
const RelayClient = require('./src/relay/client');
const dialogs = require('./src/tui/dialogs');
const { getAiApiKey } = require('./src/ai');
// ─── CLI argument parsing ────────────────────────────────────────────────────
const args = process.argv.slice(2);
const command = args[0] || '';
// IPC socket path for daemon communication — use stable ~/.airmic/ dir
const AIRMIC_DIR = path.join(require('os').homedir(), '.airmic');
try { fs.mkdirSync(AIRMIC_DIR, { recursive: true }); } catch {}
const IPC_PATH = path.join(AIRMIC_DIR, '.airmic.sock');
const PID_PATH = path.join(AIRMIC_DIR, '.airmic.pid');
const LOG_PATH = path.join(AIRMIC_DIR, 'airmic.log');
// ─── Subcommand routing ──────────────────────────────────────────────────────
if (command === 'headless') {
const action = args[1];
if (action === 'on') {
const mode = (args[2] || '').toLowerCase();
if (mode && mode !== 'relay' && mode !== 'local') {
console.log('Usage: airmic headless on [relay|local]');
process.exit(1);
}
return startDaemon(mode || null);
}
if (action === 'off') return stopDaemon();
console.log('Usage: airmic headless on [relay|local] | off');
process.exit(1);
}
if (command === 'status') return showStatus();
if (command === 'approve') {
const pin = args[1];
if (!pin) { console.log('Usage: airmic approve <PIN>'); process.exit(1); }
return approvePin(pin);
}
if (command === 'help' || command === '--help' || command === '-h') {
console.log(`
AirMic — Turn your phone into a wireless mic
Usage:
airmic Launch TUI (interactive)
airmic setup Run first-time setup wizard
airmic headless on [relay|local] Start as background daemon
airmic headless off Stop the daemon
airmic status Show daemon status
airmic approve <PIN> Approve a new device by PIN
Options:
--help, -h Show this help
`);
process.exit(0);
}
if (command === 'setup') {
runSetup().then(() => process.exit(0));
} else if (command === '--headless-daemon') {
// Parse --mode=relay|local from daemon args
const modeArg = args.find(a => a.startsWith('--mode='));
const daemonMode = modeArg ? modeArg.split('=')[1] : null;
maybeSetup(true).then(() => startApp(true, daemonMode));
} else {
maybeSetup(false).then(() => startApp(false, null));
}
// ─── First-run setup wizard ──────────────────────────────────────────────────
function ask(rl, question) {
return new Promise(resolve => rl.question(question, answer => resolve(answer.trim())));
}
async function maybeSetup(headless) {
if (fs.existsSync(CONFIG_PATH)) return;
if (headless) {
// Headless mode can't run interactive setup — use defaults
console.log('[airmic] No config.json found — using defaults. Run `airmic setup` to configure.');
return;
}
console.log('\n Welcome to AirMic! Let\'s get you set up.\n');
await runSetup();
console.log('');
}
async function runSetup() {
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const existing = fs.existsSync(CONFIG_PATH) ? JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')) : {};
const config = { ...DEFAULT_CONFIG, ...existing };
// ── Connection mode ──
console.log(' Connection Mode');
console.log(' ───────────────');
console.log(' 1) Local only — phone connects over your WiFi (no internet needed)');
console.log(' 2) Relay — phone connects through the AirMic cloud relay (works anywhere)');
console.log(' 3) Both — local with relay fallback\n');
const modeAnswer = await ask(rl, ' Choose [1/2/3] (default: 3): ');
const mode = ['1', '2', '3'].includes(modeAnswer) ? modeAnswer : '3';
if (mode === '1') {
config.relayUrl = '';
config.relaySecret = '';
} else {
// Use default relay server
const defaultRelay = 'wss://amrelay1.returnfeed.com:4001';
const relayAnswer = await ask(rl, ` Relay URL (default: ${defaultRelay}): `);
config.relayUrl = relayAnswer || defaultRelay;
config.relaySecret = '';
}
// ── Port ──
const portAnswer = await ask(rl, `\n Local server port (default: ${config.port}): `);
const portNum = parseInt(portAnswer, 10);
if (portNum > 0 && portNum < 65536) config.port = portNum;
// ── Network interface ──
if (mode !== '2') {
const nets = networkInterfaces();
const ipv4 = [];
for (const [name, addrs] of Object.entries(nets)) {
for (const a of addrs) {
if (a.family === 'IPv4' && !a.internal) ipv4.push({ name, address: a.address });
}
}
if (ipv4.length > 1) {
console.log('\n Network Interface');
console.log(' ─────────────────');
console.log(' Multiple network interfaces detected. Which IP should the phone connect to?\n');
ipv4.forEach((iface, i) => console.log(` ${i + 1}) ${iface.address} (${iface.name})`));
console.log(` ${ipv4.length + 1}) Auto-detect (first non-internal IPv4)\n`);
const ifAnswer = await ask(rl, ` Choose [1-${ipv4.length + 1}] (default: auto): `);
const ifNum = parseInt(ifAnswer, 10);
if (ifNum >= 1 && ifNum <= ipv4.length) {
config.bindAddress = ipv4[ifNum - 1].address;
} else {
config.bindAddress = '';
}
} else if (ipv4.length === 1) {
config.bindAddress = ''; // only one — auto is fine
}
}
// ── AI ──
console.log('\n AI Text Cleanup');
console.log(' ───────────────');
console.log(' AirMic can clean up your speech using AI before typing it out.');
console.log(' Providers: openai, anthropic, google\n');
const aiAnswer = await ask(rl, ' Enable AI cleanup? [y/N]: ');
const wantAi = aiAnswer.toLowerCase().startsWith('y');
if (wantAi) {
config.aiEnabled = true;
console.log('\n 1) openai');
console.log(' 2) anthropic');
console.log(' 3) google\n');
const provAnswer = await ask(rl, ' Provider [1/2/3] (default: 1): ');
config.aiProvider = provAnswer === '2' ? 'anthropic' : provAnswer === '3' ? 'google' : 'openai';
const modelAnswer = await ask(rl, ` Model name (leave blank for default): `);
config.aiModel = modelAnswer.slice(0, 100);
const keyAnswer = await ask(rl, ' API key: ');
if (keyAnswer) {
// Save to .env, not config.json
const envLine = `AIRMIC_AI_KEY=${keyAnswer.trim()}\n`;
try {
const existingEnv = fs.existsSync(ENV_PATH) ? fs.readFileSync(ENV_PATH, 'utf8') : '';
const filtered = existingEnv.split('\n').filter(l => !l.startsWith('AIRMIC_AI_KEY=')).join('\n');
fs.writeFileSync(ENV_PATH, (filtered ? filtered + '\n' : '') + envLine);
} catch {}
}
} else {
config.aiEnabled = false;
}
// Save
saveConfig(config);
rl.close();
console.log('\n Config saved to config.json');
console.log(' Run `airmic setup` anytime to reconfigure.');
}
// ─── Start app (TUI or headless inline) ──────────────────────────────────────
async function startApp(headless, mode) {
const config = initConfig();
const sessions = initSessions();
// Override relay based on mode arg
if (mode === 'local') {
config.relayUrl = '';
config.relaySecret = '';
} else if (mode === 'relay' && !config.relayUrl) {
// Force relay with default if not configured
config.relayUrl = 'wss://amrelay1.returnfeed.com:4001';
}
// Detect input backend (xdotool, ydotool, osascript, powershell)
const inputBackend = require('./src/utils/input');
// Prune sessions daily
setInterval(() => pruneSessions(sessions), 24 * 60 * 60 * 1000);
// Create TUI (or headless stubs)
const tui = await createTUI(config, { headless });
// Initialize input backend with TUI logger
inputBackend.detect(tui.logPhrase);
// Create HTTP/WSS server
const { app, server, wss } = createServer(config, ROOT);
// Shared mutable state
let paused = false;
let totalPhrases = 0;
let totalWords = 0;
let localIP = 'localhost';
let localUrl = '';
// Relay client
const relay = new RelayClient(config, {
logFn: tui.logPhrase,
onStatus: (status) => {
tui.setAppState({ relayStatus: status });
tui.updateStatus();
},
onQR: () => doRenderQR(),
});
// PIN system
const pinCtx = {
headless,
blessed: tui.blessed,
screen: tui.screen,
sessions, saveSessions,
config,
getPaused: () => paused,
get phoneStates() { return connHandler ? connHandler.phoneStates : new Map(); },
logFn: tui.logPhrase,
updateStatus: () => tui.updateStatus(),
T: tui.T,
getConnectedCount: () => connHandler.getConnectedCount(),
setConnectedCount: (n) => {
connHandler.setConnectedCount(n);
tui.setAppState({ connectedCount: n });
},
};
const pinSystem = createPinSystem(pinCtx);
// Connection handler
const connHandler = createConnectionHandler({
config, sessions, saveSessions: (s) => saveSessions(s),
saveConfig: (c) => saveConfig(c),
wss,
logFn: tui.logPhrase,
setLive: tui.setLive,
updateStatus: () => {
tui.setAppState({
connectedCount: connHandler.getConnectedCount(),
paused, totalPhrases, totalWords,
phoneStates: connHandler.phoneStates,
});
tui.updateStatus();
},
getPaused: () => paused,
setPaused: (v) => { paused = v; },
showPinPrompt: pinSystem.showPinPrompt,
relayClient: relay,
onCountChange: (n) => tui.setAppState({ connectedCount: n }),
get totalPhrases() { return totalPhrases; },
set totalPhrases(v) { totalPhrases = v; },
get totalWords() { return totalWords; },
set totalWords(v) { totalWords = v; },
});
// Set relay's handleConnection
relay.handleConnection = connHandler.handleConnection;
// Local WSS connections
wss.on('connection', (ws, req) => {
const ip = req.socket.remoteAddress || 'unknown';
tui.logPhrase(`WSS connection from ${ip}`, 'connect');
connHandler.handleConnection(ws);
});
// QR rendering
function doRenderQR() {
const useRelay = config.relayUrl && relay.roomToken;
const relayPending = config.relayUrl && !relay.roomToken;
if (relayPending) {
// Relay configured but not connected yet — don't show unreachable local IP
tui.renderQR(null, 'relay-pending', localUrl);
return;
}
const displayUrl = useRelay
? config.relayUrl.replace(/^wss:\/\//, 'https://').replace(/\/$/, '') + `/${relay.roomToken}`
: localUrl;
const mode = useRelay ? 'relay' : 'local';
tui.renderQR(displayUrl, mode, localUrl);
}
// Helper functions for TUI context
function togglePause() {
paused = !paused;
tui.logPhrase(paused ? 'Paused' : 'Resumed', 'command');
connHandler.broadcast({ type: 'paused', value: paused });
tui.setAppState({ paused });
tui.updateStatus();
}
function reconnectRelay() {
relay.disconnect();
config._localUrl = localUrl;
tui.setAppState({ relayStatus: 'disabled' });
tui.updateStatus();
doRenderQR();
relay.connect();
}
function disconnectRelay() {
relay.disconnect();
tui.setAppState({ relayStatus: 'disabled' });
tui.updateStatus();
doRenderQR();
}
// Dialog context
const dialogCtx = {
blessed: tui.blessed, screen: tui.screen, T: tui.T,
config, sessions, saveSessions,
logFn: tui.logPhrase,
updateStatus: () => tui.updateStatus(),
togglePause,
clearLog: () => tui.clearLog(),
shutdown,
reconnectRelay,
disconnectRelay,
applyTheme: (name) => tui.applyTheme(name),
};
// Setup TUI key bindings and slash commands
if (!headless) {
const slashCommands = [
{ name: 'pause', desc: 'Toggle pause', fn: () => togglePause() },
{ name: 'relay', desc: 'Relay server settings', fn: () => dialogs.showRelayServers(dialogCtx) },
{ name: 'ai', desc: 'AI settings', fn: () => dialogs.showAiSettings(dialogCtx) },
{ name: 'replace', desc: 'Add word replacement', fn: () => dialogs.showAddReplace(dialogCtx) },
{ name: 'delreplace', desc: 'Delete word replacement', fn: () => dialogs.showDelReplace(dialogCtx) },
{ name: 'clear', desc: 'Clear log', fn: () => tui.clearLog() },
{ name: 'sessions', desc: 'Manage device sessions', fn: () => dialogs.showSessionManager(dialogCtx) },
{ name: 'theme', desc: 'Switch theme', fn: () => dialogs.showThemePicker(dialogCtx) },
{ name: 'help', desc: 'Show keybinds & commands', fn: () => dialogs.showHelp(dialogCtx) },
{ name: 'quit', desc: 'Exit AirMic', fn: () => shutdown() },
];
tui.setupInputBar(slashCommands);
tui.bindKeys({
shutdown,
togglePause,
showCommandPalette: () => dialogs.showCommandPalette(dialogCtx),
showRelayServers: () => dialogs.showRelayServers(dialogCtx),
showAiSettings: () => dialogs.showAiSettings(dialogCtx),
showAddReplace: () => dialogs.showAddReplace(dialogCtx),
showDelReplace: () => dialogs.showDelReplace(dialogCtx),
});
}
// ─── Start server ──────────────────────────────────────────────────────────
server.listen(config.port, '0.0.0.0', () => {
// Use configured bindAddress, or auto-detect first non-internal IPv4
if (config.bindAddress) {
localIP = config.bindAddress;
} else {
const nets = networkInterfaces();
for (const iface of Object.values(nets))
for (const n of iface)
if (n.family === 'IPv4' && !n.internal) { localIP = n.address; break; }
}
localUrl = `https://${localIP}:${config.port}/${config.urlToken}`;
config._localUrl = localUrl;
if (!headless) tui.showQR();
doRenderQR();
tui.logPhrase(`Server started — ${localUrl}`, 'connect');
if (headless) {
tui.logPhrase('Open the Phone URL above on your phone to connect', 'info');
} else {
tui.logPhrase('Scan QR or open URL on your phone', 'info');
}
if (config.relayUrl) {
tui.logPhrase(`Relay: connecting to ${config.relayUrl}`, 'info');
relay.connect();
} else {
if (headless) tui.logPhrase('Local only — set relayUrl in config.json to enable relay', 'info');
else tui.logPhrase('Local only — press Ctrl+E to add a relay', 'info');
}
if (!getAiApiKey()) {
if (headless) tui.logPhrase('Tip: set AIRMIC_AI_KEY in .env to enable AI summarize', 'info');
else tui.logPhrase('Tip: Ctrl+A to configure AI summarize', 'info');
}
if (!headless) tui.screen.render();
// Start IPC server for CLI commands
startIPC({ pinSystem, config, relay, localUrl: () => localUrl, paused: () => paused, connectedCount: () => connHandler.getConnectedCount(), totalPhrases: () => totalPhrases, totalWords: () => totalWords });
});
// ─── Shutdown ──────────────────────────────────────────────────────────────
function shutdown() {
relay.disconnect();
tui.destroy();
cleanupIPC();
process.exit(0);
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
process.on('exit', () => tui.destroy());
process.on('uncaughtException', (err) => { try { tui.logPhrase(`uncaughtException: ${err?.message || err}`, 'warn'); } catch { console.error('uncaughtException:', err); } });
process.on('unhandledRejection', (err) => { try { tui.logPhrase(`unhandledRejection: ${err?.message || err}`, 'warn'); } catch { console.error('unhandledRejection:', err); } });
}
// ─── IPC server (Unix socket) ────────────────────────────────────────────────
let ipcServer = null;
function startIPC(ctx) {
// Clean up stale socket
try { fs.unlinkSync(IPC_PATH); } catch {}
ipcServer = net.createServer((conn) => {
let buf = '';
conn.on('data', (data) => {
buf += data.toString();
if (!buf.includes('\n')) return;
const lines = buf.split('\n');
buf = lines.pop();
for (const line of lines) {
try {
const msg = JSON.parse(line);
const resp = handleIPC(msg, ctx);
conn.write(JSON.stringify(resp) + '\n');
} catch { conn.write(JSON.stringify({ error: 'invalid request' }) + '\n'); }
}
});
});
ipcServer.listen(IPC_PATH);
// Write PID file
fs.writeFileSync(PID_PATH, String(process.pid));
}
function handleIPC(msg, ctx) {
if (msg.cmd === 'status') {
const relayDisplayUrl = (ctx.config.relayUrl && ctx.relay.roomToken)
? ctx.config.relayUrl.replace(/^wss:\/\//, 'https://').replace(/\/$/, '') + `/${ctx.relay.roomToken}`
: null;
return {
ok: true,
pid: process.pid,
url: ctx.localUrl(),
relayDisplayUrl,
paused: ctx.paused(),
connectedCount: ctx.connectedCount(),
totalPhrases: ctx.totalPhrases(),
totalWords: ctx.totalWords(),
relayStatus: ctx.relay.status,
relayUrl: ctx.config.relayUrl || null,
pendingPins: ctx.pinSystem.getPendingPins(),
};
}
if (msg.cmd === 'approve' && msg.pin) {
const ok = ctx.pinSystem.approveByPin(String(msg.pin));
return { ok, message: ok ? 'Device approved' : 'PIN not found or device disconnected' };
}
return { error: 'unknown command' };
}
function cleanupIPC() {
if (ipcServer) { try { ipcServer.close(); } catch {} }
try { fs.unlinkSync(IPC_PATH); } catch {}
try { fs.unlinkSync(PID_PATH); } catch {}
}
// ─── CLI subcommands ─────────────────────────────────────────────────────────
function startDaemon(mode) {
// Check if already running
if (fs.existsSync(PID_PATH)) {
const pid = parseInt(fs.readFileSync(PID_PATH, 'utf8'));
try { process.kill(pid, 0); console.log(`AirMic is already running (PID ${pid})`); process.exit(1); }
catch {} // process not running, stale PID file
}
const { spawn } = require('child_process');
const logFd = fs.openSync(LOG_PATH, 'a');
const daemonArgs = [__filename, '--headless-daemon'];
if (mode) daemonArgs.push(`--mode=${mode}`);
const child = spawn(process.execPath, daemonArgs, {
detached: true,
stdio: ['ignore', logFd, logFd],
env: { ...process.env },
});
child.unref();
console.log(`AirMic daemon started (PID ${child.pid})${mode ? ` [${mode} mode]` : ''}`);
console.log(` Log: ${LOG_PATH}`);
console.log(` Stop: airmic headless off`);
console.log(` Status: airmic status`);
// Wait for IPC to come up, then print URL + QR
let attempts = 0;
const maxAttempts = 30;
const wantRelay = mode === 'relay' || (!mode && true); // if no mode, still wait a bit for relay
const poll = setInterval(() => {
attempts++;
if (attempts > maxAttempts) {
clearInterval(poll);
console.log('\n Daemon started but URL not yet available. Run `airmic status` to check.');
process.exit(0);
}
if (!fs.existsSync(IPC_PATH)) return;
const conn = net.createConnection(IPC_PATH);
let buf = '';
conn.on('connect', () => { conn.write(JSON.stringify({ cmd: 'status' }) + '\n'); });
conn.on('data', (data) => {
buf += data.toString();
if (!buf.includes('\n')) return;
try {
const resp = JSON.parse(buf.split('\n')[0]);
conn.destroy();
// If relay mode, keep polling until relay is connected AND has a room token
if (mode === 'relay' && resp.relayUrl && (!resp.relayDisplayUrl || resp.relayStatus !== 'connected')) {
return; // keep polling
}
clearInterval(poll);
const displayUrl = resp.relayDisplayUrl || resp.url;
if (displayUrl) {
if (resp.relayDisplayUrl) {
console.log(`\n Relay URL: ${resp.relayDisplayUrl}`);
}
if (resp.url) {
console.log(` Local URL: ${resp.url}`);
}
// Print QR code for the best URL
const QRCode = require('qrcode');
QRCode.toString(displayUrl, { type: 'terminal', small: true }, (err, qr) => {
if (!err && qr) console.log('\n' + qr);
process.exit(0);
});
} else {
process.exit(0);
}
} catch { conn.destroy(); }
});
conn.on('error', () => { conn.destroy(); });
}, 500);
}
function stopDaemon() {
if (!fs.existsSync(PID_PATH)) {
console.log('AirMic is not running');
process.exit(1);
}
const pid = parseInt(fs.readFileSync(PID_PATH, 'utf8'));
try {
process.kill(pid, 'SIGTERM');
console.log(`AirMic stopped (PID ${pid})`);
try { fs.unlinkSync(PID_PATH); } catch {}
try { fs.unlinkSync(IPC_PATH); } catch {}
} catch {
console.log(`Process ${pid} not found — cleaning up stale PID file`);
try { fs.unlinkSync(PID_PATH); } catch {}
try { fs.unlinkSync(IPC_PATH); } catch {}
}
process.exit(0);
}
function showStatus() {
if (!fs.existsSync(IPC_PATH)) {
console.log('AirMic is not running');
process.exit(1);
}
const conn = net.createConnection(IPC_PATH);
conn.on('connect', () => {
conn.write(JSON.stringify({ cmd: 'status' }) + '\n');
});
let buf = '';
conn.on('data', (data) => {
buf += data.toString();
if (!buf.includes('\n')) return;
const resp = JSON.parse(buf.split('\n')[0]);
conn.destroy();
console.log(`AirMic — running (PID ${resp.pid})`);
if (resp.url) console.log(` URL: ${resp.url}`);
if (resp.relayDisplayUrl) console.log(` Relay: ${resp.relayDisplayUrl}`);
console.log(` Devices: ${resp.connectedCount}`);
console.log(` Paused: ${resp.paused ? 'yes' : 'no'}`);
console.log(` Phrases: ${resp.totalPhrases}`);
console.log(` Words: ${resp.totalWords}`);
console.log(` Relay: ${resp.relayUrl || 'disabled'} (${resp.relayStatus})`);
if (resp.pendingPins.length > 0) {
console.log(` Pending PINs: ${resp.pendingPins.join(', ')}`);
console.log(` Run: airmic approve <PIN>`);
}
process.exit(0);
});
conn.on('error', () => {
console.log('AirMic is not running (stale socket)');
process.exit(1);
});
}
function approvePin(pin) {
if (!fs.existsSync(IPC_PATH)) {
console.log('AirMic is not running');
process.exit(1);
}
const conn = net.createConnection(IPC_PATH);
conn.on('connect', () => {
conn.write(JSON.stringify({ cmd: 'approve', pin }) + '\n');
});
let buf = '';
conn.on('data', (data) => {
buf += data.toString();
if (!buf.includes('\n')) return;
const resp = JSON.parse(buf.split('\n')[0]);
conn.destroy();
console.log(resp.ok ? resp.message : `Failed: ${resp.message || resp.error}`);
process.exit(resp.ok ? 0 : 1);
});
conn.on('error', () => {
console.log('AirMic is not running');
process.exit(1);
});
}