Spaces:
Running
Running
JOHN SILLVESTOR commited on
Update Node HTTP service
Browse files
server.js
CHANGED
|
@@ -4,7 +4,6 @@ const http = require("http");
|
|
| 4 |
const crypto = require("crypto");
|
| 5 |
const { TelegramClient, Api } = require("teleproto");
|
| 6 |
const { StringSession } = require("teleproto/sessions");
|
| 7 |
-
const bigInt = require("big-integer");
|
| 8 |
|
| 9 |
const PORT = Number(process.env.PORT || 7860);
|
| 10 |
const ORIGIN = process.env.ALLOWED_ORIGIN || "https://dublk2000.blogspot.com";
|
|
@@ -17,7 +16,7 @@ const HASH_LEN = 6;
|
|
| 17 |
const TOKEN_TTL = 900;
|
| 18 |
const CHUNK = 512 * 1024;
|
| 19 |
const MIN_ALIGN = 4096;
|
| 20 |
-
const BOT_MAX =
|
| 21 |
const FB_PROJECT = process.env.FIREBASE_PROJECT_ID || "";
|
| 22 |
const FB_DB = String(process.env.FIREBASE_DB_URL || "").replace(/\/?$/, "/");
|
| 23 |
const FB_SECRET = process.env.FIREBASE_DB_SECRET || "";
|
|
@@ -45,7 +44,6 @@ const bots = [];
|
|
| 45 |
const fileCache = new Map();
|
| 46 |
const rateMap = new Map();
|
| 47 |
let fbKeys = { certs: null, exp: 0 };
|
| 48 |
-
let rr = 0;
|
| 49 |
|
| 50 |
function timingSafeEq(a, b) {
|
| 51 |
const x = Buffer.from(String(a));
|
|
@@ -127,7 +125,7 @@ function limited(ip) {
|
|
| 127 |
if (!k.endsWith(":" + slot) && !k.endsWith(":" + (slot - 1))) rateMap.delete(k);
|
| 128 |
}
|
| 129 |
}
|
| 130 |
-
return n >
|
| 131 |
}
|
| 132 |
|
| 133 |
async function googleCerts() {
|
|
@@ -202,16 +200,16 @@ async function accessLevel(uid) {
|
|
| 202 |
return "registered";
|
| 203 |
}
|
| 204 |
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
const
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
if (
|
| 213 |
-
|
| 214 |
-
return
|
| 215 |
}
|
| 216 |
|
| 217 |
function pickBot() {
|
|
@@ -219,10 +217,8 @@ function pickBot() {
|
|
| 219 |
const live = bots.filter((b) => b.ready && b.load < BOT_MAX);
|
| 220 |
const pool = live.length ? live : bots.filter((b) => b.ready);
|
| 221 |
if (!pool.length) return null;
|
| 222 |
-
pool.sort((a, b) => a.load - b.load);
|
| 223 |
-
|
| 224 |
-
rr++;
|
| 225 |
-
return b;
|
| 226 |
}
|
| 227 |
|
| 228 |
async function startBot(token, idx) {
|
|
@@ -231,15 +227,27 @@ async function startBot(token, idx) {
|
|
| 231 |
retryDelay: 1500,
|
| 232 |
autoReconnect: true,
|
| 233 |
useWSS: true,
|
| 234 |
-
maxConcurrentDownloads:
|
|
|
|
| 235 |
});
|
| 236 |
client.setLogLevel("error");
|
| 237 |
await client.start({ botAuthToken: token });
|
| 238 |
bots.push({ client, token, idx, ready: true, load: 0 });
|
| 239 |
}
|
| 240 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
async function fileFromMsg(bot, msgId) {
|
| 242 |
-
const key = String(msgId);
|
| 243 |
const hit = fileCache.get(key);
|
| 244 |
if (hit && Date.now() - hit.ts < 8 * 60 * 1000) return hit;
|
| 245 |
const msgs = await bot.client.getMessages(CHANNEL_ID, { ids: msgId });
|
|
@@ -266,6 +274,7 @@ async function fileFromMsg(bot, msgId) {
|
|
| 266 |
id: String(doc.id),
|
| 267 |
hash: packHash(name, Number(doc.size || 0), doc.mimeType || "video/mp4", String(doc.id)),
|
| 268 |
dcId: doc.dcId,
|
|
|
|
| 269 |
ts: Date.now()
|
| 270 |
};
|
| 271 |
fileCache.set(key, rec);
|
|
@@ -289,11 +298,10 @@ async function* rangeChunks(bot, rec, start, end) {
|
|
| 289 |
let skip = start - aligned;
|
| 290 |
let sent = 0;
|
| 291 |
const need = end - start + 1;
|
| 292 |
-
const it = bot.client.iterDownload({
|
| 293 |
-
|
| 294 |
-
|
| 295 |
requestSize: CHUNK,
|
| 296 |
-
fileSize: bigInt(rec.size),
|
| 297 |
dcId: rec.dcId
|
| 298 |
});
|
| 299 |
for await (const chunk of it) {
|
|
@@ -320,7 +328,7 @@ async function pipeRange(bot, rec, start, end, res, status, headers) {
|
|
| 320 |
try {
|
| 321 |
const gen = rangeChunks(bot, rec, start, end);
|
| 322 |
const first = await gen.next();
|
| 323 |
-
if (first.done || !first.value) {
|
| 324 |
if (!res.headersSent) {
|
| 325 |
res.writeHead(502);
|
| 326 |
res.end();
|
|
@@ -328,6 +336,7 @@ async function pipeRange(bot, rec, start, end, res, status, headers) {
|
|
| 328 |
return;
|
| 329 |
}
|
| 330 |
res.writeHead(status, headers);
|
|
|
|
| 331 |
let ok = res.write(first.value);
|
| 332 |
if (!ok) await new Promise((r) => res.once("drain", r));
|
| 333 |
for await (const buf of gen) {
|
|
@@ -357,35 +366,29 @@ async function handleGenerate(req, res, url) {
|
|
| 357 |
if (!m || !/^[0-9a-f]{6}$/.test(hash)) return json(res, 400, { error: "bad_request" });
|
| 358 |
const msgId = Number(m[1]);
|
| 359 |
let uid = null;
|
| 360 |
-
let lvl = "anonymous";
|
| 361 |
try {
|
| 362 |
const idp = await verifyIdToken(req.headers.authorization || "");
|
| 363 |
-
if (idp)
|
| 364 |
-
|
| 365 |
-
lvl = await accessLevel(uid);
|
| 366 |
-
}
|
| 367 |
-
} catch {
|
| 368 |
-
lvl = "anonymous";
|
| 369 |
-
}
|
| 370 |
-
const qid = uid || "ip:" + ip;
|
| 371 |
-
if (!(await bumpQuota(qid, lvl))) return json(res, 403, { error: "preview limit" });
|
| 372 |
const bot = pickBot();
|
| 373 |
if (!bot) return json(res, 503, { error: "bots_offline" });
|
| 374 |
let rec;
|
| 375 |
try {
|
| 376 |
rec = await fileFromMsg(bot, msgId);
|
| 377 |
} catch (e) {
|
| 378 |
-
|
| 379 |
return json(res, 400, { error: "file" });
|
| 380 |
}
|
|
|
|
| 381 |
const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL;
|
| 382 |
-
const k = sealTicket({ m: msgId, h: hash, u: uid || "anon", l:
|
| 383 |
const host = "https://" + (req.headers.host || "localhost");
|
| 384 |
json(res, 200, {
|
| 385 |
url: host + "/stream/" + msgId + "?k=" + k,
|
| 386 |
fileSize: rec.size,
|
| 387 |
-
mime:
|
| 388 |
-
|
|
|
|
| 389 |
expiry: exp
|
| 390 |
});
|
| 391 |
}
|
|
@@ -410,14 +413,14 @@ async function handleStream(req, res, url, msgId) {
|
|
| 410 |
try {
|
| 411 |
rec = await fileFromMsg(bot, msgId);
|
| 412 |
} catch {
|
| 413 |
-
|
| 414 |
res.writeHead(404);
|
| 415 |
return res.end();
|
| 416 |
}
|
| 417 |
const size = rec.size;
|
| 418 |
const rng = parseRange(req.headers.range, size);
|
| 419 |
const headers = {
|
| 420 |
-
"Content-Type": rec.mime
|
| 421 |
"Accept-Ranges": "bytes",
|
| 422 |
"Cache-Control": "private, max-age=60",
|
| 423 |
"Content-Disposition": "inline"
|
|
@@ -442,7 +445,14 @@ async function handleStream(req, res, url, msgId) {
|
|
| 442 |
await pipeRange(bot, rec, rng.start, rng.end, res, status, headers);
|
| 443 |
} catch (e) {
|
| 444 |
const msg = String(e && e.errorMessage || e.message || e);
|
| 445 |
-
if (/FILE_REFERENCE/i.test(msg))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
if (!res.headersSent) {
|
| 447 |
res.writeHead(502);
|
| 448 |
res.end();
|
|
|
|
| 4 |
const crypto = require("crypto");
|
| 5 |
const { TelegramClient, Api } = require("teleproto");
|
| 6 |
const { StringSession } = require("teleproto/sessions");
|
|
|
|
| 7 |
|
| 8 |
const PORT = Number(process.env.PORT || 7860);
|
| 9 |
const ORIGIN = process.env.ALLOWED_ORIGIN || "https://dublk2000.blogspot.com";
|
|
|
|
| 16 |
const TOKEN_TTL = 900;
|
| 17 |
const CHUNK = 512 * 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 || "";
|
|
|
|
| 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));
|
|
|
|
| 125 |
if (!k.endsWith(":" + slot) && !k.endsWith(":" + (slot - 1))) rateMap.delete(k);
|
| 126 |
}
|
| 127 |
}
|
| 128 |
+
return n > 180;
|
| 129 |
}
|
| 130 |
|
| 131 |
async function googleCerts() {
|
|
|
|
| 200 |
return "registered";
|
| 201 |
}
|
| 202 |
|
| 203 |
+
function httpVideoType(mime, name) {
|
| 204 |
+
const s = String(mime || "").toLowerCase();
|
| 205 |
+
const n = String(name || "").toLowerCase();
|
| 206 |
+
if (s.includes("webm") || n.endsWith(".webm")) return "video/webm";
|
| 207 |
+
if (s.includes("ogg") || n.endsWith(".ogv") || n.endsWith(".ogg")) return "video/ogg";
|
| 208 |
+
if (s.includes("matroska") || n.endsWith(".mkv")) return "video/mp4";
|
| 209 |
+
if (s.includes("quicktime") || n.endsWith(".mov")) return "video/mp4";
|
| 210 |
+
if (s.startsWith("video/")) return s.split(";")[0].trim();
|
| 211 |
+
if (n.endsWith(".mp4") || n.endsWith(".m4v") || n.endsWith(".mpeg") || n.endsWith(".mpg")) return "video/mp4";
|
| 212 |
+
return "video/mp4";
|
| 213 |
}
|
| 214 |
|
| 215 |
function pickBot() {
|
|
|
|
| 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) {
|
|
|
|
| 227 |
retryDelay: 1500,
|
| 228 |
autoReconnect: true,
|
| 229 |
useWSS: true,
|
| 230 |
+
maxConcurrentDownloads: 8,
|
| 231 |
+
downloadPool: { poolSize: 2, workers: 4, requestDeadlineMs: 30000 }
|
| 232 |
});
|
| 233 |
client.setLogLevel("error");
|
| 234 |
await client.start({ botAuthToken: token });
|
| 235 |
bots.push({ client, token, idx, ready: true, load: 0 });
|
| 236 |
}
|
| 237 |
|
| 238 |
+
function dropFile(msgId, bot) {
|
| 239 |
+
if (bot) {
|
| 240 |
+
fileCache.delete(String(msgId) + ":" + bot.idx);
|
| 241 |
+
return;
|
| 242 |
+
}
|
| 243 |
+
const p = String(msgId) + ":";
|
| 244 |
+
for (const k of [...fileCache.keys()]) {
|
| 245 |
+
if (k === String(msgId) || k.startsWith(p)) fileCache.delete(k);
|
| 246 |
+
}
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
async function fileFromMsg(bot, msgId) {
|
| 250 |
+
const key = String(msgId) + ":" + bot.idx;
|
| 251 |
const hit = fileCache.get(key);
|
| 252 |
if (hit && Date.now() - hit.ts < 8 * 60 * 1000) return hit;
|
| 253 |
const msgs = await bot.client.getMessages(CHANNEL_ID, { ids: msgId });
|
|
|
|
| 274 |
id: String(doc.id),
|
| 275 |
hash: packHash(name, Number(doc.size || 0), doc.mimeType || "video/mp4", String(doc.id)),
|
| 276 |
dcId: doc.dcId,
|
| 277 |
+
doc,
|
| 278 |
ts: Date.now()
|
| 279 |
};
|
| 280 |
fileCache.set(key, rec);
|
|
|
|
| 298 |
let skip = start - aligned;
|
| 299 |
let sent = 0;
|
| 300 |
const need = end - start + 1;
|
| 301 |
+
const it = bot.client.iterDownload(rec.doc || rec.loc, {
|
| 302 |
+
offset: aligned,
|
| 303 |
+
limit: skip + need,
|
| 304 |
requestSize: CHUNK,
|
|
|
|
| 305 |
dcId: rec.dcId
|
| 306 |
});
|
| 307 |
for await (const chunk of it) {
|
|
|
|
| 328 |
try {
|
| 329 |
const gen = rangeChunks(bot, rec, start, end);
|
| 330 |
const first = await gen.next();
|
| 331 |
+
if (first.done || !first.value || !first.value.length) {
|
| 332 |
if (!res.headersSent) {
|
| 333 |
res.writeHead(502);
|
| 334 |
res.end();
|
|
|
|
| 336 |
return;
|
| 337 |
}
|
| 338 |
res.writeHead(status, headers);
|
| 339 |
+
if (typeof res.flushHeaders === "function") res.flushHeaders();
|
| 340 |
let ok = res.write(first.value);
|
| 341 |
if (!ok) await new Promise((r) => res.once("drain", r));
|
| 342 |
for await (const buf of gen) {
|
|
|
|
| 366 |
if (!m || !/^[0-9a-f]{6}$/.test(hash)) return json(res, 400, { error: "bad_request" });
|
| 367 |
const msgId = Number(m[1]);
|
| 368 |
let uid = null;
|
|
|
|
| 369 |
try {
|
| 370 |
const idp = await verifyIdToken(req.headers.authorization || "");
|
| 371 |
+
if (idp) uid = idp.sub;
|
| 372 |
+
} catch {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
const bot = pickBot();
|
| 374 |
if (!bot) return json(res, 503, { error: "bots_offline" });
|
| 375 |
let rec;
|
| 376 |
try {
|
| 377 |
rec = await fileFromMsg(bot, msgId);
|
| 378 |
} catch (e) {
|
| 379 |
+
dropFile(msgId, bot);
|
| 380 |
return json(res, 400, { error: "file" });
|
| 381 |
}
|
| 382 |
+
const playMime = httpVideoType(rec.mime, rec.name);
|
| 383 |
const exp = Math.floor(Date.now() / 1000) + TOKEN_TTL;
|
| 384 |
+
const k = sealTicket({ m: msgId, h: hash, u: uid || "anon", l: "subscribed", e: exp, s: rec.size, n: playMime });
|
| 385 |
const host = "https://" + (req.headers.host || "localhost");
|
| 386 |
json(res, 200, {
|
| 387 |
url: host + "/stream/" + msgId + "?k=" + k,
|
| 388 |
fileSize: rec.size,
|
| 389 |
+
mime: playMime,
|
| 390 |
+
name: rec.name,
|
| 391 |
+
accessLevel: "subscribed",
|
| 392 |
expiry: exp
|
| 393 |
});
|
| 394 |
}
|
|
|
|
| 413 |
try {
|
| 414 |
rec = await fileFromMsg(bot, msgId);
|
| 415 |
} catch {
|
| 416 |
+
dropFile(msgId, bot);
|
| 417 |
res.writeHead(404);
|
| 418 |
return res.end();
|
| 419 |
}
|
| 420 |
const size = rec.size;
|
| 421 |
const rng = parseRange(req.headers.range, size);
|
| 422 |
const headers = {
|
| 423 |
+
"Content-Type": httpVideoType(rec.mime, rec.name),
|
| 424 |
"Accept-Ranges": "bytes",
|
| 425 |
"Cache-Control": "private, max-age=60",
|
| 426 |
"Content-Disposition": "inline"
|
|
|
|
| 445 |
await pipeRange(bot, rec, rng.start, rng.end, res, status, headers);
|
| 446 |
} catch (e) {
|
| 447 |
const msg = String(e && e.errorMessage || e.message || e);
|
| 448 |
+
if (/FILE_REFERENCE/i.test(msg)) dropFile(msgId, bot);
|
| 449 |
+
if (/FILE_REFERENCE/i.test(msg) && !res.headersSent) {
|
| 450 |
+
try {
|
| 451 |
+
rec = await fileFromMsg(bot, msgId);
|
| 452 |
+
await pipeRange(bot, rec, rng.start, rng.end, res, status, headers);
|
| 453 |
+
return;
|
| 454 |
+
} catch {}
|
| 455 |
+
}
|
| 456 |
if (!res.headersSent) {
|
| 457 |
res.writeHead(502);
|
| 458 |
res.end();
|