JOHN SILLVESTOR commited on
Commit
011d6da
·
verified ·
1 Parent(s): 2987850

Update Node HTTP service

Browse files
Files changed (1) hide show
  1. server.js +81 -30
server.js CHANGED
@@ -16,7 +16,10 @@ const HASH_LEN = 6;
16
  const TOKEN_TTL = 900;
17
  const CHUNK = 64 * 1024;
18
  const MIN_ALIGN = 4096;
19
- const BOT_MAX = 10;
 
 
 
20
  const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "";
21
  const FB_DB = String(process.env.FIREBASE_DB_URL || "").replace(/\/?$/, "/");
22
  const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
@@ -42,8 +45,11 @@ const hmacKey = STREAM_SECRET
42
 
43
  const bots = [];
44
  const fileCache = new Map();
 
 
45
  const rateMap = new Map();
46
  let fbKeys = { certs: null, exp: 0 };
 
47
 
48
  function timingSafeEq(a, b) {
49
  const x = Buffer.from(String(a));
@@ -193,11 +199,15 @@ function vipActive(sub) {
193
 
194
  async function accessLevel(uid) {
195
  if (!uid) return "anonymous";
 
 
 
196
  try {
197
  const sub = await rtdb("users/" + uid + "/subscription", "GET");
198
- if (vipActive(sub)) return "subscribed";
199
  } catch {}
200
- return "registered";
 
201
  }
202
 
203
  function httpVideoType(mime, name) {
@@ -212,13 +222,31 @@ function httpVideoType(mime, name) {
212
  return "video/mp4";
213
  }
214
 
215
- function pickBot() {
216
  if (!bots.length) return null;
 
 
 
 
217
  const live = bots.filter((b) => b.ready && b.load < BOT_MAX);
218
  const pool = live.length ? live : bots.filter((b) => b.ready);
219
  if (!pool.length) return null;
220
- pool.sort((a, b) => a.load - b.load || a.idx - b.idx);
221
- return pool[0];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  }
223
 
224
  async function startBot(token, idx) {
@@ -303,8 +331,17 @@ function durationFromMp4(buf) {
303
  }
304
  }
305
 
306
- async function fillDuration(bot, rec) {
307
- if (rec.duration > 0 || !rec.size) return;
 
 
 
 
 
 
 
 
 
308
  const n = Math.min(rec.size, 1024 * 1024);
309
  const start = rec.size - n;
310
  let acc = Buffer.alloc(0);
@@ -312,7 +349,10 @@ async function fillDuration(bot, rec) {
312
  for await (const c of rangeChunks(bot, rec, start, rec.size - 1)) {
313
  acc = Buffer.concat([acc, c]);
314
  rec.duration = durationFromMp4(acc);
315
- if (rec.duration > 0) return;
 
 
 
316
  if (acc.length >= n) return;
317
  }
318
  } catch {}
@@ -343,9 +383,10 @@ async function* rangeChunks(bot, rec, start, end) {
343
  let skip = start - aligned;
344
  let sent = 0;
345
  const need = end - start + 1;
346
- let reqSize = CHUNK;
 
347
  const want = skip + need;
348
- if (want < CHUNK) {
349
  reqSize = Math.max(MIN_ALIGN, Math.ceil(want / MIN_ALIGN) * MIN_ALIGN);
350
  }
351
  const it = bot.client.iterDownload(rec.doc || rec.loc, {
@@ -406,23 +447,30 @@ async function handleGenerate(req, res, url) {
406
  if (!m || !/^[0-9a-f]{6}$/.test(hash)) return json(res, 400, { error: "bad_request" });
407
  const msgId = Number(m[1]);
408
  let uid = null;
 
409
  try {
410
  const idp = await verifyIdToken(req.headers.authorization || "");
411
- if (idp) uid = idp.sub;
412
- } catch {}
 
 
 
 
 
413
  const bot = pickBot();
414
  if (!bot) return json(res, 503, { error: "bots_offline" });
415
  let rec;
416
  try {
417
  rec = await fileFromMsg(bot, msgId);
418
- await fillDuration(bot, rec);
419
  } catch (e) {
420
  dropFile(msgId, bot);
421
  return json(res, 400, { error: "file" });
422
  }
 
 
423
  const playMime = httpVideoType(rec.mime, rec.name);
424
  const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL;
425
- const k = sealTicket({ m: msgId, h: hash, u: uid || "anon", l: "subscribed", e: exp, s: rec.size, n: playMime });
426
  const host = "https://" + (req.headers.host || "localhost");
427
  json(res, 200, {
428
  url: host + "/stream/" + msgId + "?k=" + k,
@@ -430,9 +478,10 @@ async function handleGenerate(req, res, url) {
430
  mime: playMime,
431
  name: rec.name,
432
  duration: rec.duration || 0,
433
- accessLevel: "subscribed",
434
  expiry: exp
435
  });
 
436
  }
437
 
438
  async function handleStream(req, res, url, msgId) {
@@ -446,7 +495,7 @@ async function handleStream(req, res, url, msgId) {
446
  res.writeHead(410);
447
  return res.end();
448
  }
449
- const bot = pickBot();
450
  if (!bot) {
451
  res.writeHead(503);
452
  return res.end();
@@ -461,28 +510,29 @@ async function handleStream(req, res, url, msgId) {
461
  }
462
  const size = rec.size;
463
  const rng = parseRange(req.headers.range, size);
 
 
 
 
 
 
 
464
  const headers = {
465
  "Content-Type": httpVideoType(rec.mime, rec.name),
466
  "Accept-Ranges": "bytes",
467
  "Cache-Control": "private, max-age=60",
468
  "Content-Disposition": "inline"
469
  };
470
- if (req.method === "HEAD") {
471
- headers["Content-Length"] = String(rng.partial ? rng.end - rng.start + 1 : size);
472
- if (rng.partial) {
473
- headers["Content-Range"] = "bytes " + rng.start + "-" + rng.end + "/" + size;
474
- res.writeHead(206, headers);
475
- } else {
476
- res.writeHead(200, headers);
477
- }
478
- return res.end();
479
- }
480
  headers["Content-Length"] = String(rng.end - rng.start + 1);
481
- let status = 200;
482
- if (rng.partial || req.headers.range) {
483
  headers["Content-Range"] = "bytes " + rng.start + "-" + rng.end + "/" + size;
484
- status = 206;
485
  }
 
 
 
 
 
486
  try {
487
  await pipeRange(bot, rec, rng.start, rng.end, res, status, headers);
488
  } catch (e) {
@@ -576,6 +626,7 @@ async function grantVip(uid, planKey) {
576
  updatedAt: now
577
  };
578
  await rtdb("users/" + uid + "/subscription", "PUT", sub);
 
579
  return sub;
580
  }
581
 
 
16
  const TOKEN_TTL = 900;
17
  const CHUNK = 64 * 1024;
18
  const MIN_ALIGN = 4096;
19
+ const BOT_MAX = 12;
20
+ const FAST_CHUNK = 512 * 1024;
21
+ const MOOV_TAIL = 1024 * 1024;
22
+ const PREVIEW_PCT = { anonymous: 30, registered: 60, subscribed: 100 };
23
  const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "";
24
  const FB_DB = String(process.env.FIREBASE_DB_URL || "").replace(/\/?$/, "/");
25
  const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
 
45
 
46
  const bots = [];
47
  const fileCache = new Map();
48
+ const durCache = new Map();
49
+ const lvlCache = new Map();
50
  const rateMap = new Map();
51
  let fbKeys = { certs: null, exp: 0 };
52
+ let rr = 0;
53
 
54
  function timingSafeEq(a, b) {
55
  const x = Buffer.from(String(a));
 
199
 
200
  async function accessLevel(uid) {
201
  if (!uid) return "anonymous";
202
+ const hit = lvlCache.get(uid);
203
+ if (hit && Date.now() - hit.ts < 25000) return hit.lvl;
204
+ let lvl = "registered";
205
  try {
206
  const sub = await rtdb("users/" + uid + "/subscription", "GET");
207
+ if (vipActive(sub)) lvl = "subscribed";
208
  } catch {}
209
+ lvlCache.set(uid, { lvl, ts: Date.now() });
210
+ return lvl;
211
  }
212
 
213
  function httpVideoType(mime, name) {
 
222
  return "video/mp4";
223
  }
224
 
225
+ function pickBot(preferIdx) {
226
  if (!bots.length) return null;
227
+ if (preferIdx != null) {
228
+ const sticky = bots.find((b) => b.idx === preferIdx && b.ready && b.load < BOT_MAX);
229
+ if (sticky) return sticky;
230
+ }
231
  const live = bots.filter((b) => b.ready && b.load < BOT_MAX);
232
  const pool = live.length ? live : bots.filter((b) => b.ready);
233
  if (!pool.length) return null;
234
+ const min = Math.min(...pool.map((b) => b.load));
235
+ const even = pool.filter((b) => b.load === min);
236
+ const bot = even[rr % even.length];
237
+ rr += 1;
238
+ return bot;
239
+ }
240
+
241
+ function clampPreviewRange(start, end, size, lvl) {
242
+ const pct = PREVIEW_PCT[lvl] || 30;
243
+ if (pct >= 100 || size <= 0) return { start, end, deny: false };
244
+ const headEnd = Math.max(0, Math.floor((size * pct) / 100) - 1);
245
+ const tailStart = Math.max(0, size - MOOV_TAIL);
246
+ if (start >= tailStart) return { start, end, deny: false };
247
+ if (end <= headEnd) return { start, end, deny: false };
248
+ if (start <= headEnd) return { start, end: headEnd, deny: false };
249
+ return { start, end, deny: true };
250
  }
251
 
252
  async function startBot(token, idx) {
 
331
  }
332
  }
333
 
334
+ async function fillDuration(bot, rec, msgId) {
335
+ const id = String(msgId || rec.id || "");
336
+ if (id && durCache.has(id)) {
337
+ rec.duration = durCache.get(id);
338
+ return;
339
+ }
340
+ if (rec.duration > 0) {
341
+ if (id) durCache.set(id, rec.duration);
342
+ return;
343
+ }
344
+ if (!rec.size) return;
345
  const n = Math.min(rec.size, 1024 * 1024);
346
  const start = rec.size - n;
347
  let acc = Buffer.alloc(0);
 
349
  for await (const c of rangeChunks(bot, rec, start, rec.size - 1)) {
350
  acc = Buffer.concat([acc, c]);
351
  rec.duration = durationFromMp4(acc);
352
+ if (rec.duration > 0) {
353
+ if (id) durCache.set(id, rec.duration);
354
+ return;
355
+ }
356
  if (acc.length >= n) return;
357
  }
358
  } catch {}
 
383
  let skip = start - aligned;
384
  let sent = 0;
385
  const need = end - start + 1;
386
+ const tailZone = rec.size > 0 && aligned >= Math.max(0, rec.size - 2 * 1024 * 1024);
387
+ let reqSize = tailZone ? CHUNK : FAST_CHUNK;
388
  const want = skip + need;
389
+ if (want < reqSize) {
390
  reqSize = Math.max(MIN_ALIGN, Math.ceil(want / MIN_ALIGN) * MIN_ALIGN);
391
  }
392
  const it = bot.client.iterDownload(rec.doc || rec.loc, {
 
447
  if (!m || !/^[0-9a-f]{6}$/.test(hash)) return json(res, 400, { error: "bad_request" });
448
  const msgId = Number(m[1]);
449
  let uid = null;
450
+ let lvl = "anonymous";
451
  try {
452
  const idp = await verifyIdToken(req.headers.authorization || "");
453
+ if (idp) {
454
+ uid = idp.sub;
455
+ lvl = await accessLevel(uid);
456
+ }
457
+ } catch {
458
+ lvl = "anonymous";
459
+ }
460
  const bot = pickBot();
461
  if (!bot) return json(res, 503, { error: "bots_offline" });
462
  let rec;
463
  try {
464
  rec = await fileFromMsg(bot, msgId);
 
465
  } catch (e) {
466
  dropFile(msgId, bot);
467
  return json(res, 400, { error: "file" });
468
  }
469
+ const cachedDur = durCache.get(String(msgId));
470
+ if (cachedDur) rec.duration = cachedDur;
471
  const playMime = httpVideoType(rec.mime, rec.name);
472
  const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL;
473
+ const k = sealTicket({ m: msgId, h: hash, u: uid || "anon", l: lvl, b: bot.idx, e: exp, s: rec.size, n: playMime });
474
  const host = "https://" + (req.headers.host || "localhost");
475
  json(res, 200, {
476
  url: host + "/stream/" + msgId + "?k=" + k,
 
478
  mime: playMime,
479
  name: rec.name,
480
  duration: rec.duration || 0,
481
+ accessLevel: lvl,
482
  expiry: exp
483
  });
484
+ if (!rec.duration) fillDuration(bot, rec, msgId).catch(function () {});
485
  }
486
 
487
  async function handleStream(req, res, url, msgId) {
 
495
  res.writeHead(410);
496
  return res.end();
497
  }
498
+ const bot = pickBot(Number.isInteger(ticket.b) ? ticket.b : undefined);
499
  if (!bot) {
500
  res.writeHead(503);
501
  return res.end();
 
510
  }
511
  const size = rec.size;
512
  const rng = parseRange(req.headers.range, size);
513
+ const cap = clampPreviewRange(rng.start, rng.end, size, ticket.l || "anonymous");
514
+ if (cap.deny) {
515
+ res.writeHead(416, { "Content-Range": "bytes */" + size, "Accept-Ranges": "bytes" });
516
+ return res.end();
517
+ }
518
+ rng.start = cap.start;
519
+ rng.end = cap.end;
520
  const headers = {
521
  "Content-Type": httpVideoType(rec.mime, rec.name),
522
  "Accept-Ranges": "bytes",
523
  "Cache-Control": "private, max-age=60",
524
  "Content-Disposition": "inline"
525
  };
526
+ const partial = rng.start > 0 || rng.end < size - 1 || !!req.headers.range;
 
 
 
 
 
 
 
 
 
527
  headers["Content-Length"] = String(rng.end - rng.start + 1);
528
+ if (partial) {
 
529
  headers["Content-Range"] = "bytes " + rng.start + "-" + rng.end + "/" + size;
 
530
  }
531
+ if (req.method === "HEAD") {
532
+ res.writeHead(partial ? 206 : 200, headers);
533
+ return res.end();
534
+ }
535
+ const status = partial ? 206 : 200;
536
  try {
537
  await pipeRange(bot, rec, rng.start, rng.end, res, status, headers);
538
  } catch (e) {
 
626
  updatedAt: now
627
  };
628
  await rtdb("users/" + uid + "/subscription", "PUT", sub);
629
+ lvlCache.delete(uid);
630
  return sub;
631
  }
632