JOHN SILLVESTOR commited on
Commit
3a2609d
·
verified ·
1 Parent(s): 9cd4fe7

Update Node HTTP service

Browse files
Files changed (1) hide show
  1. server.js +336 -94
server.js CHANGED
@@ -19,6 +19,11 @@ const MB = 1024 * 1024;
19
  const HTTP_WINDOW = MB;
20
  const GET_SIZES = [524288, 262144, 131072, 65536, 32768, 16384, 8192, 4096];
21
  const BOT_MAX = 24;
 
 
 
 
 
22
  const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "";
23
  const FB_DB = String(process.env.FIREBASE_DB_URL || "").replace(/\/?$/, "/");
24
  const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
@@ -44,9 +49,11 @@ const hmacKey = STREAM_SECRET
44
 
45
  const bots = [];
46
  const fileCache = new Map();
 
47
  const durCache = new Map();
48
  const lvlCache = new Map();
49
  const rateMap = new Map();
 
50
  let fbKeys = { certs: null, exp: 0 };
51
  let rr = 0;
52
 
@@ -114,28 +121,144 @@ function cors(req, res) {
114
  }
115
 
116
  function json(res, code, body) {
 
117
  const s = JSON.stringify(body);
118
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
119
  res.end(s);
120
  }
121
 
122
- function limited(ip) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  const now = Date.now();
124
- const slot = Math.floor(now / 60000);
125
- const key = ip + ":" + slot;
126
- const n = (rateMap.get(key) || 0) + 1;
127
- rateMap.set(key, n);
 
 
 
 
 
 
 
 
 
 
128
  if (rateMap.size > 4000) {
 
129
  for (const k of rateMap.keys()) {
130
  if (!k.endsWith(":" + slot) && !k.endsWith(":" + (slot - 1))) rateMap.delete(k);
131
  }
132
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  return n > 800;
134
  }
135
 
136
  async function googleCerts() {
137
  if (fbKeys.certs && Date.now() < fbKeys.exp) return fbKeys.certs;
138
- const r = await fetch("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com");
 
 
139
  if (!r.ok) throw new Error("certs");
140
  const certs = await r.json();
141
  const cc = r.headers.get("cache-control") || "";
@@ -178,7 +301,8 @@ async function rtdb(path, method, body) {
178
  const r = await fetch(url, {
179
  method,
180
  headers: body == null ? undefined : { "Content-Type": "application/json" },
181
- body: body == null ? undefined : JSON.stringify(body)
 
182
  });
183
  if (!r.ok) throw new Error("db " + r.status);
184
  const t = await r.text();
@@ -199,10 +323,10 @@ function vipActive(sub) {
199
  async function accessLevel(uid) {
200
  if (!uid) return "anonymous";
201
  const hit = lvlCache.get(uid);
202
- if (hit && Date.now() - hit.ts < 25000) return hit.lvl;
203
  let lvl = "registered";
204
  try {
205
- const sub = await rtdb("users/" + uid + "/subscription", "GET");
206
  if (vipActive(sub)) lvl = "subscribed";
207
  } catch {}
208
  lvlCache.set(uid, { lvl, ts: Date.now() });
@@ -221,10 +345,9 @@ function httpVideoType(mime, name) {
221
  return "video/mp4";
222
  }
223
 
224
- function pickBot(preferIdx) {
225
  if (!bots.length) return null;
226
- const live = bots.filter((b) => b.ready && b.load < BOT_MAX);
227
- const pool = live.length ? live : bots.filter((b) => b.ready);
228
  if (!pool.length) return null;
229
  const min = Math.min(...pool.map((b) => b.load));
230
  if (preferIdx != null) {
@@ -237,19 +360,24 @@ function pickBot(preferIdx) {
237
  return bot;
238
  }
239
 
240
-
241
  async function startBot(token, idx) {
242
  const client = new TelegramClient(new StringSession(""), API_ID, API_HASH, {
243
- connectionRetries: 8,
 
244
  retryDelay: 1500,
245
  autoReconnect: true,
246
  useWSS: true,
247
- maxConcurrentDownloads: 16,
248
- downloadPool: { poolSize: 6, workers: 8, requestDeadlineMs: 25000 }
 
 
 
249
  });
250
  client.setLogLevel("error");
 
251
  await client.start({ botAuthToken: token });
252
- bots.push({ client, token, idx, ready: true, load: 0 });
 
253
  }
254
 
255
  function dropFile(msgId, bot) {
@@ -263,10 +391,7 @@ function dropFile(msgId, bot) {
263
  }
264
  }
265
 
266
- async function fileFromMsg(bot, msgId) {
267
- const key = String(msgId) + ":" + bot.idx;
268
- const hit = fileCache.get(key);
269
- if (hit && Date.now() - hit.ts < 15 * 60 * 1000) return hit;
270
  const msgs = await bot.client.getMessages(CHANNEL_ID, { ids: msgId });
271
  const msg = msgs && msgs[0];
272
  if (!msg || msg.deleted) throw new Error("missing");
@@ -297,10 +422,47 @@ async function fileFromMsg(bot, msgId) {
297
  doc,
298
  ts: Date.now()
299
  };
300
- fileCache.set(key, rec);
301
  return rec;
302
  }
303
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  function durationFromMp4(buf) {
305
  const i = buf.indexOf(Buffer.from("mvhd"));
306
  if (i < 4 || i + 24 > buf.length) return 0;
@@ -330,12 +492,12 @@ async function fillDuration(bot, rec, msgId) {
330
  if (id) durCache.set(id, rec.duration);
331
  return;
332
  }
333
- if (!rec.size) return;
334
  const n = Math.min(rec.size, 1024 * 1024);
335
  const start = rec.size - n;
336
  let acc = Buffer.alloc(0);
337
  try {
338
- for await (const c of rangeChunks(bot, rec, start, rec.size - 1)) {
339
  acc = Buffer.concat([acc, c]);
340
  rec.duration = durationFromMp4(acc);
341
  if (rec.duration > 0) {
@@ -383,9 +545,10 @@ function pickGetSize(room, want) {
383
  return MIN_ALIGN;
384
  }
385
 
386
- async function* rangeChunks(bot, rec, start, end) {
387
  let pos = start;
388
  while (pos <= end) {
 
389
  const aligned = Math.floor(pos / MIN_ALIGN) * MIN_ALIGN;
390
  let skip = pos - aligned;
391
  const pageEnd = Math.floor(aligned / MB) * MB + MB;
@@ -402,6 +565,7 @@ async function* rangeChunks(bot, rec, start, end) {
402
  });
403
  let sent = 0;
404
  for await (const chunk of it) {
 
405
  let buf = Buffer.from(chunk);
406
  if (skip) {
407
  if (buf.length <= skip) {
@@ -423,37 +587,51 @@ async function* rangeChunks(bot, rec, start, end) {
423
  }
424
  }
425
 
426
- async function pipeRange(bot, rec, start, end, res, status, headers) {
427
  bot.load++;
 
428
  try {
429
  if (res.socket) {
430
  res.socket.setNoDelay(true);
431
  res.socket.setKeepAlive(true, 15000);
432
  }
 
433
  res.writeHead(status, headers);
434
  if (typeof res.flushHeaders === "function") res.flushHeaders();
435
- const gen = rangeChunks(bot, rec, start, end);
 
436
  for await (const buf of gen) {
437
- if (res.destroyed || res.writableEnded) break;
438
  const ok = res.write(buf);
439
- if (!ok) await new Promise((r) => res.once("drain", r));
440
  }
441
  } finally {
442
  bot.load = Math.max(0, bot.load - 1);
443
- if (!res.writableEnded) res.end();
 
 
444
  }
445
  }
446
 
447
- async function readBody(req) {
 
448
  const chunks = [];
449
- for await (const c of req) chunks.push(c);
 
 
 
 
 
450
  return Buffer.concat(chunks);
451
  }
452
 
453
  async function handleGenerate(req, res, url) {
454
  if (!aesKey) return json(res, 503, { error: "misconfigured" });
455
- const ip = req.headers["x-forwarded-for"] ? String(req.headers["x-forwarded-for"]).split(",")[0].trim() : req.socket.remoteAddress || "0";
456
- if (limited(ip)) return json(res, 429, { error: "rate_limited" });
 
 
 
457
  const path = url.searchParams.get("path") || "";
458
  const hash = (url.searchParams.get("hash") || "").toLowerCase();
459
  const m = /\/stream\/(\d+)/.exec(path);
@@ -462,23 +640,23 @@ async function handleGenerate(req, res, url) {
462
  let uid = null;
463
  let lvl = "anonymous";
464
  try {
465
- const idp = await verifyIdToken(req.headers.authorization || "");
466
  if (idp) {
467
  uid = idp.sub;
468
  lvl = await accessLevel(uid);
469
  }
470
  } catch {
471
- lvl = "anonymous";
472
  }
473
- const bot = pickBot();
474
- if (!bot) return json(res, 503, { error: "bots_offline" });
475
- let rec;
476
  try {
477
- rec = await fileFromMsg(bot, msgId);
478
- } catch (e) {
479
- dropFile(msgId, bot);
480
- return json(res, 400, { error: "file" });
481
  }
 
 
 
482
  const cachedDur = durCache.get(String(msgId));
483
  if (cachedDur) rec.duration = cachedDur;
484
  const playMime = httpVideoType(rec.mime, rec.name);
@@ -508,60 +686,91 @@ async function handleStream(req, res, url, msgId) {
508
  res.writeHead(410);
509
  return res.end();
510
  }
511
- const bot = pickBot(Number.isInteger(ticket.b) ? ticket.b : undefined);
512
- if (!bot) {
513
- res.writeHead(503);
 
514
  return res.end();
515
  }
516
- let rec;
517
  try {
518
- rec = await fileFromMsg(bot, msgId);
519
- } catch {
520
- dropFile(msgId, bot);
521
- res.writeHead(404);
522
- return res.end();
523
- }
524
- const size = rec.size;
525
- const rng = parseRange(req.headers.range, size);
526
- const headers = {
527
- "Content-Type": httpVideoType(rec.mime, rec.name),
528
- "Accept-Ranges": "bytes",
529
- "Cache-Control": "private, max-age=60",
530
- "Content-Disposition": "inline"
531
- };
532
- const partial = rng.start > 0 || rng.end < size - 1 || !!req.headers.range;
533
- headers["Content-Length"] = String(rng.end - rng.start + 1);
534
- if (partial) {
535
- headers["Content-Range"] = "bytes " + rng.start + "-" + rng.end + "/" + size;
536
- }
537
- if (req.method === "HEAD") {
538
- res.writeHead(partial ? 206 : 200, headers);
539
- return res.end();
540
- }
541
- const status = partial ? 206 : 200;
542
- try {
543
- await pipeRange(bot, rec, rng.start, rng.end, res, status, headers);
544
- } catch (e) {
545
- const msg = String(e && e.errorMessage || e.message || e);
546
- if (/FILE_REFERENCE/i.test(msg)) dropFile(msgId, bot);
547
- if (/FILE_REFERENCE/i.test(msg) && !res.headersSent) {
548
  try {
549
- rec = await fileFromMsg(bot, msgId);
550
- await pipeRange(bot, rec, rng.start, rng.end, res, status, headers);
551
- return;
552
- } catch {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  }
554
- if (!res.headersSent) {
555
- res.writeHead(502);
556
- res.end();
557
- } else if (!res.writableEnded) res.end();
558
  }
559
  }
560
 
561
  async function handleVipStatus(req, res) {
562
  let lvl = "anonymous";
563
  try {
564
- const idp = await verifyIdToken(req.headers.authorization || "");
565
  if (idp) {
566
  lvl = await accessLevel(idp.sub);
567
  let sub = null;
@@ -575,9 +784,14 @@ async function handleVipStatus(req, res) {
575
  async function handleVipStart(req, res) {
576
  if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
577
  if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
578
- const idp = await verifyIdToken(req.headers.authorization || "");
579
  if (!idp) return json(res, 401, { error: "login" });
580
- const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
 
 
 
 
 
581
  const plan = PLANS[body.plan];
582
  if (!plan) return json(res, 400, { error: "plan" });
583
  const r = await fetch("https://api.stripe.com/v1/checkout/sessions", {
@@ -598,7 +812,8 @@ async function handleVipStart(req, res) {
598
  "metadata[plan]": body.plan,
599
  "payment_intent_data[metadata][uid]": idp.sub,
600
  "payment_intent_data[metadata][plan]": body.plan
601
- }).toString()
 
602
  });
603
  const d = await r.json();
604
  if (!r.ok || !d.id) return json(res, 400, { error: d.error && d.error.message || "Payment failed" });
@@ -608,12 +823,18 @@ async function handleVipStart(req, res) {
608
  async function handleVipGo(req, res) {
609
  if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
610
  if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
611
- const idp = await verifyIdToken(req.headers.authorization || "");
612
  if (!idp) return json(res, 401, { error: "login" });
613
- const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
 
 
 
 
 
614
  if (!body.sid) return json(res, 400, { error: "session" });
615
  const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(body.sid), {
616
- headers: { Authorization: "Bearer " + STRIPE_KEY }
 
617
  });
618
  const d = await r.json();
619
  if (!r.ok || !d.url) return json(res, 400, { error: d.error && d.error.message || "Payment failed" });
@@ -683,10 +904,15 @@ async function handleBootstrap(req, res, url) {
683
  }
684
 
685
  function handleHealth(res) {
 
 
 
 
 
686
  json(res, 200, {
687
  ok: true,
688
  role: ROLE,
689
- bots: bots.filter((b) => b.ready).length,
690
  load: bots.reduce((n, b) => n + b.load, 0),
691
  cap: bots.filter((b) => b.ready).length * BOT_MAX
692
  });
@@ -705,6 +931,8 @@ function handleHome(req, res) {
705
  }
706
 
707
  async function onReq(req, res) {
 
 
708
  cors(req, res);
709
  if (req.method === "OPTIONS") {
710
  res.writeHead(204);
@@ -762,11 +990,25 @@ async function main() {
762
  keepAlive: true,
763
  keepAliveTimeout: 65000,
764
  headersTimeout: 70000,
765
- requestTimeout: 0
 
766
  }, onReq);
 
 
 
 
 
 
767
  srv.listen(PORT, "0.0.0.0");
768
  }
769
 
 
 
 
 
 
 
 
770
  main().catch((e) => {
771
  process.stderr.write(String(e && e.stack || e) + "\n");
772
  process.exit(1);
 
19
  const HTTP_WINDOW = MB;
20
  const GET_SIZES = [524288, 262144, 131072, 65536, 32768, 16384, 8192, 4096];
21
  const BOT_MAX = 24;
22
+ const PIPE_MS = 45000;
23
+ const IP_STREAM_MAX = 48;
24
+ const BODY_MAX = 262144;
25
+ const FILE_TTL = 15 * 60 * 1000;
26
+ const LVL_TTL = 25000;
27
  const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "";
28
  const FB_DB = String(process.env.FIREBASE_DB_URL || "").replace(/\/?$/, "/");
29
  const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
 
49
 
50
  const bots = [];
51
  const fileCache = new Map();
52
+ const inflightFile = new Map();
53
  const durCache = new Map();
54
  const lvlCache = new Map();
55
  const rateMap = new Map();
56
+ const ipStreams = new Map();
57
  let fbKeys = { certs: null, exp: 0 };
58
  let rr = 0;
59
 
 
121
  }
122
 
123
  function json(res, code, body) {
124
+ if (res.headersSent || res.writableEnded) return;
125
  const s = JSON.stringify(body);
126
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
127
  res.end(s);
128
  }
129
 
130
+ function clientIp(req) {
131
+ const xf = req.headers["x-forwarded-for"];
132
+ if (xf) return String(xf).split(",")[0].trim() || "0";
133
+ return req.socket && req.socket.remoteAddress || "0";
134
+ }
135
+
136
+ function errText(e) {
137
+ return String(e && (e.errorMessage || e.message || e) || "");
138
+ }
139
+
140
+ function isFileRef(e) {
141
+ return /FILE_REFERENCE/i.test(errText(e));
142
+ }
143
+
144
+ function isFlood(e) {
145
+ return /FLOOD_WAIT/i.test(errText(e)) || (e && e.seconds > 0 && /flood/i.test(String(e.className || e.name || "")));
146
+ }
147
+
148
+ function coolBot(bot, e) {
149
+ if (!bot) return;
150
+ const t = errText(e);
151
+ const m = /FLOOD_WAIT[_ ]?(\d+)/i.exec(t);
152
+ const sec = m ? Number(m[1]) : Number(e && e.seconds || 0);
153
+ if (sec > 8) bot.coolUntil = Date.now() + Math.min(sec, 90) * 1000;
154
+ if (/AUTH_KEY|SESSION_REVOKED|USER_DEACTIVATED|PHONE_NUMBER_BANNED/i.test(t)) bot.ready = false;
155
+ }
156
+
157
+ function botUsable(b) {
158
+ if (!b || !b.ready) return false;
159
+ if (b.coolUntil && Date.now() < b.coolUntil) return false;
160
+ if (b.client && b.client.connected === false) return false;
161
+ return b.load < BOT_MAX;
162
+ }
163
+
164
+ function pipeDead(req, res) {
165
+ return !!(req.destroyed || res.destroyed || res.writableEnded || res.writableFinished);
166
+ }
167
+
168
+ function waitDrain(req, res) {
169
+ return new Promise((resolve) => {
170
+ if (pipeDead(req, res)) return resolve();
171
+ let done = false;
172
+ const finish = () => {
173
+ if (done) return;
174
+ done = true;
175
+ clearTimeout(tm);
176
+ res.off("drain", finish);
177
+ res.off("close", finish);
178
+ req.off("close", finish);
179
+ resolve();
180
+ };
181
+ const tm = setTimeout(finish, 15000);
182
+ res.once("drain", finish);
183
+ res.once("close", finish);
184
+ req.once("close", finish);
185
+ });
186
+ }
187
+
188
+ function takeStream(ip) {
189
+ const n = (ipStreams.get(ip) || 0) + 1;
190
+ if (n > IP_STREAM_MAX) return false;
191
+ ipStreams.set(ip, n);
192
+ return true;
193
+ }
194
+
195
+ function freeStream(ip) {
196
+ const n = (ipStreams.get(ip) || 1) - 1;
197
+ if (n <= 0) ipStreams.delete(ip);
198
+ else ipStreams.set(ip, n);
199
+ }
200
+
201
+ function sweepMaps() {
202
  const now = Date.now();
203
+ if (fileCache.size) {
204
+ for (const [k, v] of fileCache) {
205
+ if (!v || !v.ts || now - v.ts > FILE_TTL) fileCache.delete(k);
206
+ }
207
+ if (fileCache.size > 400) {
208
+ const arr = [...fileCache.entries()].sort((a, b) => (a[1].ts || 0) - (b[1].ts || 0));
209
+ for (let i = 0; i < arr.length - 280; i++) fileCache.delete(arr[i][0]);
210
+ }
211
+ }
212
+ if (lvlCache.size > 2000) {
213
+ for (const [k, v] of lvlCache) {
214
+ if (!v || now - v.ts > LVL_TTL * 4) lvlCache.delete(k);
215
+ }
216
+ }
217
  if (rateMap.size > 4000) {
218
+ const slot = Math.floor(now / 60000);
219
  for (const k of rateMap.keys()) {
220
  if (!k.endsWith(":" + slot) && !k.endsWith(":" + (slot - 1))) rateMap.delete(k);
221
  }
222
  }
223
+ }
224
+
225
+ function withTime(p, ms, fallback) {
226
+ let t;
227
+ return Promise.race([
228
+ Promise.resolve(p).then((v) => {
229
+ clearTimeout(t);
230
+ return v;
231
+ }, () => {
232
+ clearTimeout(t);
233
+ return fallback;
234
+ }),
235
+ new Promise((r) => {
236
+ t = setTimeout(() => r(fallback), ms);
237
+ })
238
+ ]);
239
+ }
240
+
241
+ function busyJson(res) {
242
+ if (res.headersSent || res.writableEnded) return;
243
+ res.setHeader("Retry-After", "1");
244
+ json(res, 503, { error: "busy" });
245
+ }
246
+
247
+ function limited(ip) {
248
+ const now = Date.now();
249
+ const slot = Math.floor(now / 60000);
250
+ const key = ip + ":" + slot;
251
+ const n = (rateMap.get(key) || 0) + 1;
252
+ rateMap.set(key, n);
253
+ if (rateMap.size > 4000) sweepMaps();
254
  return n > 800;
255
  }
256
 
257
  async function googleCerts() {
258
  if (fbKeys.certs && Date.now() < fbKeys.exp) return fbKeys.certs;
259
+ const r = await fetch("https://www.googleapis.com/robot/v1/metadata/x509/securetoken@system.gserviceaccount.com", {
260
+ signal: AbortSignal.timeout(4000)
261
+ });
262
  if (!r.ok) throw new Error("certs");
263
  const certs = await r.json();
264
  const cc = r.headers.get("cache-control") || "";
 
301
  const r = await fetch(url, {
302
  method,
303
  headers: body == null ? undefined : { "Content-Type": "application/json" },
304
+ body: body == null ? undefined : JSON.stringify(body),
305
+ signal: AbortSignal.timeout(4000)
306
  });
307
  if (!r.ok) throw new Error("db " + r.status);
308
  const t = await r.text();
 
323
  async function accessLevel(uid) {
324
  if (!uid) return "anonymous";
325
  const hit = lvlCache.get(uid);
326
+ if (hit && Date.now() - hit.ts < LVL_TTL) return hit.lvl;
327
  let lvl = "registered";
328
  try {
329
+ const sub = await withTime(rtdb("users/" + uid + "/subscription", "GET"), 900, null);
330
  if (vipActive(sub)) lvl = "subscribed";
331
  } catch {}
332
  lvlCache.set(uid, { lvl, ts: Date.now() });
 
345
  return "video/mp4";
346
  }
347
 
348
+ function pickBot(preferIdx, skipIdx) {
349
  if (!bots.length) return null;
350
+ const pool = bots.filter((b) => botUsable(b) && b.idx !== skipIdx);
 
351
  if (!pool.length) return null;
352
  const min = Math.min(...pool.map((b) => b.load));
353
  if (preferIdx != null) {
 
360
  return bot;
361
  }
362
 
 
363
  async function startBot(token, idx) {
364
  const client = new TelegramClient(new StringSession(""), API_ID, API_HASH, {
365
+ connectionRetries: Infinity,
366
+ reconnectRetries: Infinity,
367
  retryDelay: 1500,
368
  autoReconnect: true,
369
  useWSS: true,
370
+ floodSleepThreshold: 8,
371
+ requestRetries: 3,
372
+ downloadRetries: 3,
373
+ maxConcurrentDownloads: 12,
374
+ downloadPool: { poolSize: 4, workers: 6, requestDeadlineMs: 18000 }
375
  });
376
  client.setLogLevel("error");
377
+ const bot = { client, token, idx, ready: false, load: 0, coolUntil: 0 };
378
  await client.start({ botAuthToken: token });
379
+ bot.ready = true;
380
+ bots.push(bot);
381
  }
382
 
383
  function dropFile(msgId, bot) {
 
391
  }
392
  }
393
 
394
+ async function loadFile(bot, msgId) {
 
 
 
395
  const msgs = await bot.client.getMessages(CHANNEL_ID, { ids: msgId });
396
  const msg = msgs && msgs[0];
397
  if (!msg || msg.deleted) throw new Error("missing");
 
422
  doc,
423
  ts: Date.now()
424
  };
425
+ fileCache.set(String(msgId) + ":" + bot.idx, rec);
426
  return rec;
427
  }
428
 
429
+ async function fileFromMsg(bot, msgId) {
430
+ const key = String(msgId) + ":" + bot.idx;
431
+ const hit = fileCache.get(key);
432
+ if (hit && Date.now() - hit.ts < FILE_TTL) return hit;
433
+ let p = inflightFile.get(key);
434
+ if (p) return p;
435
+ p = loadFile(bot, msgId).finally(() => inflightFile.delete(key));
436
+ inflightFile.set(key, p);
437
+ return p;
438
+ }
439
+
440
+ async function fileFromPool(msgId, prefer, skipIdx) {
441
+ const seen = new Set();
442
+ const order = [];
443
+ const first = prefer && botUsable(prefer) && prefer.idx !== skipIdx ? prefer : pickBot(prefer && prefer.idx, skipIdx);
444
+ if (first) order.push(first);
445
+ for (const b of bots) {
446
+ if (order.length >= 4) break;
447
+ if (order.includes(b) || !botUsable(b) || b.idx === skipIdx) continue;
448
+ order.push(b);
449
+ }
450
+ let last = null;
451
+ for (const bot of order) {
452
+ if (seen.has(bot.idx)) continue;
453
+ seen.add(bot.idx);
454
+ try {
455
+ const rec = await fileFromMsg(bot, msgId);
456
+ return { bot, rec };
457
+ } catch (e) {
458
+ last = e;
459
+ dropFile(msgId, bot);
460
+ coolBot(bot, e);
461
+ }
462
+ }
463
+ throw last || new Error("file");
464
+ }
465
+
466
  function durationFromMp4(buf) {
467
  const i = buf.indexOf(Buffer.from("mvhd"));
468
  if (i < 4 || i + 24 > buf.length) return 0;
 
492
  if (id) durCache.set(id, rec.duration);
493
  return;
494
  }
495
+ if (!rec.size || !botUsable(bot) || bot.load >= 6) return;
496
  const n = Math.min(rec.size, 1024 * 1024);
497
  const start = rec.size - n;
498
  let acc = Buffer.alloc(0);
499
  try {
500
+ for await (const c of rangeChunks(bot, rec, start, rec.size - 1, () => false)) {
501
  acc = Buffer.concat([acc, c]);
502
  rec.duration = durationFromMp4(acc);
503
  if (rec.duration > 0) {
 
545
  return MIN_ALIGN;
546
  }
547
 
548
+ async function* rangeChunks(bot, rec, start, end, stop) {
549
  let pos = start;
550
  while (pos <= end) {
551
+ if (stop && stop()) break;
552
  const aligned = Math.floor(pos / MIN_ALIGN) * MIN_ALIGN;
553
  let skip = pos - aligned;
554
  const pageEnd = Math.floor(aligned / MB) * MB + MB;
 
565
  });
566
  let sent = 0;
567
  for await (const chunk of it) {
568
+ if (stop && stop()) break;
569
  let buf = Buffer.from(chunk);
570
  if (skip) {
571
  if (buf.length <= skip) {
 
587
  }
588
  }
589
 
590
+ async function pipeRange(bot, rec, start, end, req, res, status, headers) {
591
  bot.load++;
592
+ const t0 = Date.now();
593
  try {
594
  if (res.socket) {
595
  res.socket.setNoDelay(true);
596
  res.socket.setKeepAlive(true, 15000);
597
  }
598
+ if (pipeDead(req, res)) return;
599
  res.writeHead(status, headers);
600
  if (typeof res.flushHeaders === "function") res.flushHeaders();
601
+ const stop = () => pipeDead(req, res) || Date.now() - t0 > PIPE_MS;
602
+ const gen = rangeChunks(bot, rec, start, end, stop);
603
  for await (const buf of gen) {
604
+ if (stop()) break;
605
  const ok = res.write(buf);
606
+ if (!ok) await waitDrain(req, res);
607
  }
608
  } finally {
609
  bot.load = Math.max(0, bot.load - 1);
610
+ if (!res.writableEnded && !res.destroyed) {
611
+ try { res.end(); } catch {}
612
+ }
613
  }
614
  }
615
 
616
+ async function readBody(req, max) {
617
+ const lim = max || BODY_MAX;
618
  const chunks = [];
619
+ let n = 0;
620
+ for await (const c of req) {
621
+ n += c.length;
622
+ if (n > lim) throw new Error("body");
623
+ chunks.push(c);
624
+ }
625
  return Buffer.concat(chunks);
626
  }
627
 
628
  async function handleGenerate(req, res, url) {
629
  if (!aesKey) return json(res, 503, { error: "misconfigured" });
630
+ const ip = clientIp(req);
631
+ if (limited(ip)) {
632
+ res.setHeader("Retry-After", "2");
633
+ return json(res, 429, { error: "rate_limited" });
634
+ }
635
  const path = url.searchParams.get("path") || "";
636
  const hash = (url.searchParams.get("hash") || "").toLowerCase();
637
  const m = /\/stream\/(\d+)/.exec(path);
 
640
  let uid = null;
641
  let lvl = "anonymous";
642
  try {
643
+ const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 1200, null);
644
  if (idp) {
645
  uid = idp.sub;
646
  lvl = await accessLevel(uid);
647
  }
648
  } catch {
649
+ lvl = uid ? "registered" : "anonymous";
650
  }
651
+ let got;
 
 
652
  try {
653
+ got = await fileFromPool(msgId, pickBot());
654
+ } catch {
655
+ return busyJson(res);
 
656
  }
657
+ const bot = got.bot;
658
+ const rec = got.rec;
659
+ if (rec.hash && rec.hash !== hash) return json(res, 400, { error: "hash" });
660
  const cachedDur = durCache.get(String(msgId));
661
  if (cachedDur) rec.duration = cachedDur;
662
  const playMime = httpVideoType(rec.mime, rec.name);
 
686
  res.writeHead(410);
687
  return res.end();
688
  }
689
+ const ip = clientIp(req);
690
+ if (!takeStream(ip)) {
691
+ res.setHeader("Retry-After", "1");
692
+ res.writeHead(429);
693
  return res.end();
694
  }
 
695
  try {
696
+ const prefer = Number.isInteger(ticket.b) ? ticket.b : undefined;
697
+ let bot = pickBot(prefer);
698
+ if (!bot) {
699
+ res.setHeader("Retry-After", "1");
700
+ res.writeHead(503);
701
+ return res.end();
702
+ }
703
+ let rec;
704
+ try {
705
+ rec = await fileFromMsg(bot, msgId);
706
+ } catch (e) {
707
+ dropFile(msgId, bot);
708
+ coolBot(bot, e);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
709
  try {
710
+ const got = await fileFromPool(msgId, null, bot.idx);
711
+ bot = got.bot;
712
+ rec = got.rec;
713
+ } catch {
714
+ res.writeHead(404);
715
+ return res.end();
716
+ }
717
+ }
718
+ if (ticket.h && rec.hash && ticket.h !== rec.hash) {
719
+ res.writeHead(403);
720
+ return res.end();
721
+ }
722
+ const size = rec.size;
723
+ const rng = parseRange(req.headers.range, size);
724
+ const headers = {
725
+ "Content-Type": httpVideoType(rec.mime, rec.name),
726
+ "Accept-Ranges": "bytes",
727
+ "Cache-Control": "private, max-age=60",
728
+ "Content-Disposition": "inline"
729
+ };
730
+ const partial = rng.start > 0 || rng.end < size - 1 || !!req.headers.range;
731
+ headers["Content-Length"] = String(rng.end - rng.start + 1);
732
+ if (partial) {
733
+ headers["Content-Range"] = "bytes " + rng.start + "-" + rng.end + "/" + size;
734
+ }
735
+ if (req.method === "HEAD") {
736
+ res.writeHead(partial ? 206 : 200, headers);
737
+ return res.end();
738
+ }
739
+ const status = partial ? 206 : 200;
740
+ try {
741
+ await pipeRange(bot, rec, rng.start, rng.end, req, res, status, headers);
742
+ } catch (e) {
743
+ coolBot(bot, e);
744
+ if (isFileRef(e)) dropFile(msgId, bot);
745
+ if (!res.headersSent && (isFileRef(e) || isFlood(e))) {
746
+ const next = pickBot(undefined, bot.idx);
747
+ if (next) {
748
+ try {
749
+ rec = await fileFromMsg(next, msgId);
750
+ await pipeRange(next, rec, rng.start, rng.end, req, res, status, headers);
751
+ return;
752
+ } catch (e2) {
753
+ coolBot(next, e2);
754
+ if (isFileRef(e2)) dropFile(msgId, next);
755
+ }
756
+ }
757
+ }
758
+ if (!res.headersSent) {
759
+ res.writeHead(502);
760
+ res.end();
761
+ } else if (!res.writableEnded && !res.destroyed) {
762
+ try { res.end(); } catch {}
763
+ }
764
  }
765
+ } finally {
766
+ freeStream(ip);
 
 
767
  }
768
  }
769
 
770
  async function handleVipStatus(req, res) {
771
  let lvl = "anonymous";
772
  try {
773
+ const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 1200, null);
774
  if (idp) {
775
  lvl = await accessLevel(idp.sub);
776
  let sub = null;
 
784
  async function handleVipStart(req, res) {
785
  if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
786
  if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
787
+ const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 1200, null);
788
  if (!idp) return json(res, 401, { error: "login" });
789
+ let body;
790
+ try {
791
+ body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
792
+ } catch {
793
+ return json(res, 400, { error: "body" });
794
+ }
795
  const plan = PLANS[body.plan];
796
  if (!plan) return json(res, 400, { error: "plan" });
797
  const r = await fetch("https://api.stripe.com/v1/checkout/sessions", {
 
812
  "metadata[plan]": body.plan,
813
  "payment_intent_data[metadata][uid]": idp.sub,
814
  "payment_intent_data[metadata][plan]": body.plan
815
+ }).toString(),
816
+ signal: AbortSignal.timeout(12000)
817
  });
818
  const d = await r.json();
819
  if (!r.ok || !d.id) return json(res, 400, { error: d.error && d.error.message || "Payment failed" });
 
823
  async function handleVipGo(req, res) {
824
  if (ROLE !== "indexer") return json(res, 409, { error: "use_s1" });
825
  if (!STRIPE_KEY) return json(res, 503, { error: "stripe_not_configured" });
826
+ const idp = await withTime(verifyIdToken(req.headers.authorization || ""), 1200, null);
827
  if (!idp) return json(res, 401, { error: "login" });
828
+ let body;
829
+ try {
830
+ body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
831
+ } catch {
832
+ return json(res, 400, { error: "body" });
833
+ }
834
  if (!body.sid) return json(res, 400, { error: "session" });
835
  const r = await fetch("https://api.stripe.com/v1/checkout/sessions/" + encodeURIComponent(body.sid), {
836
+ headers: { Authorization: "Bearer " + STRIPE_KEY },
837
+ signal: AbortSignal.timeout(12000)
838
  });
839
  const d = await r.json();
840
  if (!r.ok || !d.url) return json(res, 400, { error: d.error && d.error.message || "Payment failed" });
 
904
  }
905
 
906
  function handleHealth(res) {
907
+ sweepMaps();
908
+ for (const b of bots) {
909
+ if (b.client && b.client.connected === false) b.ready = false;
910
+ else if (b.client && b.client.connected !== false && !b.ready && !(b.coolUntil && Date.now() < b.coolUntil)) b.ready = true;
911
+ }
912
  json(res, 200, {
913
  ok: true,
914
  role: ROLE,
915
+ bots: bots.filter((b) => botUsable(b) || (b.ready && !(b.coolUntil && Date.now() < b.coolUntil))).length,
916
  load: bots.reduce((n, b) => n + b.load, 0),
917
  cap: bots.filter((b) => b.ready).length * BOT_MAX
918
  });
 
931
  }
932
 
933
  async function onReq(req, res) {
934
+ req.on("error", () => {});
935
+ res.on("error", () => {});
936
  cors(req, res);
937
  if (req.method === "OPTIONS") {
938
  res.writeHead(204);
 
990
  keepAlive: true,
991
  keepAliveTimeout: 65000,
992
  headersTimeout: 70000,
993
+ requestTimeout: 0,
994
+ connectionsCheckingInterval: 10000
995
  }, onReq);
996
+ srv.maxConnections = 480;
997
+ srv.on("clientError", (err, sock) => {
998
+ try {
999
+ if (sock.writable) sock.end("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
1000
+ } catch {}
1001
+ });
1002
  srv.listen(PORT, "0.0.0.0");
1003
  }
1004
 
1005
+ process.on("unhandledRejection", (e) => {
1006
+ process.stderr.write("rej " + errText(e) + "\n");
1007
+ });
1008
+ process.on("uncaughtException", (e) => {
1009
+ process.stderr.write("exc " + errText(e) + "\n");
1010
+ });
1011
+
1012
  main().catch((e) => {
1013
  process.stderr.write(String(e && e.stack || e) + "\n");
1014
  process.exit(1);