Arbitrage01 commited on
Commit
177b13f
Β·
verified Β·
1 Parent(s): cc7d457

Upload 5 files

Browse files
Files changed (5) hide show
  1. .gitignore +29 -0
  2. Dockerfile +24 -0
  3. decimal-bot.html +0 -0
  4. package.json +17 -0
  5. proxy.js +984 -0
.gitignore ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Node modules
2
+ node_modules/
3
+
4
+ # Browser profile and session data
5
+ rebel777-profile/
6
+ rebel777-session.json
7
+
8
+ # Environment variables
9
+ .env
10
+ .env.local
11
+ .env.development.local
12
+ .env.test.local
13
+ .env.production.local
14
+
15
+ # Debug logs
16
+ npm-debug.log*
17
+ yarn-debug.log*
18
+ yarn-error.log*
19
+ pnpm-debug.log*
20
+
21
+ # OS metadata
22
+ .DS_Store
23
+ Thumbs.db
24
+
25
+ # Playwright
26
+ /test-results/
27
+ /playwright-report/
28
+ /blob-report/
29
+ /playwright/.cache/
Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use the official Playwright image which comes with all system dependencies and browsers
2
+ FROM mcr.microsoft.com/playwright:v1.43.0-jammy
3
+
4
+ # Create and change to the app directory
5
+ WORKDIR /usr/src/app
6
+
7
+ # Copy package.json and package-lock.json
8
+ COPY package*.json ./
9
+
10
+ # Install dependencies
11
+ RUN npm install
12
+
13
+ # Copy the rest of the application code
14
+ COPY . .
15
+
16
+ # Expose the port the app runs on
17
+ EXPOSE 3000
18
+
19
+ # Set environment variables
20
+ ENV NODE_ENV=production
21
+ ENV PORT=3000
22
+
23
+ # Start the application
24
+ CMD [ "node", "proxy.js" ]
decimal-bot.html ADDED
The diff for this file is too large to render. See raw diff
 
package.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "ipl-arb-proxy",
3
+ "version": "1.0.0",
4
+ "main": "proxy.js",
5
+ "engines": {
6
+ "node": ">=18.0.0"
7
+ },
8
+ "scripts": {
9
+ "start": "node proxy.js",
10
+ "dev": "nodemon proxy.js",
11
+ "postinstall": "npx playwright install chromium --with-deps"
12
+ },
13
+ "dependencies": {
14
+ "playwright": "^1.59.0",
15
+ "ws": "^8.20.0"
16
+ }
17
+ }
proxy.js ADDED
@@ -0,0 +1,984 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ── IPL ARB PROXY SERVER v4 ──
2
+ // Fixes: session persistence so rebel777 login survives across runs.
3
+ //
4
+ // FIRST TIME SETUP:
5
+ // 1. node proxy.js
6
+ // 2. Open http://localhost:3000/login ← opens a VISIBLE browser window
7
+ // 3. Log into rebel777 manually in that window
8
+ // 4. Click "Done" or visit http://localhost:3000/save-session
9
+ // 5. Session saved to rebel777-session.json β€” all future runs reuse it
10
+ //
11
+ // NORMAL USAGE (after first login):
12
+ // node proxy.js β†’ open http://localhost:3000
13
+
14
+ const http = require('http');
15
+ const https = require('https');
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+
19
+ const PORT = process.env.PORT || 3000;
20
+ const HEADLESS = process.env.HEADLESS !== 'false'; // Default to true on server
21
+ let SCRAPE_INTERVAL = 500;
22
+ const RENDER_WAIT_MS = 20000;
23
+ const SESSION_FILE = path.join(__dirname, 'rebel777-session.json');
24
+ const USER_DATA_DIR = path.join(__dirname, 'rebel777-profile');
25
+ const LOGIN_ORIGIN = 'https://rebel777.co';
26
+
27
+ // ─────────────────────────────────────────────────────────
28
+ // DEPENDENCIES
29
+ // ─────────────────────────────────────────────────────────
30
+ let WebSocketServer;
31
+ try { WebSocketServer = require('ws').Server; }
32
+ catch { console.error('[FATAL] Run: npm install ws'); process.exit(1); }
33
+
34
+ let playwright;
35
+ try { playwright = require('playwright'); }
36
+ catch { console.error('[FATAL] Run: npm install playwright && npx playwright install chromium'); process.exit(1); }
37
+
38
+ // ─────────────────────────────────────────────────────────
39
+ // STATE
40
+ // ─────────────────────────────────────────────────────────
41
+ let browser = null; // headless persistent browser context
42
+ let loginBrowser = null; // visible persistent browser context (temporary)
43
+ let loginPage = null;
44
+ let page = null;
45
+ let currentUrl = '';
46
+ let lastOdds = null;
47
+ let scrapeTimer = null;
48
+ let isScraping = false;
49
+ let wsClients = new Set();
50
+
51
+ // ─────────────────────────────────────────────────────────
52
+ // UTILS
53
+ // ─────────────────────────────────────────────────────────
54
+ function broadcast(data) {
55
+ const msg = JSON.stringify(data);
56
+ wsClients.forEach(ws => { try { if (ws.readyState === 1) ws.send(msg); } catch { } });
57
+ }
58
+ function log(tag, msg) {
59
+ console.log(`[${tag}] ${new Date().toLocaleTimeString()} β€” ${msg}`);
60
+ }
61
+ function hasSession() {
62
+ return fs.existsSync(SESSION_FILE);
63
+ }
64
+
65
+ // ─────────────────────────────────────────────────────────
66
+ // SESSION: save & load
67
+ // ─────────────────────────────────────────────────────────
68
+ async function saveSession(ctx) {
69
+ const storage = await ctx.storageState();
70
+ fs.writeFileSync(SESSION_FILE, JSON.stringify(storage, null, 2));
71
+ log('SESSION', `Saved to ${SESSION_FILE}`);
72
+ }
73
+
74
+ function loadSessionOptions() {
75
+ if (!hasSession()) return {};
76
+ try {
77
+ return { storageState: JSON.parse(fs.readFileSync(SESSION_FILE, 'utf8')) };
78
+ } catch {
79
+ return {};
80
+ }
81
+ }
82
+
83
+ // ─────────────────────────────────────────────────────────
84
+ // LOGIN FLOW β€” opens a visible browser window
85
+ // ─────────────────────────────────────────────────────────
86
+ async function startLogin(res) {
87
+ // Send response immediately so the user sees the instructions
88
+ if (res) {
89
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
90
+ res.end(`
91
+ <html><body style="font-family:monospace;background:#07090f;color:#b8cae8;padding:30px">
92
+ <h2 style="color:#00d47e">βœ“ Login request received</h2>
93
+ <p>A Chromium window is opening. Log into rebel777 in that window.</p>
94
+ <p>When you are fully logged in and can see the odds, click below:</p>
95
+ <br>
96
+ <a href="/save-session" style="background:#6c63ff;color:#fff;padding:12px 24px;border-radius:4px;text-decoration:none;font-size:14px">
97
+ βœ“ I'm logged in β€” Save Session
98
+ </a>
99
+ <br><br>
100
+ <p style="color:#4a5a72;font-size:12px">Session will be saved to rebel777-session.json and reused automatically.</p>
101
+ <script>
102
+ // Auto-refresh logic or status check could go here
103
+ </script>
104
+ </body></html>
105
+ `);
106
+ }
107
+
108
+ // Close any existing login browser
109
+ if (loginBrowser) {
110
+ log('LOGIN', 'Closing previous login browser...');
111
+ await loginBrowser.close().catch(() => { });
112
+ loginBrowser = null;
113
+ loginPage = null;
114
+ }
115
+ if (browser) {
116
+ log('LOGIN', 'Closing active scrape browser to allow login...');
117
+ await browser.close().catch(() => { });
118
+ browser = null;
119
+ page = null;
120
+ }
121
+
122
+ try {
123
+ log('LOGIN', 'Opening visible browser for manual login...');
124
+ loginBrowser = await playwright.chromium.launchPersistentContext(USER_DATA_DIR, {
125
+ headless: process.env.LOGIN_HEADLESS === 'true', // Usually false for login, but can be true for automated login
126
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
127
+ viewport: { width: 1280, height: 800 },
128
+ locale: 'en-IN',
129
+ timezoneId: 'Asia/Kolkata',
130
+ args: [
131
+ '--no-sandbox',
132
+ '--disable-setuid-sandbox',
133
+ '--disable-blink-features=AutomationControlled',
134
+ ],
135
+ ignoreDefaultArgs: ['--enable-automation'],
136
+ });
137
+
138
+ await loginBrowser.addInitScript(() => {
139
+ Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
140
+ });
141
+
142
+ loginPage = loginBrowser.pages()[0] || await loginBrowser.newPage();
143
+
144
+ log('LOGIN', `Navigating to ${LOGIN_ORIGIN}...`);
145
+ await loginPage.goto(LOGIN_ORIGIN, { waitUntil: 'domcontentloaded', timeout: 30000 }).catch(e => {
146
+ log('LOGIN-ERR', `Navigation aborted or failed: ${e.message}`);
147
+ });
148
+
149
+ log('LOGIN', 'Browser ready for manual login');
150
+ } catch (e) {
151
+ log('LOGIN-ERR', `Failed to launch login browser: ${e.message}`);
152
+ }
153
+ }
154
+
155
+ async function saveSessionAndClose(res) {
156
+ if (!loginBrowser || !loginPage) {
157
+ if (res) {
158
+ res.writeHead(400, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
159
+ res.end(`
160
+ <html><body style="font-family:monospace;background:#07090f;color:#b8cae8;padding:30px">
161
+ <h2 style="color:#ff3a5e">βœ— No login browser open</h2>
162
+ <p>Visit <a href="/login" style="color:var(--p)">/login</a> first to open a window.</p>
163
+ </body></html>
164
+ `);
165
+ }
166
+ return;
167
+ }
168
+
169
+ try {
170
+ const ctx = loginPage.context();
171
+ if (!ctx) throw new Error('Browser context lost');
172
+
173
+ await saveSession(ctx);
174
+ log('SESSION', 'Session saved successfully βœ“');
175
+
176
+ if (res) {
177
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
178
+ res.end(`
179
+ <html><body style="font-family:monospace;background:#07090f;color:#b8cae8;padding:30px">
180
+ <h2 style="color:#00d47e">βœ“ Session Saved!</h2>
181
+ <p>rebel777-session.json written. You can close this tab.</p>
182
+ <p>Now go to your tool and click <b style="color:#ffd44a">START</b> β€” it will use your saved login.</p>
183
+ <br>
184
+ <p style="color:#4a5a72;font-size:12px">You won't need to log in again unless your session expires.</p>
185
+ </body></html>
186
+ `);
187
+ }
188
+
189
+ // Clean up but keep references if needed for immediate transition
190
+ browser = loginBrowser;
191
+ page = loginPage;
192
+ loginBrowser = null;
193
+ loginPage = null;
194
+ log('LOGIN', 'Login browser promoted to active scrape browser');
195
+
196
+ } catch (e) {
197
+ log('SESSION-ERR', e.message);
198
+ if (res) {
199
+ res.writeHead(500, { 'Content-Type': 'text/html', 'Access-Control-Allow-Origin': '*' });
200
+ res.end(`
201
+ <html><body style="font-family:monospace;background:#07090f;color:#b8cae8;padding:30px">
202
+ <h2 style="color:#ff3a5e">βœ— Session Error</h2>
203
+ <p>${e.message}</p>
204
+ <p>Try opening <a href="/login" style="color:var(--p)">/login</a> again.</p>
205
+ </body></html>
206
+ `);
207
+ }
208
+ }
209
+ }
210
+
211
+ // ─────────────────────────────────────────────────────────
212
+ // CORE SCRAPER β€” tuned to rebel777 DOM
213
+ // ─────────────────────────────────────────────────────────
214
+ async function scrapeOdds(pg) {
215
+ return await pg.evaluate(() => {
216
+
217
+ function parseCell(div) {
218
+ const span = div.querySelector('[class="d-block odds"], [class*="d-block"][class*="odds"], span.odds');
219
+ if (!span) return null;
220
+ const odds = parseFloat(span.innerText.trim());
221
+ if (isNaN(odds) || odds <= 1 || odds > 1000) return null;
222
+ const lines = div.innerText.trim().split(/\s*\n\s*/);
223
+ const size = lines.length > 1 ? parseFloat(lines[lines.length - 1].replace(/[^0-9.]/g, '')) || 0 : 0;
224
+ return { odds, size };
225
+ }
226
+
227
+ const results = [];
228
+
229
+ // Strategy 1: runner rows with bl-box cells
230
+ const runnerRows = document.querySelectorAll(
231
+ '[class*="runner-row"], [class*="brow"], [class*="market-runner"], [class*="runnerRow"]'
232
+ );
233
+ runnerRows.forEach(row => {
234
+ const cells = row.querySelectorAll('[class*="bl-box"]');
235
+ if (!cells.length) return;
236
+ const nameEl = row.querySelector(
237
+ '[class*="runner-name"], [class*="runnerName"], [class*="team-name"], [class*="teamName"], .btn, b, strong'
238
+ );
239
+ const name = nameEl?.innerText.trim().slice(0, 60);
240
+ if (!name || name.length < 2) return;
241
+ const back = [], lay = [];
242
+ cells.forEach(cell => {
243
+ const cls = cell.className || '';
244
+ const c = parseCell(cell);
245
+ if (!c) return;
246
+ if (cls.includes('lay')) lay.push(c);
247
+ else if (cls.includes('back')) back.push(c);
248
+ });
249
+ if (back.length || lay.length)
250
+ results.push({ name, back: back.slice(0, 3), lay: lay.slice(0, 3) });
251
+ });
252
+ if (results.length >= 2) return results.slice(0, 2);
253
+
254
+ // Strategy 2: global bl-box scan grouped by team name
255
+ const allCells = Array.from(document.querySelectorAll('[class*="bl-box"]'));
256
+ if (!allCells.length) return [];
257
+ const nameEls = Array.from(document.querySelectorAll(
258
+ '[class*="team"], [class*="runner"], [class*="selection"], [class*="player"]'
259
+ )).map(el => el.innerText.trim()).filter(t => t.length > 2 && t.length < 60 && !/^\d/.test(t));
260
+ const teams = [...new Set(nameEls)].slice(0, 6);
261
+ for (let i = 0; i < (teams.length || 2); i++) {
262
+ const chunk = allCells.slice(i * 6, i * 6 + 6);
263
+ if (!chunk.length) break;
264
+ const back = [], lay = [];
265
+ chunk.forEach(cell => {
266
+ const cls = cell.className || '';
267
+ const c = parseCell(cell);
268
+ if (!c) return;
269
+ if (cls.includes('lay')) lay.push(c);
270
+ else if (cls.includes('back')) back.push(c);
271
+ else if (back.length < 3) back.push(c);
272
+ else lay.push(c);
273
+ });
274
+ if (back.length || lay.length)
275
+ results.push({ name: teams[i] || `Runner ${i + 1}`, back: back.slice(0, 3), lay: lay.slice(0, 3) });
276
+ }
277
+ if (results.length >= 2) return results.slice(0, 2);
278
+
279
+ // Strategy 3: bare odds spans
280
+ const oddsSpans = Array.from(document.querySelectorAll('[class="d-block odds"], [class*="d-block"][class*="odds"]'));
281
+ if (!oddsSpans.length) return [];
282
+ const fallbackNames = Array.from(document.querySelectorAll('h4,h5,h6,[class*="title"]'))
283
+ .map(el => el.innerText.trim()).filter(t => t.length > 2 && !/^\d/.test(t)).slice(0, 4);
284
+ const perRunner = Math.floor(oddsSpans.length / Math.max(fallbackNames.length, 2));
285
+ for (let i = 0; i < Math.max(fallbackNames.length, 2); i++) {
286
+ const chunk = oddsSpans.slice(i * perRunner, (i + 1) * perRunner);
287
+ const parsed = chunk.map(sp => {
288
+ const odds = parseFloat(sp.innerText.trim());
289
+ const lines = sp.parentElement?.innerText?.trim().split(/\n/) || [];
290
+ const size = lines.length > 1 ? parseFloat(lines[lines.length - 1].replace(/[^0-9.]/g, '')) || 0 : 0;
291
+ return { odds, size };
292
+ }).filter(o => o.odds > 1 && o.odds < 1000);
293
+ const mid = Math.floor(parsed.length / 2);
294
+ if (parsed.slice(0, mid).length)
295
+ results.push({ name: fallbackNames[i] || `Runner ${i + 1}`, back: parsed.slice(0, mid), lay: parsed.slice(mid) });
296
+ }
297
+ return results.slice(0, 2);
298
+ });
299
+ }
300
+
301
+ // ─────────────────────────────────────────────────────────
302
+ // WS FRAME PARSERS β€” Sprint platform formats
303
+ // ─────────────────────────────────────────────────────────
304
+
305
+ // Ladder format: rc = [ { id, batb: [[price,size],...], batl: [[price,size],...] } ]
306
+ // Runner names come from MarketDefinition β€” we cache them
307
+ let _runnerNames = {};
308
+ function parseLadder(rc) {
309
+ if (!rc || rc.length < 2) return null;
310
+ const runners = rc.slice(0, 2).map((r, i) => {
311
+ const name = _runnerNames[r.id] || _runnerNames[String(r.id)] || `Runner ${i + 1}`;
312
+ const back = (r.batb || []).slice(0, 3).map(([odds, size]) => ({ odds, size }));
313
+ const lay = (r.batl || []).slice(0, 3).map(([odds, size]) => ({ odds, size }));
314
+ if (!back.length && !lay.length) return null;
315
+ return { name, back, lay };
316
+ }).filter(Boolean);
317
+ return runners.length >= 2 ? runners : null;
318
+ }
319
+
320
+ // Runners array format: [ { runnerName, ex: { availableToBack, availableToLay } } ]
321
+ function parseRunners(arr) {
322
+ if (!Array.isArray(arr) || arr.length < 2) return null;
323
+ const runners = arr.slice(0, 2).map(r => {
324
+ const name = r.runnerName || r.name || r.teamName || r.selectionName || 'Runner';
325
+ // Cache name→id for ladder parser
326
+ if (r.selectionId) _runnerNames[r.selectionId] = name;
327
+ const back = (r.ex?.availableToBack || r.back || r.availableToBack || []).slice(0, 3)
328
+ .map(x => ({ odds: x.price ?? x.odds, size: x.size }));
329
+ const lay = (r.ex?.availableToLay || r.lay || r.availableToLay || []).slice(0, 3)
330
+ .map(x => ({ odds: x.price ?? x.odds, size: x.size }));
331
+ return { name, back, lay };
332
+ });
333
+ return runners;
334
+ }
335
+
336
+ // ─────────────────────────────────────────────────────────
337
+ // POLL LOOP
338
+ // ─────────────────────────────────────────────────────────
339
+ async function doPoll() {
340
+ if (!page || isScraping) return;
341
+ isScraping = true;
342
+ try {
343
+ const runners = await scrapeOdds(page);
344
+
345
+ if (!runners || runners.length < 2) {
346
+ const snap = await page.evaluate(() => {
347
+ const boxes = document.querySelectorAll('[class*="bl-box"]');
348
+ const spans = document.querySelectorAll('[class="d-block odds"]');
349
+ return {
350
+ blBoxCount: boxes.length,
351
+ oddsSpanCount: spans.length,
352
+ firstBoxHtml: boxes[0]?.outerHTML?.slice(0, 300) || 'none',
353
+ pageTitle: document.title,
354
+ url: location.href,
355
+ bodyClass: document.body?.className || '',
356
+ hasLoginFlag: localStorage.getItem('isLoggedin'),
357
+ hasUserDetails: !!localStorage.getItem('userDetails'),
358
+ // FIX: only treat as login page if a visible password field exists
359
+ // AND there are no odds elements β€” avoids nuking session on nav links
360
+ isLoginPage: !!document.querySelector('input[type="password"]:not([style*="display: none"])')
361
+ && !document.querySelector('[class*="odds"], [class*="bl-box"]'),
362
+ };
363
+ });
364
+ log('POLL', `No odds β€” bl-boxes:${snap.blBoxCount} spans:${snap.oddsSpanCount} title:"${snap.pageTitle}" loginPage:${snap.isLoginPage}`);
365
+
366
+ // FIX: dump page HTML so you can open debug-page.html and see exactly what headless got
367
+ if (snap.blBoxCount === 0 && snap.oddsSpanCount === 0) {
368
+ try {
369
+ const html = await page.content();
370
+ fs.writeFileSync(path.join(__dirname, 'debug-page.html'), html);
371
+ log('DEBUG', 'Dumped β†’ debug-page.html (open in browser to see what headless got)');
372
+ } catch { }
373
+ }
374
+
375
+ if (snap.isLoginPage) {
376
+ broadcast({ type: 'error', msg: '⚠️ Session expired β€” visit http://localhost:3000/login to re-authenticate' });
377
+ // Clear saved session so next start triggers fresh login
378
+ if (hasSession()) { fs.unlinkSync(SESSION_FILE); log('SESSION', 'Expired session deleted'); }
379
+ } else {
380
+ broadcast({ type: 'debug', data: snap });
381
+ }
382
+ isScraping = false;
383
+ return;
384
+ }
385
+
386
+ const changed = JSON.stringify(runners) !== JSON.stringify(lastOdds);
387
+ if (changed) {
388
+ lastOdds = runners;
389
+ broadcast({ type: 'odds', data: { runners, _source: 'rebel777', _ts: Date.now() } });
390
+ log('POLL', `βœ“ ${runners.map(r => r.name).join(' vs ')} β†’ ${wsClients.size} client(s)`);
391
+ } else {
392
+ broadcast({ type: 'ping', ts: Date.now() });
393
+ }
394
+ } catch (e) {
395
+ log('POLL-ERR', e.message);
396
+ broadcast({ type: 'error', msg: e.message });
397
+ }
398
+ isScraping = false;
399
+ }
400
+
401
+ // ─────────────────────────────────────────────────────────
402
+ // START SCRAPING BROWSER (headless, with saved session)
403
+ // ────────────────────────────────────────��────────────────
404
+ async function startBrowser(targetUrl) {
405
+ // Check session first
406
+ if (!hasSession()) {
407
+ broadcast({ type: 'error', msg: '⚠️ No session found. Visit http://localhost:3000/login to log in first.' });
408
+ log('SESSION', 'No rebel777-session.json β€” login required');
409
+ return;
410
+ }
411
+
412
+ if (scrapeTimer) { clearInterval(scrapeTimer); scrapeTimer = null; }
413
+ if (loginBrowser && !browser) {
414
+ browser = loginBrowser;
415
+ loginBrowser = null;
416
+ page = page || loginPage;
417
+ loginPage = null;
418
+ log('LOGIN', 'Reusing live login browser for scraping');
419
+ }
420
+ if (currentUrl !== targetUrl && page) {
421
+ try {
422
+ if (page.url() && page.url() !== 'about:blank') {
423
+ await page.goto(LOGIN_ORIGIN, { waitUntil: 'load', timeout: 30000 }).catch(() => { });
424
+ }
425
+ } catch { }
426
+ page = null;
427
+ }
428
+ currentUrl = targetUrl;
429
+
430
+ if (!browser) {
431
+ log('BROWSER', `Launching ${HEADLESS ? 'headless' : 'visible'} Chromium...`);
432
+ browser = await playwright.chromium.launchPersistentContext(USER_DATA_DIR, {
433
+ headless: HEADLESS,
434
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
435
+ viewport: { width: 1366, height: 768 },
436
+ locale: 'en-IN',
437
+ timezoneId: 'Asia/Kolkata',
438
+ extraHTTPHeaders: {
439
+ 'Accept-Language': 'en-IN,en;q=0.9',
440
+ 'sec-ch-ua': '"Chromium";v="124", "Google Chrome";v="124"',
441
+ 'sec-ch-ua-mobile': '?0',
442
+ 'sec-ch-ua-platform': '"Windows"',
443
+ },
444
+ args: [
445
+ '--disable-blink-features=AutomationControlled',
446
+ '--no-sandbox',
447
+ '--disable-setuid-sandbox',
448
+ '--disable-dev-shm-usage',
449
+ '--disable-web-security',
450
+ ],
451
+ ignoreDefaultArgs: ['--enable-automation'],
452
+ });
453
+ browser.on('disconnected', () => {
454
+ log('BROWSER', 'Crashed β€” will relaunch on next call');
455
+ browser = null; page = null;
456
+ });
457
+ }
458
+
459
+ if (!page) {
460
+ log('BROWSER', `Opening: ${targetUrl}`);
461
+ broadcast({ type: 'status', msg: 'Opening rebel777 with saved session...', state: 'loading' });
462
+
463
+ if (hasSession()) {
464
+ try {
465
+ const storage = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf8'));
466
+ if (Array.isArray(storage.cookies) && storage.cookies.length) {
467
+ await browser.addCookies(storage.cookies);
468
+ }
469
+ } catch { }
470
+ }
471
+
472
+ page = browser.pages()[0] || await browser.newPage();
473
+
474
+ // FIX: anti-detection β€” hide webdriver flag from the site
475
+ await page.addInitScript(() => {
476
+ Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
477
+ Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3] });
478
+ window.chrome = { runtime: {} };
479
+ });
480
+
481
+ // ── STRATEGY 1: Intercept rebel777's own WebSocket feed directly ──
482
+ // Sprint platform pushes odds as JSON frames β€” parse them here instead of
483
+ // scraping the DOM (which the fingerprint challenge blocks in headless).
484
+ page.on('websocket', ws => {
485
+ log('WS-INTERCEPT', `Opened: ${ws.url().slice(0, 100)}`);
486
+
487
+ ws.on('framereceived', event => {
488
+ try {
489
+ const raw = event.payload;
490
+ if (!raw || typeof raw !== 'string') return;
491
+
492
+ // Sprint/Betfair WS frames: try to find runners/odds arrays
493
+ const data = JSON.parse(raw);
494
+
495
+ // Cache runner names from MarketDefinition frames
496
+ if (data.MarketDefinition?.runners) {
497
+ data.MarketDefinition.runners.forEach(r => {
498
+ if (r.id && r.name) _runnerNames[r.id] = r.name;
499
+ });
500
+ }
501
+
502
+ // Common Sprint platform shapes:
503
+ // { t: 'ou', d: { mid: ..., runners: [...] } }
504
+ // { MarketDefinition: { runners: [...] } }
505
+ // { rc: [ { id, batb, batl } ] } ← ladder format
506
+ let runners = null;
507
+
508
+ // Shape A: { rc: [...] } ladder β€” batb=back, batl=lay
509
+ if (data.rc && Array.isArray(data.rc)) {
510
+ runners = parseLadder(data.rc);
511
+ }
512
+ // Shape B: nested runners array
513
+ if (!runners && data.d?.runners) runners = parseRunners(data.d.runners);
514
+ if (!runners && data.runners) runners = parseRunners(data.runners);
515
+ // Shape C: { data: { market: { runners: [...] } } }
516
+ if (!runners && data.data?.market?.runners) runners = parseRunners(data.data.market.runners);
517
+ // Shape D: array of market objects
518
+ if (!runners && Array.isArray(data)) {
519
+ for (const item of data) {
520
+ if (item.runners) { runners = parseRunners(item.runners); break; }
521
+ }
522
+ }
523
+
524
+ if (runners && runners.length >= 2) {
525
+ const changed = JSON.stringify(runners) !== JSON.stringify(lastOdds);
526
+ if (changed) {
527
+ lastOdds = runners;
528
+ broadcast({ type: 'odds', data: { runners, _source: 'rebel777-ws', _ts: Date.now() } });
529
+ log('WS-ODDS', `βœ“ ${runners.map(r => r.name).join(' vs ')} β†’ ${wsClients.size} client(s)`);
530
+ }
531
+ }
532
+ } catch { /* non-JSON frames, ignore */ }
533
+ });
534
+
535
+ ws.on('framereceived', () => setTimeout(doPoll, 250)); // DOM fallback still runs
536
+ });
537
+
538
+ // FIX: all page interaction inside one try/catch, waitForSelector no longer orphaned outside
539
+ try {
540
+ // Warm the authenticated SPA first. Rebel777 sometimes drops deep links
541
+ // back to "/" on a fresh context before auth state finishes hydrating.
542
+ await page.goto(LOGIN_ORIGIN, { waitUntil: 'load', timeout: 30000 });
543
+ await page.waitForLoadState('networkidle', { timeout: 15000 })
544
+ .catch(() => log('WAIT', 'Warm-up networkidle timeout β€” continuing anyway'));
545
+
546
+ const warmState = await page.evaluate(() => ({
547
+ url: location.href,
548
+ bodyClass: document.body?.className || '',
549
+ isLoggedin: localStorage.getItem('isLoggedin'),
550
+ hasUserDetails: !!localStorage.getItem('userDetails'),
551
+ hasToken: !!localStorage.getItem('token'),
552
+ hasPasswordInput: !!document.querySelector('input[type="password"]'),
553
+ }));
554
+ log('SESSION', `Warm-up β†’ url:${warmState.url} body:"${warmState.bodyClass}" logged:${warmState.isLoggedin} user:${warmState.hasUserDetails} token:${warmState.hasToken}`);
555
+
556
+ // FIX: 'load' instead of 'domcontentloaded' β€” waits for SPA JS to execute
557
+ await page.evaluate(() => {
558
+ const clickIfVisible = (el) => {
559
+ if (!el) return false;
560
+ const style = window.getComputedStyle(el);
561
+ const rect = el.getBoundingClientRect();
562
+ const visible = style && style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
563
+ if (!visible) return false;
564
+ el.click();
565
+ return true;
566
+ };
567
+ const selectors = [
568
+ '[aria-label="Close"]',
569
+ '[aria-label="close"]',
570
+ '.close',
571
+ '.btn-close',
572
+ '.modal .close',
573
+ '.popup .close',
574
+ '.banner .close',
575
+ '.swal2-close',
576
+ 'button[class*="close"]',
577
+ 'div[class*="close"]',
578
+ 'span[class*="close"]',
579
+ ];
580
+ for (const selector of selectors) {
581
+ const nodes = Array.from(document.querySelectorAll(selector));
582
+ for (const node of nodes) {
583
+ if (clickIfVisible(node)) return;
584
+ }
585
+ }
586
+ const nodes = Array.from(document.querySelectorAll('button, div, span, a'));
587
+ const fallback = nodes.find(el => /^(x|close|skip)$/i.test((el.textContent || '').trim()));
588
+ if (fallback) clickIfVisible(fallback);
589
+ }).catch(() => { });
590
+ await page.waitForTimeout(1500).catch(() => { });
591
+ await page.goto(targetUrl, { waitUntil: 'load', timeout: 30000 });
592
+ await page.waitForLoadState('networkidle', { timeout: 15000 })
593
+ .catch(() => log('WAIT', 'Target networkidle timeout β€” continuing anyway'));
594
+
595
+ await page.evaluate(() => {
596
+ const clickIfVisible = (el) => {
597
+ if (!el) return false;
598
+ const style = window.getComputedStyle(el);
599
+ const rect = el.getBoundingClientRect();
600
+ const visible = style && style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
601
+ if (!visible) return false;
602
+ el.click();
603
+ return true;
604
+ };
605
+ const selectors = [
606
+ '[aria-label="Close"]',
607
+ '[aria-label="close"]',
608
+ '.close',
609
+ '.btn-close',
610
+ '.modal .close',
611
+ '.popup .close',
612
+ '.banner .close',
613
+ '.swal2-close',
614
+ 'button[class*="close"]',
615
+ 'div[class*="close"]',
616
+ 'span[class*="close"]',
617
+ ];
618
+ for (const selector of selectors) {
619
+ const nodes = Array.from(document.querySelectorAll(selector));
620
+ for (const node of nodes) {
621
+ if (clickIfVisible(node)) return;
622
+ }
623
+ }
624
+ const nodes = Array.from(document.querySelectorAll('button, div, span, a'));
625
+ const fallback = nodes.find(el => /^(x|close|skip)$/i.test((el.textContent || '').trim()));
626
+ if (fallback) clickIfVisible(fallback);
627
+ }).catch(() => { });
628
+ await page.waitForTimeout(1500).catch(() => { });
629
+
630
+ const landed = await page.evaluate(() => ({
631
+ url: location.href,
632
+ bodyClass: document.body?.className || '',
633
+ hasOdds: !!document.querySelector('span.odds, [class*="odds"], [class*="bl-box"], [class*="bet-btn"], [class*="back-price"], [class*="lay-price"]'),
634
+ }));
635
+
636
+ if (!landed.hasOdds && (landed.url === LOGIN_ORIGIN || landed.url === `${LOGIN_ORIGIN}/`)) {
637
+ log('NAV', `Deep link bounced to home (${landed.url}) β€” retrying once after SPA warm-up`);
638
+ await page.evaluate((url) => { location.href = url; }, targetUrl);
639
+ await page.waitForLoadState('load', { timeout: 30000 }).catch(() => { });
640
+ }
641
+
642
+ log('BROWSER', `Loaded β€” waiting for odds elements (up to ${RENDER_WAIT_MS / 1000}s)...`);
643
+ broadcast({ type: 'status', msg: 'Page loaded β€” waiting for odds to render...', state: 'loading' });
644
+
645
+ // Wait for network to settle β€” SPA fetches session/markets after load.
646
+ // WS interception above catches odds frames as soon as the site opens its feed.
647
+ if (page) {
648
+ await page.waitForLoadState('networkidle', { timeout: 15000 })
649
+ .catch(() => log('WAIT', 'networkidle timeout β€” continuing anyway'));
650
+ // DOM selector as a bonus β€” works when session is healthy and site renders
651
+ await page.waitForSelector(
652
+ 'span.odds, [class*="odds"], [class*="bl-box"], [class*="bet-btn"], [class*="back-price"], [class*="lay-price"]',
653
+ { timeout: 8000 }
654
+ ).then(() => {
655
+ broadcast({ type: 'status', msg: 'Odds elements detected β€” live!', state: 'ready' });
656
+ }).catch(() => {
657
+ log('WAIT', 'DOM odds selector not found β€” relying on WS interception');
658
+ broadcast({ type: 'status', msg: 'Connected β€” waiting for WS odds feed...', state: 'ready' });
659
+ });
660
+ }
661
+ } catch (e) {
662
+ log('BROWSER-ERR', `Page load failed: ${e.message}`);
663
+ broadcast({ type: 'error', msg: `Page load failed: ${e.message}` });
664
+ // FIX: safely close page before nulling to avoid resource leak
665
+ if (page) { await page.close().catch(() => { }); }
666
+ page = null;
667
+ return;
668
+ }
669
+ }
670
+
671
+ await doPoll();
672
+ scrapeTimer = setInterval(doPoll, SCRAPE_INTERVAL);
673
+ log('POLL', `Running every ${SCRAPE_INTERVAL / 1000}s`);
674
+ }
675
+
676
+ async function stopScraper() {
677
+ if (scrapeTimer) { clearInterval(scrapeTimer); scrapeTimer = null; }
678
+ if (page) { await page.close().catch(() => { }); page = null; }
679
+ lastOdds = null;
680
+ broadcast({ type: 'status', msg: 'Scraper stopped', state: 'idle' });
681
+ log('SCRAPER', 'Stopped');
682
+ }
683
+
684
+ // ─────────────────────────────────────────────────────────
685
+ // CHROMIUM FETCH β€” uses real Chrome TLS fingerprint (bypasses Cloudflare)
686
+ // Spins up a minimal context, does fetch() inside the page, returns JSON
687
+ // ─────────────────────────────────────────────────────────
688
+ const POLY_WORKER = 'https://ravi.ravisainagendra386-rs.workers.dev';
689
+
690
+ function workerFetch(targetUrl, res) {
691
+ const relayUrl = `${POLY_WORKER}?url=${encodeURIComponent(targetUrl)}`;
692
+ const parsed = new URL(relayUrl);
693
+ const req = https.request({
694
+ hostname: parsed.hostname,
695
+ port: 443,
696
+ path: parsed.pathname + parsed.search,
697
+ method: 'GET',
698
+ headers: { 'Accept': 'application/json', 'User-Agent': 'Mozilla/5.0', 'Connection': 'close' },
699
+ timeout: 10000,
700
+ }, apiRes => {
701
+ res.writeHead(apiRes.statusCode || 200, {
702
+ 'Content-Type': 'application/json',
703
+ 'Access-Control-Allow-Origin': '*',
704
+ 'Cache-Control': 'no-cache',
705
+ });
706
+ apiRes.pipe(res);
707
+ apiRes.on('error', () => { try { res.end(); } catch { } });
708
+ });
709
+ req.on('timeout', () => { req.destroy(); try { res.writeHead(504, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); res.end(JSON.stringify({ error: 'Worker timeout' })); } catch { } });
710
+ req.on('error', e => { log('WORKER-ERR', e.message); try { res.writeHead(502, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); res.end(JSON.stringify({ error: e.message })); } catch { } });
711
+ req.end();
712
+ }
713
+
714
+ let chromiumFetchBrowser = null;
715
+
716
+ async function chromiumFetch(targetUrl, res) {
717
+ try {
718
+ // Launch or reuse a separate lightweight browser for API fetches
719
+ if (!chromiumFetchBrowser) {
720
+ chromiumFetchBrowser = await playwright.chromium.launch({
721
+ headless: true,
722
+ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-blink-features=AutomationControlled'],
723
+ ignoreDefaultArgs: ['--enable-automation'],
724
+ });
725
+ chromiumFetchBrowser.on('disconnected', () => { chromiumFetchBrowser = null; });
726
+ }
727
+ const ctx = await chromiumFetchBrowser.newContext({
728
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
729
+ locale: 'en-US',
730
+ });
731
+ const pg = await ctx.newPage();
732
+ // Use page.evaluate to run fetch() inside Chrome β€” real TLS fingerprint
733
+ const result = await pg.evaluate(async (url) => {
734
+ try {
735
+ const r = await fetch(url, {
736
+ headers: {
737
+ 'Accept': 'application/json',
738
+ 'Accept-Language': 'en-US,en;q=0.9',
739
+ }
740
+ });
741
+ const text = await r.text();
742
+ return { ok: r.ok, status: r.status, body: text };
743
+ } catch (e) {
744
+ return { ok: false, status: 0, body: JSON.stringify({ error: e.message }) };
745
+ }
746
+ }, targetUrl);
747
+ await ctx.close();
748
+
749
+ res.writeHead(result.ok ? 200 : result.status, {
750
+ 'Content-Type': 'application/json',
751
+ 'Access-Control-Allow-Origin': '*',
752
+ 'Cache-Control': 'no-cache',
753
+ });
754
+ res.end(result.body);
755
+ log('CHROME-FETCH', `βœ“ ${targetUrl.slice(0, 70)}`);
756
+ } catch (e) {
757
+ log('CHROME-FETCH-ERR', e.message);
758
+ try {
759
+ res.writeHead(502, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
760
+ res.end(JSON.stringify({ error: e.message }));
761
+ } catch { }
762
+ }
763
+ }
764
+
765
+ // ─────────────────────────────────────────────────────────
766
+ // PROXY FETCH (Polymarket / direct JSON APIs)
767
+ // ─────────────────────────────────────────────────────────
768
+ function proxyFetch(targetUrl, res) {
769
+ const parsed = new URL(targetUrl);
770
+ const isHttps = parsed.protocol === 'https:';
771
+ const lib = isHttps ? https : http;
772
+
773
+ const agent = isHttps ? new https.Agent({
774
+ rejectUnauthorized: false,
775
+ keepAlive: false,
776
+ timeout: 15000,
777
+ servername: parsed.hostname, // SNI β€” required by Cloudflare/Polymarket
778
+ }) : null;
779
+
780
+ const options = {
781
+ hostname: parsed.hostname,
782
+ port: parsed.port || (isHttps ? 443 : 80),
783
+ path: parsed.pathname + parsed.search,
784
+ method: 'GET',
785
+ headers: {
786
+ 'Accept': 'application/json',
787
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
788
+ 'Accept-Encoding': 'identity',
789
+ 'Accept-Language': 'en-US,en;q=0.9',
790
+ 'Connection': 'close',
791
+ },
792
+ timeout: 15000,
793
+ ...(agent ? { agent } : {}),
794
+ };
795
+
796
+ const req = lib.request(options, apiRes => {
797
+ res.writeHead(apiRes.statusCode || 200, {
798
+ 'Content-Type': apiRes.headers['content-type'] || 'application/json',
799
+ 'Access-Control-Allow-Origin': '*',
800
+ 'Cache-Control': 'no-cache',
801
+ });
802
+ apiRes.pipe(res);
803
+ apiRes.on('error', () => { try { res.end(); } catch { } });
804
+ });
805
+ req.on('timeout', () => {
806
+ req.destroy();
807
+ try { res.writeHead(504, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); res.end(JSON.stringify({ error: 'Upstream timeout' })); } catch { }
808
+ });
809
+ req.on('error', e => {
810
+ log('PROXY-ERR', `${targetUrl.slice(0, 80)} β€” ${e.message}`);
811
+ try { res.writeHead(502, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); res.end(JSON.stringify({ error: e.message })); } catch { }
812
+ });
813
+ req.end();
814
+ }
815
+
816
+ // ─────────────────────────���───────────────────────────────
817
+ // HTTP SERVER
818
+ // ─────────────────────────────────────────────────────────
819
+ const server = http.createServer((req, res) => {
820
+ const parsed = new URL(req.url, `http://${req.headers.host}`);
821
+
822
+ if (req.method === 'OPTIONS') {
823
+ res.writeHead(204, { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': '*' });
824
+ res.end(); return;
825
+ }
826
+
827
+ // ── /login β€” open visible browser for manual login ──
828
+ if (parsed.pathname === '/login') {
829
+ startLogin(res).catch(e => { log('LOGIN-ERR', e.message); res.writeHead(500); res.end(e.message); });
830
+ return;
831
+ }
832
+
833
+ // ── /save-session β€” save cookies after manual login ──
834
+ if (parsed.pathname === '/save-session') {
835
+ saveSessionAndClose(res).catch(e => { log('SAVE-ERR', e.message); res.writeHead(500); res.end(e.message); });
836
+ return;
837
+ }
838
+
839
+ // ── /session-status β€” check if session exists ──
840
+ if (parsed.pathname === '/session-status') {
841
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
842
+ res.end(JSON.stringify({ hasSession: hasSession(), file: SESSION_FILE }));
843
+ return;
844
+ }
845
+
846
+ // ── /start-rebel777?url=... ──
847
+ if (parsed.pathname === '/start-rebel777') {
848
+ const target = parsed.searchParams.get('url');
849
+ if (!target) { res.writeHead(400, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); res.end(JSON.stringify({ error: 'Missing ?url=' })); return; }
850
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
851
+ res.end(JSON.stringify({ ok: true, msg: 'Starting...' }));
852
+ startBrowser(target).catch(e => log('ERR', e.message));
853
+ return;
854
+ }
855
+
856
+ // ── /stop-rebel777 ──
857
+ if (parsed.pathname === '/stop-rebel777') {
858
+ stopScraper().catch(() => { });
859
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
860
+ res.end(JSON.stringify({ ok: true }));
861
+ return;
862
+ }
863
+
864
+ // ── /set-interval?ms=5000 ──
865
+ if (parsed.pathname === '/set-interval') {
866
+ const ms = parseInt(parsed.searchParams.get('ms'));
867
+ if (ms >= 250 && ms <= 60000) {
868
+ SCRAPE_INTERVAL = ms;
869
+ if (scrapeTimer) { clearInterval(scrapeTimer); scrapeTimer = page ? setInterval(doPoll, ms) : null; }
870
+ log('INTERVAL', `Poll rate β†’ ${ms}ms`);
871
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
872
+ res.end(JSON.stringify({ ok: true, ms }));
873
+ } else {
874
+ res.writeHead(400, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
875
+ res.end(JSON.stringify({ error: 'ms must be 1000–60000' }));
876
+ }
877
+ return;
878
+ }
879
+
880
+ // ── /debug ──
881
+ if (parsed.pathname === '/debug') {
882
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
883
+ res.end(JSON.stringify({ hasSession: hasSession(), lastOdds, wsClients: wsClients.size, currentUrl, isScraping, scrapeInterval: SCRAPE_INTERVAL }, null, 2));
884
+ return;
885
+ }
886
+
887
+ // ── /poly-fetch?url=... β€” uses headless Chrome TLS fingerprint to bypass Cloudflare ──
888
+ if (parsed.pathname === '/poly-fetch') {
889
+ const target = parsed.searchParams.get('url');
890
+ if (!target) {
891
+ res.writeHead(400, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
892
+ res.end(JSON.stringify({ error: 'Missing ?url=' })); return;
893
+ }
894
+ workerFetch(target, res); return;
895
+ }
896
+
897
+ // ── /proxy?url=... ──
898
+ if (parsed.pathname === '/proxy') {
899
+ const target = parsed.searchParams.get('url');
900
+ if (!target) { res.writeHead(400, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }); res.end(JSON.stringify({ error: 'Missing ?url=' })); return; }
901
+ proxyFetch(target, res); return;
902
+ }
903
+
904
+ // ── / β†’ serve HTML ──
905
+ if (parsed.pathname === '/' || parsed.pathname === '/index.html') {
906
+ const htmlPath = path.join(__dirname, 'decimal-bot.html');
907
+ if (fs.existsSync(htmlPath)) {
908
+ res.writeHead(200, { 'Content-Type': 'text/html', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache' });
909
+ res.end(fs.readFileSync(htmlPath));
910
+ } else {
911
+ res.writeHead(404);
912
+ res.end('decimal-bot.html not found in the same folder');
913
+ }
914
+ return;
915
+ }
916
+ res.writeHead(404); res.end('Not found');
917
+ });
918
+
919
+ // ─────────────────────────────────────────────────────────
920
+ // WEBSOCKET SERVER
921
+ // ─────────────────────────────────────────────────────────
922
+ const wss = new WebSocketServer({ server });
923
+ wss.on('connection', ws => {
924
+ wsClients.add(ws);
925
+ log('WS', `Client connected (${wsClients.size} total)`);
926
+
927
+ // Tell client immediately if session is missing
928
+ if (!hasSession()) {
929
+ ws.send(JSON.stringify({ type: 'error', msg: '⚠️ No session β€” visit http://localhost:3000/login first' }));
930
+ } else if (lastOdds) {
931
+ ws.send(JSON.stringify({ type: 'odds', data: { runners: lastOdds, _source: 'rebel777', _ts: Date.now() } }));
932
+ } else {
933
+ ws.send(JSON.stringify({ type: 'status', msg: 'Connected β€” paste rebel777 URL and click START', state: 'idle' }));
934
+ }
935
+
936
+ ws.on('close', () => { wsClients.delete(ws); log('WS', `Disconnected (${wsClients.size} total)`); });
937
+ ws.on('error', () => wsClients.delete(ws));
938
+ });
939
+
940
+ // ─────────────────────────────────────────────────────────
941
+ // GRACEFUL SHUTDOWN
942
+ // ─────────────────────────────────────────────────────────
943
+ process.on('SIGINT', async () => {
944
+ console.log('\n[SHUTDOWN] Closing...');
945
+ if (scrapeTimer) clearInterval(scrapeTimer);
946
+ if (browser) await browser.close().catch(() => { });
947
+ if (loginBrowser) await loginBrowser.close().catch(() => { });
948
+ process.exit(0);
949
+ });
950
+
951
+ // ─────────────────────────────────────────────────────────
952
+ // START
953
+ // ─────────────────────────────────────────────────────────
954
+ server.listen(PORT, () => {
955
+ const sessionStatus = hasSession() ? 'βœ“ Session found β€” ready to scrape' : '⚠ No session β€” open /login first';
956
+ console.log(`
957
+ ╔══════════════════════════════════════════════════════════════╗
958
+ β•‘ IPL Arb Proxy v4 β€” Session-Persistent Edition β•‘
959
+ ╠══════════════════════════════════════════════════════════════╣
960
+ β•‘ UI: http://localhost:${PORT} β•‘
961
+ β•‘ Login: http://localhost:${PORT}/login β•‘
962
+ β•‘ Save session: http://localhost:${PORT}/save-session β•‘
963
+ β•‘ Debug: http://localhost:${PORT}/debug β•‘
964
+ ╠══════════════════════════════════════════════════════════════╣
965
+ β•‘ ${sessionStatus.padEnd(58)}β•‘
966
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
967
+ `);
968
+
969
+ if (!hasSession()) {
970
+ console.log(' πŸ‘‰ First time setup: open http://localhost:3000/login in your browser\n');
971
+ }
972
+ });
973
+
974
+
975
+
976
+ // ─────────────────────────────────────────────────────────
977
+
978
+ //1. node proxy.js
979
+ //2. Open http://localhost:3000/login ← opens a VISIBLE Chromium window
980
+ //3. Log into rebel777 in that window normally
981
+ //4. Once you can see match odds, go to http://localhost:3000/save-session
982
+ //5. Done β€” rebel777-session.json is saved to disk
983
+
984
+ // ─────────────────────────────────────────────────────────