-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
466 lines (397 loc) · 18.8 KB
/
script.js
File metadata and controls
466 lines (397 loc) · 18.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
import * as playwright from "playwright";
import * as fs from "fs";
// ─── Konfiguration ───────────────────────────────────────────────────────────
const CONFIG = {
rufnummer: "01234567890",
passwort: "deinPasswort",
sleepmode: "smart", // "smart", "fixed", "random"
sleepTime: 300, // Sekunden (nur bei sleepmode = "fixed")
// Proxy (optional, null = kein Proxy)
// Formate: "http://host:port" | "http://user:pass@host:port" | "socks5://host:port"
proxy: null,
};
// ─── Konstanten ──────────────────────────────────────────────────────────────
const uebersichtUrl = "https://kundenkonto.lidl-connect.de/mein-lidl-connect/uebersicht.html";
const USER_AGENT = "Mozilla/5.0 (X11; Linux aarch64; rv:137.0) Gecko/20100101 Firefox/137.0";
const cookiefile = "cookies.json";
const MAX_LOGIN_ATTEMPTS = 3;
const MAX_CONSECUTIVE_ERRORS = 5;
const KEEPALIVE_INTERVAL = 2 * 60 * 1000; // 2 min
const BROWSER_RESTART_INTERVAL = 2 * 60 * 60 * 1000; // 2h
const LOGIN_RESET_INTERVAL = 30 * 60 * 1000; // 30 min
const delay = ms => new Promise(res => setTimeout(res, ms));
// ─── Zustand ─────────────────────────────────────────────────────────────────
let context = null;
let page = null;
let loginAttempts = 0;
let lastLoginTime = 0;
let consecutiveErrors = 0;
let isShuttingDown = false;
let isRestarting = false;
let isRunning = false;
let letzterDataCheck = null; // Datum (YYYY-MM-DD) des letzten DATA-Label-Checks
let circuitOpen = false;
let circuitOpenTime = null;
// ─── Logging ─────────────────────────────────────────────────────────────────
const LOG_FILE = 'bot.log';
const LOG_MAX = 2 * 1024 * 1024; // 2 MB Ring-Buffer
function writeLog(line) {
try {
const entry = line + '\n';
const entryBuf = Buffer.from(entry, 'utf-8');
if (!fs.existsSync(LOG_FILE)) {
fs.writeFileSync(LOG_FILE, entry);
return;
}
const size = fs.statSync(LOG_FILE).size;
if (size + entryBuf.length <= LOG_MAX) {
fs.appendFileSync(LOG_FILE, entry);
} else {
// Ring-Buffer: älteste Hälfte wegwerfen, neuere behalten + neuen Eintrag anhängen
const current = fs.readFileSync(LOG_FILE, 'utf-8');
const half = Math.floor(current.length / 2);
const cutIdx = current.indexOf('\n', half) + 1;
fs.writeFileSync(LOG_FILE, current.slice(cutIdx) + entry);
}
} catch (e) {
// Log-Fehler nie crashen lassen
}
}
function log(message, level = 'info') {
const ts = new Date().toLocaleString('de-DE');
let line;
switch (level) {
case 'error': line = `[${ts}] ❌ ${message}`; console.error(line); break;
case 'warn': line = `[${ts}] ⚠️ ${message}`; console.warn(line); break;
case 'success': line = `[${ts}] ✅ ${message}`; console.log(line); break;
default: line = `[${ts}] ℹ️ ${message}`; console.log(line);
}
writeLog(line);
}
// ─── Circuit Breaker ─────────────────────────────────────────────────────────
function circuitCheck() {
if (!circuitOpen) return;
const elapsed = Date.now() - circuitOpenTime;
if (elapsed > 2 * 60 * 1000) {
log('Circuit Breaker: Reset nach 2 min', 'warn');
circuitOpen = false;
circuitOpenTime = null;
consecutiveErrors = Math.floor(MAX_CONSECUTIVE_ERRORS / 2);
} else {
throw new Error(`Circuit Breaker offen - warte noch ${Math.round((120000 - elapsed) / 1000)}s`);
}
}
function circuitFailure() {
consecutiveErrors++;
if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
log(`Circuit Breaker: Offen nach ${consecutiveErrors} Fehlern`, 'error');
circuitOpen = true;
circuitOpenTime = Date.now();
} else {
log(`Fehler ${consecutiveErrors}/${MAX_CONSECUTIVE_ERRORS}`, 'warn');
}
}
function circuitSuccess() {
if (consecutiveErrors > 0) log('Fehler zurückgesetzt', 'success');
consecutiveErrors = 0;
circuitOpen = false;
circuitOpenTime = null;
}
// ─── Browser ─────────────────────────────────────────────────────────────────
async function closeBrowser() {
try {
if (page && !page.isClosed()) { await page.close(); page = null; }
if (context) { await context.close(); context = null; }
} catch (e) {
log(`Fehler beim Schließen: ${e.message}`, 'error');
}
}
async function initBrowser() {
if (isShuttingDown) return false;
log('Initialisiere Browser...');
try {
const userDataDir = './lidl-data';
if (consecutiveErrors >= 2) {
log('Räume Browser-Daten auf...', 'warn');
if (fs.existsSync(userDataDir)) fs.rmSync(userDataDir, { recursive: true, force: true });
if (fs.existsSync(cookiefile)) fs.unlinkSync(cookiefile);
}
const browserOptions = {
headless: true,
args: ["--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage", "--disable-gpu", "--single-process"],
userAgent: USER_AGENT,
storageState: fs.existsSync(cookiefile) ? cookiefile : undefined
};
if (CONFIG.proxy) {
const url = new URL(CONFIG.proxy);
browserOptions.proxy = {
server: `${url.protocol}//${url.hostname}:${url.port}`,
...(url.username && { username: decodeURIComponent(url.username) }),
...(url.password && { password: decodeURIComponent(url.password) }),
};
log(`Proxy aktiv: ${url.protocol}//${url.hostname}:${url.port}`);
}
context = await playwright.chromium.launchPersistentContext(userDataDir, browserOptions);
page = await context.newPage();
page.on('crash', () => { log('Browser abgestürzt!', 'error'); circuitFailure(); });
log('Browser gestartet', 'success');
return true;
} catch (e) {
log(`Browser-Init fehlgeschlagen: ${e.message}`, 'error');
circuitFailure();
return false;
}
}
async function restartBrowser() {
if (isRestarting) return;
isRestarting = true;
log('Starte Browser neu...', 'warn');
await closeBrowser();
await delay(5000);
if (await initBrowser()) {
circuitSuccess();
log('Browser neu gestartet', 'success');
}
isRestarting = false;
}
// ─── Daten auslesen ──────────────────────────────────────────────────────────
async function tryReadData() {
try {
if (!page || page.isClosed()) return { success: false, daten: 0, refill: 0 };
// Login-Prüfung
if (await page.$("input[name='msisdn']") !== null)
return { success: false, daten: 0, refill: 0 };
// Seite immer neu laden damit aktuelle Werte gelesen werden
await page.goto(uebersichtUrl, { waitUntil: "networkidle", timeout: 30000 });
if (await page.$("input[name='msisdn']") !== null)
return { success: false, daten: 0, refill: 0 };
// Warten bis Web Components gerendert sind
await page.waitForSelector('article[aria-label="Unlimited Refill"]', { timeout: 15000 }).catch(() => null);
// Wert aus article-Element lesen
const readArticle = async (ariaLabel) => {
const article = await page.$(`article[aria-label="${ariaLabel}"]`);
if (!article) return null;
const raw = await article.$eval('p[aria-live="polite"]', el => el.textContent).catch(() => null);
if (!raw) return null;
const nums = raw.match(/(\d+[.,]\d+|\d+)/g);
return nums ? +parseFloat(nums[0].replace(',', '.')).toFixed(3) : null;
};
// DATA-Label nur einmal täglich checken:
// - Kurz nach Mitternacht (00:00–00:30): checken ob Monat neu gestartet
// - Wenn danach noch 0: erst wieder nächsten Tag um 00:00
const heute = new Date().toISOString().slice(0, 10);
const minuten = new Date().getHours() * 60 + new Date().getMinutes();
let daten = 0;
if (letzterDataCheck !== heute) {
const datenWert = await readArticle('Verfügbares Gesamtvolumen');
if (datenWert === null) log('DATA-Label nicht im DOM gefunden', 'warn');
else if (datenWert === 0) log('DATA-Label gefunden - Volumen leer (0 GB)');
else log(`Reguläres Volumen: ${datenWert} GB`, 'success');
daten = datenWert ?? 0;
// Erst nach 00:30 als "heute gecheckt" markieren,
// damit kurz nach Mitternacht ggf. nochmal geprüft wird
if (minuten >= 30 || daten > 0) letzterDataCheck = heute;
} else {
log('DATA-Label heute bereits gecheckt (0 GB) - überspringe');
}
const refill = await readArticle('Unlimited Refill');
if (refill === null) log('Refill-Label nicht im DOM gefunden', 'warn');
else if (refill > 0) log(`Refill-Volumen: ${refill} GB`);
return { success: true, daten: daten ?? 0, refill: refill ?? 0 };
} catch (e) {
log(`Fehler beim Auslesen: ${e.message}`, 'error');
return { success: false, daten: 0, refill: 0 };
}
}
// ─── Login ───────────────────────────────────────────────────────────────────
async function performLogin() {
if (isShuttingDown) return false;
if (loginAttempts > 0 && (Date.now() - lastLoginTime) > LOGIN_RESET_INTERVAL) {
loginAttempts = 0;
}
if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
throw new Error(`Max Login-Versuche erreicht (${loginAttempts}/${MAX_LOGIN_ATTEMPTS})`);
}
loginAttempts++;
lastLoginTime = Date.now();
log(`Login-Versuch ${loginAttempts}/${MAX_LOGIN_ATTEMPTS}`, 'warn');
try {
await page.goto(uebersichtUrl, { waitUntil: "networkidle", timeout: 30000 });
if (await page.$("input[name='msisdn']") === null) {
log('Bereits eingeloggt', 'success');
loginAttempts = 0;
return true;
}
await page.waitForSelector("input[name='msisdn']", { timeout: 15000 });
await page.waitForSelector("input[type='password']", { timeout: 15000 });
await delay(1000);
log('Fülle Login-Daten aus...');
await page.fill("input[name='msisdn']", CONFIG.rufnummer);
await delay(500);
await page.fill("input[type='password']", CONFIG.passwort);
await delay(500);
log('Sende Login-Formular...');
const btn = await page.$("button:has-text('Einloggen')");
await Promise.all([
btn ? btn.click() : page.press("input[type='password']", "Enter"),
page.waitForNavigation({ waitUntil: "networkidle", timeout: 30000 })
]);
if (!page.url().includes('uebersicht')) {
await page.screenshot({ path: 'login-failed.png', fullPage: true });
throw new Error("Nicht auf Übersichtsseite gelandet");
}
await context.storageState({ path: cookiefile });
loginAttempts = 0;
log('Login erfolgreich!', 'success');
return true;
} catch (e) {
log(`Login fehlgeschlagen: ${e.message}`, 'error');
if (loginAttempts >= 2) { log('Warte 60s...', 'warn'); await delay(60000); }
return false;
}
}
// ─── Hauptprozess ────────────────────────────────────────────────────────────
async function main() {
if (isShuttingDown) return 0;
log('========== Starte Hauptprozess ==========');
circuitCheck();
if (!context || !page || page.isClosed()) {
if (!await initBrowser()) throw new Error("Browser init fehlgeschlagen");
}
let data = await tryReadData();
if (!data.success) {
log('Login erforderlich', 'warn');
if (fs.existsSync(cookiefile)) fs.unlinkSync(cookiefile);
if (!await performLogin()) throw new Error("Login fehlgeschlagen");
data = await tryReadData();
if (!data.success) throw new Error("Daten nach Login nicht lesbar");
}
const { daten, refill } = data;
const regularesLeer = daten === 0;
const refillUnter04 = refill < 0.4;
let gebucht = false;
let refillNachBuchung = refill;
if (regularesLeer && refillUnter04) {
log('Reguläres Volumen leer und Refill unter 0.4 GB - versuche Nachbuchung...', 'warn');
for (const sel of [
"button[aria-label='Datenvolumen per Refill wieder auffüllen']",
"button:has-text('Refill aktivieren')",
"button:has-text('Nachbuchen')"
]) {
try {
const btn = await page.$(sel);
if (!btn) continue;
await btn.scrollIntoViewIfNeeded();
await delay(1000);
await btn.click({ timeout: 10000 });
await delay(8000);
await page.reload({ waitUntil: "networkidle", timeout: 30000 });
const nachher = await tryReadData();
if (nachher.success && nachher.refill > refill) {
gebucht = true;
log(`Nachbuchung bestätigt! Refill: ${refill} GB → ${nachher.refill} GB`, 'success');
// Direkt den verifizierten Wert verwenden statt zu rechnen
refillNachBuchung = nachher.refill;
} else {
await page.screenshot({ path: 'refill-verify-failed.png', fullPage: true });
log(`Nachbuchung nicht bestätigt (vorher: ${refill} GB, nachher: ${nachher.refill} GB)`, 'error');
}
break;
} catch (e) {
log(`${sel} nicht klickbar: ${e.message}`, 'warn');
}
}
if (!gebucht) {
await page.screenshot({ path: 'no-refill-button.png', fullPage: true });
log('Kein Nachbuchungs-Button gefunden', 'error');
}
} else if (daten > 0) {
log(`Reguläres Volumen noch vorhanden (${daten} GB) - kein Refill nötig`);
} else {
log('Nachbuchung nicht erforderlich');
}
const verfuegbar = daten > 0 ? daten : +(gebucht ? refillNachBuchung : refill).toFixed(3);
log(`Verfügbar: ${verfuegbar} GB`, 'success');
circuitSuccess();
return verfuegbar;
}
// ─── Intervall ───────────────────────────────────────────────────────────────
const rnd = (min, max) => Math.floor(Math.random() * (max - min)) + min;
function getInterval(daten) {
if (CONFIG.sleepmode === 'fixed') return Math.max(CONFIG.sleepTime || 300, 60);
if (CONFIG.sleepmode === 'random') return rnd(300, 500);
// Reguläres Monatsvolumen vorhanden → selten checken
if (daten >= 10) return rnd(3600, 5400);
if (daten >= 5) return rnd(1800, 2700);
if (daten >= 3) return rnd(900, 1800);
if (daten >= 2) return rnd(600, 900);
// Refill-Modus
if (daten >= 1.2) return rnd(300, 450);
if (daten >= 1.0) return rnd(120, 180);
if (daten >= 0.5) return rnd(60, 90);
if (daten >= 0.4) return 30;
return 60;
}
// ─── Start ───────────────────────────────────────────────────────────────────
async function start() {
log('='.repeat(50));
log('🚀 Lidl Connect Refill Bot');
log(`Sleep Mode: ${CONFIG.sleepmode}`);
log('='.repeat(50));
// KeepAlive: nur pingen wenn main() nicht läuft
setInterval(async () => {
if (!isShuttingDown && !isRunning && !isRestarting && page && !page.isClosed()) {
try {
await page.evaluate(() => fetch('/mein-lidl-connect/uebersicht.html', { method: 'HEAD' }));
log('Session aufgefrischt');
} catch (e) {
log(`KeepAlive fehlgeschlagen: ${e.message}`, 'warn');
}
}
}, KEEPALIVE_INTERVAL);
// Browser alle 2h neu starten
setInterval(async () => {
if (!isShuttingDown && !isRestarting) {
log('Geplanter Browser-Neustart', 'warn');
while (isRunning) await delay(1000);
await restartBrowser();
}
}, BROWSER_RESTART_INTERVAL);
const run = async () => {
if (isShuttingDown || isRestarting) {
if (!isShuttingDown) setTimeout(run, 5000);
return;
}
isRunning = true;
let daten = 0;
try {
daten = await main();
} catch (e) {
log(`Fehler: ${e.message}`, 'error');
circuitFailure();
if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) await restartBrowser();
}
isRunning = false;
if (!isShuttingDown) {
const next = getInterval(daten);
log(`Nächster Check in ${next}s (${Math.round(next / 60)} min)`);
if (daten > 0) log(`📊 Verfügbar: ${daten} GB`, 'success');
setTimeout(run, next * 1000);
}
};
run();
}
// ─── Shutdown ────────────────────────────────────────────────────────────────
async function shutdown(signal) {
if (isShuttingDown) return;
log(`Shutdown: ${signal}`, 'warn');
isShuttingDown = true;
await closeBrowser();
process.exit(0);
}
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGHUP', () => shutdown('SIGHUP'));
process.on('unhandledRejection', (r) => { log(`Unhandled: ${r}`, 'error'); circuitFailure(); });
process.on('uncaughtException', (e) => { log(`Exception: ${e.message}`, 'error'); shutdown('exception'); });
start();