File size: 11,333 Bytes
5491da5
 
c6c2114
 
 
 
 
5491da5
 
c6c2114
64206e9
 
 
5491da5
 
c6c2114
5491da5
141552e
5491da5
64206e9
 
 
 
141552e
64206e9
 
 
 
 
 
 
 
 
 
141552e
 
 
 
64206e9
141552e
 
 
 
 
 
 
 
64206e9
141552e
 
 
 
 
 
 
 
 
 
64206e9
 
 
 
141552e
 
 
 
 
 
 
64206e9
141552e
 
64206e9
141552e
64206e9
141552e
64206e9
 
 
141552e
 
64206e9
141552e
 
 
 
 
 
 
5491da5
64206e9
141552e
5491da5
 
64206e9
141552e
64206e9
141552e
 
 
 
5491da5
 
64206e9
141552e
5491da5
 
64206e9
c6c2114
 
 
5491da5
 
c6c2114
 
 
 
 
5491da5
 
 
c6c2114
 
5491da5
 
c6c2114
 
5491da5
 
64206e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5491da5
64206e9
 
 
 
 
 
 
 
 
 
 
 
 
5491da5
64206e9
 
 
 
 
5491da5
 
64206e9
 
 
 
 
 
 
 
c6c2114
64206e9
 
5491da5
c6c2114
64206e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5491da5
 
 
64206e9
 
 
 
 
 
 
 
 
5491da5
 
c6c2114
141552e
5491da5
c6c2114
5491da5
 
64206e9
5491da5
c6c2114
 
 
 
5491da5
 
 
 
c6c2114
64206e9
5491da5
c6c2114
141552e
64206e9
141552e
 
64206e9
 
 
 
 
 
 
 
 
5491da5
 
64206e9
5491da5
c6c2114
5491da5
c6c2114
 
64206e9
 
c6c2114
5491da5
 
64206e9
5491da5
c6c2114
 
 
141552e
5491da5
 
64206e9
 
 
 
 
 
5491da5
64206e9
 
 
 
 
 
 
 
 
 
 
5491da5
 
 
 
141552e
c6c2114
5491da5
c6c2114
64206e9
5491da5
c6c2114
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
'use strict';

const { spawn } = require('child_process');
const http      = require('http');
const fs        = require('fs');
const path      = require('path');
const CDP       = require('chrome-remote-interface');
const WebSocket = require('ws');

const PORT         = parseInt(process.env.PORT         || '7860');
const FPS          = parseInt(process.env.FPS          || '25');
// Single-user optimized: lower quality = lower latency
const JPEG_QUALITY = parseInt(process.env.JPEG_QUALITY || '40');
const VIEWPORT     = { width: 1280, height: 720 };
const FRAME_MS     = Math.floor(1000 / FPS);
const CHROME_BIN   = process.env.CHROME_BIN || '/usr/bin/chromium';

const sleep = ms => new Promise(r => setTimeout(r, ms));

// ── State ─────────────────────────────────────────────────────────────────────
let cdpClient   = null;
let chromeProc  = null;
let chromeReady = false;

// Single session for single user
let session     = null;

// Screenshot loop state
let loopTimer   = null;
let capturing   = false;
let pendingInput = false;    // flag: user just interacted β†’ capture ASAP
let lastFrameTs  = 0;

// ── Chrome Launch ─────────────────────────────────────────────────────────────
function launchChrome() {
  chromeReady = false;
  cdpClient   = null;

  console.log('Starting Chrome...');
  chromeProc = spawn(CHROME_BIN, [
    '--remote-debugging-port=9222',
    '--no-sandbox',
    '--disable-setuid-sandbox',
    '--disable-dev-shm-usage',
    '--disable-gpu',
    '--headless=new',
    '--no-first-run',
    '--no-zygote',
    '--disable-extensions',
    '--disable-background-networking',
    '--disable-sync',
    '--disable-translate',
    '--disable-default-apps',
    '--disable-features=TranslateUI,BlinkGenPropertyTrees,VizDisplayCompositor',
    '--mute-audio',
    '--hide-scrollbars',
    '--metrics-recording-only',
    '--use-mock-keychain',
    // Performance: disable unnecessary rendering
    '--disable-background-timer-throttling',
    '--disable-renderer-backgrounding',
    '--disable-backgrounding-occluded-windows',
    `--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
  ], { stdio: ['ignore', 'pipe', 'pipe'] });

  chromeProc.stdout.on('data', d => process.stdout.write(d));
  chromeProc.stderr.on('data', d => process.stderr.write(d));

  chromeProc.on('exit', async (code) => {
    console.error(`Chrome exited (code=${code}). Restarting...`);
    chromeReady = false;
    cdpClient   = null;
    stopLoop();

    if (session) {
      try {
        if (session.ws.readyState === WebSocket.OPEN) {
          session.ws.send(JSON.stringify({ type: 'error', message: 'Browser restarted – please reload.' }));
          session.ws.close();
        }
      } catch {}
      session = null;
    }

    await sleep(2000);
    launchChrome();
    await connectBrowser();
  });
}

// ── CDP Connection ────────────────────────────────────────────────────────────
async function connectBrowser(retries = 25) {
  for (let i = 0; i < retries; i++) {
    try {
      cdpClient   = await CDP({ port: 9222 });
      chromeReady = true;
      console.log('CDP connected');
      return true;
    } catch {
      process.stdout.write('.');
      await sleep(500);
    }
  }
  console.error('CDP connection failed');
  return false;
}

// ── Tab Creation ──────────────────────────────────────────────────────────────
async function createTab(url = 'https://duckduckgo.com') {
  const { targetId } = await cdpClient.Target.createTarget({ url: 'about:blank' });
  const tab = await CDP({ port: 9222, target: targetId });

  await Promise.all([
    tab.Network.enable(),
    tab.Page.enable(),
    tab.Emulation.setDeviceMetricsOverride({
      width: VIEWPORT.width, height: VIEWPORT.height,
      deviceScaleFactor: 1, mobile: false,
    }),
  ]);

  await tab.Page.addScriptToEvaluateOnNewDocument({ source:
    'window.open=()=>null;window.alert=()=>null;window.confirm=()=>false;window.prompt=()=>null;'
  });

  await tab.Page.navigate({ url });
  return { targetId, tab };
}

// ── Screenshot Loop ───────────────────────────────────────────────────────────
// Key optimization: after user input β†’ capture immediately (don't wait for next tick)
// Otherwise use steady FPS timer so we don't saturate the event loop

function stopLoop() {
  if (loopTimer) { clearTimeout(loopTimer); loopTimer = null; }
  capturing = false;
}

async function captureNow() {
  if (!session || capturing) return;
  const s = session;
  if (s.ws.readyState !== WebSocket.OPEN) return;

  capturing = true;
  try {
    const { data } = await s.tab.Page.captureScreenshot({
      format: 'jpeg',
      quality: JPEG_QUALITY,
      clip: { x: 0, y: 0, width: VIEWPORT.width, height: VIEWPORT.height, scale: 1 },
    });
    if (s.ws.readyState === WebSocket.OPEN) {
      const buf = Buffer.concat([Buffer.from([0x01]), Buffer.from(data, 'base64')]);
      s.ws.send(buf);
      lastFrameTs = Date.now();
    }
  } catch {
    // silent
  } finally {
    capturing = false;
  }
}

function scheduleNext() {
  if (!session) return;
  const elapsed = Date.now() - lastFrameTs;
  const delay   = Math.max(0, FRAME_MS - elapsed);
  loopTimer = setTimeout(tick, delay);
}

async function tick() {
  loopTimer = null;
  if (!session) return;
  await captureNow();
  scheduleNext();
}

function startLoop() {
  stopLoop();
  lastFrameTs = 0;
  scheduleNext();
}

// ── Input Handler ─────────────────────────────────────────────────────────────
// After every click/key: immediately queue a fast screenshot
async function handleInput(s, m) {
  const needsFastCapture = ['mousedown','mouseup','keydown','char','navigate','back','forward','reload','scroll'].includes(m.type);

  try {
    const I = s.tab.Input, P = s.tab.Page;

    switch (m.type) {
      case 'mousemove': await I.dispatchMouseEvent({ type: 'mouseMoved',   x: m.x, y: m.y }); break;
      case 'mousedown': await I.dispatchMouseEvent({ type: 'mousePressed',  x: m.x, y: m.y, button: 'left', clickCount: 1 }); break;
      case 'mouseup':   await I.dispatchMouseEvent({ type: 'mouseReleased', x: m.x, y: m.y, button: 'left', clickCount: 1 }); break;
      case 'scroll':    await I.dispatchMouseEvent({ type: 'mouseWheel',    x: m.x, y: m.y, deltaX: 0, deltaY: m.dy }); break;
      case 'keydown':   await I.dispatchKeyEvent({ type: 'keyDown', key: m.key, code: m.code, windowsVirtualKeyCode: m.keyCode || 0 }); break;
      case 'keyup':     await I.dispatchKeyEvent({ type: 'keyUp',   key: m.key, code: m.code, windowsVirtualKeyCode: m.keyCode || 0 }); break;
      case 'char':      await I.dispatchKeyEvent({ type: 'char', text: m.text }); break;
      case 'navigate': {
        let url = m.url.trim();
        if (!/^https?:\/\//i.test(url)) url = 'https://duckduckgo.com/?q=' + encodeURIComponent(url);
        await P.navigate({ url });
        break;
      }
      case 'back':    await P.goBack().catch(() => {}); break;
      case 'forward': await P.goForward().catch(() => {}); break;
      case 'reload':  await P.reload(); break;
    }
  } catch {}

  // After any meaningful interaction β†’ immediately capture (skip waiting for the timer)
  if (needsFastCapture) {
    // Small delay so Chrome can render the interaction result
    setTimeout(async () => {
      if (loopTimer) { clearTimeout(loopTimer); loopTimer = null; }
      await captureNow();
      scheduleNext();
    }, 60); // 60ms: Chrome needs ~1-2 paint cycles to reflect click state
  }
}

// ── HTTP ──────────────────────────────────────────────────────────────────────
const MIME = { '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css' };

const server = http.createServer((req, res) => {
  if (req.url === '/status') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(JSON.stringify({ active: !!session, ready: chromeReady }));
  }
  const file = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);
  fs.readFile(file, (err, data) => {
    if (err) { res.writeHead(404); return res.end('Not found'); }
    res.writeHead(200, { 'Content-Type': MIME[path.extname(file)] || 'text/plain' });
    res.end(data);
  });
});

// ── WebSocket ─────────────────────────────────────────────────────────────────
const wss = new WebSocket.Server({ server, perMessageDeflate: false }); // no deflate = lower latency

wss.on('connection', async (ws) => {
  if (!chromeReady) {
    ws.send(JSON.stringify({ type: 'error', message: 'Browser starting – please wait 10s and reload.' }));
    return ws.close();
  }

  // Single user: close any existing session
  if (session) {
    console.log('Replacing existing session');
    try { session.ws.close(); } catch {}
    stopLoop();
    try { await cdpClient.Target.closeTarget({ targetId: session.targetId }); } catch {}
    session = null;
    await sleep(200);
  }

  console.log('New session');

  let tabData;
  try {
    tabData = await createTab();
  } catch (e) {
    console.error('Tab error:', e.message);
    ws.send(JSON.stringify({ type: 'error', message: 'Could not start tab.' }));
    return ws.close();
  }

  session = { targetId: tabData.targetId, tab: tabData.tab, ws };

  tabData.tab.Page.on('frameNavigated', ({ frame }) => {
    if (frame.parentId) return;
    if (ws.readyState === WebSocket.OPEN)
      ws.send(JSON.stringify({ type: 'url', url: frame.url }));
  });

  startLoop();
  ws.send(JSON.stringify({ type: 'ready' }));

  ws.on('message', raw => {
    try { handleInput(session, JSON.parse(raw)); } catch {}
  });

  const cleanup = async () => {
    if (session && session.ws === ws) {
      console.log('Session closed');
      stopLoop();
      try { await cdpClient.Target.closeTarget({ targetId: session.targetId }); } catch {}
      session = null;
    }
  };

  ws.on('close', cleanup);
  ws.on('error', () => { try { ws.close(); } catch {} });
});

// ── Start ─────────────────────────────────────────────────────────────────────
(async () => {
  launchChrome();
  await sleep(2500);
  await connectBrowser();
  server.listen(PORT, () => {
    console.log(`Running on :${PORT}  fps=${FPS}  quality=${JPEG_QUALITY}`);
  });
})();