This repository was archived by the owner on Jun 30, 2026. It is now read-only.
forked from 6roach/clipper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclipper.js
More file actions
1578 lines (1398 loc) · 60.5 KB
/
Copy pathclipper.js
File metadata and controls
1578 lines (1398 loc) · 60.5 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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
require('dotenv').config();
const express = require('express');
const { spawn } = require('child_process');
const ffmpeg = require('fluent-ffmpeg');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
const fetch = (...a) => import('node-fetch').then(({ default: f }) => f(...a));
const Database = require('better-sqlite3');
/* ============================================================
CONFIG
============================================================ */
const CLIP_OUTPUT_DIR = process.env.CLIP_OUTPUT_DIR || path.join(__dirname, 'public', 'clips');
const CLIP_TEMP_DIR = process.env.CLIP_TEMP_DIR || path.join(__dirname, 'temp');
const KICK_API_BASE = process.env.KICK_API_BASE || 'https://api.kick.com';
const KICK_AUTH_BASE = process.env.KICK_AUTH_BASE || 'https://id.kick.com';
const KICK_WEB_BASE = process.env.KICK_WEB_BASE || 'https://kick.com';
const KICK_CLIENT_ID = process.env.KICK_CLIENT_ID || '';
const KICK_CLIENT_SECRET = process.env.KICK_CLIENT_SECRET || '';
const TWITCH_WEB_BASE = process.env.TWITCH_WEB_BASE || 'https://www.twitch.tv';
const YOUTUBE_API_BASE = process.env.YOUTUBE_API_BASE || 'https://www.googleapis.com/youtube/v3';
const YOUTUBE_API_KEY = process.env.YOUTUBE_API_KEY || '';
const CATBOX_USERHASH = process.env.CATBOX_USERHASH || '';
const VIDEY_API_KEY = process.env.VIDEY_API_KEY || '';
const VIDEY_API_SECRET = process.env.VIDEY_API_SECRET || '';
const MAX_CLIP_SECONDS = Number(process.env.MAX_CLIP_SECONDS) || 300;
const DEFAULT_CLIP_SECS = Number(process.env.DEFAULT_CLIP_SECS) || 60;
const DB_PATH = process.env.DB_PATH || path.join(__dirname, 'clipper.db');
const FFMPEG_THREADS = Number(process.env.FFMPEG_THREADS) || 0; // 0 = ffmpeg auto
const YTDLP_CONCURRENT_FRAGS = Number(process.env.YTDLP_CONCURRENT_FRAGS) || 1;
const USER_AGENT = process.env.USER_AGENT || '';
/* ── Security ─────────────────────────────────────────────── */
// Set CLIPPER_API_KEY in your environment to require an Authorization header
// on every mutating request (POST, DELETE). Server will refuse to start without it.
const API_KEY = process.env.CLIPPER_API_KEY || '';
if (!API_KEY || API_KEY.length < 32) {
console.error(
'[Clipper] FATAL: CLIPPER_API_KEY must be set to a string of at least 32 characters.\n' +
' Generate one with: node -e "require(\'crypto\').randomBytes(32).toString(\'hex\')|0 && process.stdout.write(require(\'crypto\').randomBytes(32).toString(\'hex\'))"'
);
process.exit(1);
}
// Separate browser-facing key so the real CLIPPER_API_KEY (admin-level) is
// never sent to the browser. Set CLIPPER_BROWSER_KEY in your .env to a
// different value; if omitted it falls back to CLIPPER_API_KEY so existing
// deployments keep working without any changes.
const BROWSER_KEY = process.env.CLIPPER_BROWSER_KEY || API_KEY;
// In-memory session store: token → expiresAt (ms)
// Sessions last 8 hours; they are also pruned every 30 minutes.
const SESSION_TTL_MS = 8 * 3_600_000;
const _sessions = new Map(); // token → expiresAt
function createSession() {
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = Date.now() + SESSION_TTL_MS;
_sessions.set(token, expiresAt);
return token;
}
function isValidSession(token) {
if (!token) return false;
const exp = _sessions.get(token);
if (!exp) return false;
if (Date.now() > exp) { _sessions.delete(token); return false; }
return true;
}
// Prune expired sessions periodically
setInterval(() => {
const now = Date.now();
for (const [t, exp] of _sessions) { if (now > exp) _sessions.delete(t); }
}, 30 * 60_000).unref();
// How long to keep completed clip files on disk before auto-deleting.
// Keeps disk usage bounded with multiple users. Override with CLIP_MAX_AGE_HOURS.
const CLIP_MAX_AGE_MS = (Number(process.env.CLIP_MAX_AGE_HOURS) || 1) * 3_600_000;
// Maximum simultaneous capture jobs (yt-dlp + ffmpeg processes).
const MAX_CONCURRENT_JOBS = Number(process.env.MAX_CONCURRENT_JOBS) || 5;
// Simple in-memory rate limiter: max requests per window per IP.
const RATE_LIMIT_WINDOW_MS = Number(process.env.RATE_LIMIT_WINDOW_MS) || 60_000; // 1 min
// POST /clip: how many new clip jobs each IP can start per window.
const RATE_LIMIT_MAX_CLIPS = Number(process.env.RATE_LIMIT_MAX_CLIPS) || 5;
// GET poll/status endpoints: much higher ceiling so polling every 2 s never
// triggers a 429 even with 5 simultaneous users on the same IP.
const RATE_LIMIT_MAX_POLLS = Number(process.env.RATE_LIMIT_MAX_POLLS) || 300;
// Allowed HTTPS hostnames for user-supplied stream URLs (SSRF guard).
// Add more if you need to support additional platforms.
const ALLOWED_STREAM_HOSTS = new Set([
'www.youtube.com', 'youtube.com', 'm.youtube.com',
'www.twitch.tv', 'twitch.tv',
'kick.com', 'www.kick.com', 'm.kick.com',
]);
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const VALID_PLATFORMS = ['youtube', 'twitch', 'kick'];
const VALID_QUALITIES = ['low', 'medium', 'high'];
/* Ensure directories exist */
[CLIP_OUTPUT_DIR, CLIP_TEMP_DIR].forEach(d => {
if (!fs.existsSync(d)) fs.mkdirSync(d, { recursive: true });
});
/* ============================================================
JOB STORE (SQLite-backed)
============================================================ */
/**
* @typedef {Object} ClipJob
* @property {string} id
* @property {string} platform
* @property {string} username
* @property {number} duration
* @property {'pending'|'resolving'|'capturing'|'encoding'|'ready'|'error'} status
* @property {number} progress 0–100
* @property {string|null} outputFile absolute path to finished mp4
* @property {string|null} downloadUrl relative URL the client can use
* @property {string|null} error
* @property {string} createdAt ISO timestamp
*/
const db = new Database(DB_PATH);
// WAL mode for better concurrent read/write performance
db.pragma('journal_mode = WAL');
db.exec(`
CREATE TABLE IF NOT EXISTS jobs (
id TEXT PRIMARY KEY,
platform TEXT NOT NULL,
username TEXT NOT NULL,
duration INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
progress INTEGER NOT NULL DEFAULT 0,
outputFile TEXT,
downloadUrl TEXT,
error TEXT,
createdAt TEXT NOT NULL,
startOffset INTEGER NOT NULL DEFAULT 0
)
`);
// Add startOffset column to existing DBs that pre-date this migration
try {
db.exec(`ALTER TABLE jobs ADD COLUMN startOffset INTEGER NOT NULL DEFAULT 0`);
} catch (_) { /* column already exists — ignore */ }
/* ── Clipped-users registry ───────────────────────────────── */
db.exec(`
CREATE TABLE IF NOT EXISTS clipped_users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
platform TEXT NOT NULL,
url TEXT,
clip_count INTEGER NOT NULL DEFAULT 1,
total_duration INTEGER NOT NULL DEFAULT 0,
first_clipped_at TEXT NOT NULL,
last_clipped_at TEXT NOT NULL,
UNIQUE (username, platform)
)
`);
// Add url column to existing DBs that pre-date this migration
try {
db.exec(`ALTER TABLE clipped_users ADD COLUMN url TEXT`);
} catch (_) { /* column already exists — ignore */ }
/* ── Per-platform aggregate stats ────────────────────────── */
db.exec(`
CREATE TABLE IF NOT EXISTS platform_stats (
platform TEXT PRIMARY KEY,
clip_count INTEGER NOT NULL DEFAULT 0,
total_duration INTEGER NOT NULL DEFAULT 0,
unique_users INTEGER NOT NULL DEFAULT 0,
last_activity_at TEXT NOT NULL
)
`);
/* ── Prepared statements for user/platform tracking ─────── */
const stmtUpsertUser = db.prepare(`
INSERT INTO clipped_users (username, platform, url, clip_count, total_duration, first_clipped_at, last_clipped_at)
VALUES (@username, @platform, @url, 1, @duration, @now, @now)
ON CONFLICT(username, platform) DO UPDATE SET
clip_count = clip_count + 1,
total_duration = total_duration + @duration,
url = COALESCE(@url, url),
last_clipped_at = @now
`);
const stmtUpsertPlatform = db.prepare(`
INSERT INTO platform_stats (platform, clip_count, total_duration, unique_users, last_activity_at)
VALUES (@platform, 1, @duration, 1, @now)
ON CONFLICT(platform) DO UPDATE SET
clip_count = clip_count + 1,
total_duration = total_duration + @duration,
unique_users = (SELECT COUNT(DISTINCT username) FROM clipped_users WHERE platform = @platform),
last_activity_at = @now
`);
const stmtAllUsers = db.prepare('SELECT * FROM clipped_users ORDER BY last_clipped_at DESC');
const stmtUsersByPlat = db.prepare('SELECT * FROM clipped_users WHERE platform = ? ORDER BY last_clipped_at DESC');
const stmtAllPlatStats = db.prepare('SELECT * FROM platform_stats ORDER BY clip_count DESC');
/**
* Record a successfully completed clip into the users + platform registries.
* Called once a job transitions to 'ready'.
*/
const recordClipCompletion = db.transaction((username, platform, duration, url = null) => {
const now = new Date().toISOString();
stmtUpsertUser.run({ username, platform, url, duration, now });
stmtUpsertPlatform.run({ platform, duration, now });
});
// Prepared statements
const stmtInsert = db.prepare(`
INSERT INTO jobs (id, platform, username, duration, status, progress, outputFile, downloadUrl, error, createdAt, startOffset)
VALUES (@id, @platform, @username, @duration, @status, @progress, @outputFile, @downloadUrl, @error, @createdAt, @startOffset)
`);
const stmtSelectOne = db.prepare('SELECT * FROM jobs WHERE id = ?');
const stmtUpdate = db.prepare(`
UPDATE jobs
SET status = COALESCE(@status, status),
progress = COALESCE(@progress, progress),
outputFile = COALESCE(@outputFile, outputFile),
downloadUrl = COALESCE(@downloadUrl, downloadUrl),
error = COALESCE(@error, error),
startOffset = COALESCE(@startOffset, startOffset)
WHERE id = @id
`);
const stmtDelete = db.prepare('DELETE FROM jobs WHERE id = ?');
const stmtCount = db.prepare('SELECT COUNT(*) AS n FROM jobs');
const stmtRecent = db.prepare('SELECT * FROM jobs ORDER BY createdAt DESC LIMIT 100');
/** Parse a raw DB row back into a ClipJob (coerce integer progress). */
function rowToJob(row) {
if (!row) return null;
return { ...row, progress: Number(row.progress), duration: Number(row.duration) };
}
/**
* Thin compatibility shim so the rest of the file can still call
* jobs.get / jobs.set / jobs.delete / jobs.values / jobs.size.
*/
const jobs = {
get: (id) => rowToJob(stmtSelectOne.get(id)),
set: (_id, job) => stmtInsert.run(job), // only used by createJob
delete: (id) => { stmtDelete.run(id); },
values: () => stmtRecent.all().map(rowToJob),
get size() { return stmtCount.get().n; },
};
function createJob(platform, username, duration) {
const id = uuidv4();
/** @type {ClipJob} */
const job = {
id,
platform,
username,
duration,
status: 'pending',
progress: 0,
outputFile: null,
downloadUrl: null,
error: null,
createdAt: new Date().toISOString(),
startOffset: 0,
};
stmtInsert.run(job);
return job;
}
function updateJob(id, patch) {
stmtUpdate.run({
id,
status: patch.status ?? null,
progress: patch.progress ?? null,
outputFile: patch.outputFile ?? null,
downloadUrl: patch.downloadUrl ?? null,
error: patch.error ?? null,
startOffset: patch.startOffset ?? null,
});
}
/* ── Auto-cleanup of old clips ────────────────────────────── */
/**
* Delete clips (file + DB row) older than CLIP_MAX_AGE_HOURS.
* Runs at startup and every 30 minutes so disk stays bounded
* when multiple users are clipping throughout the day.
*/
function cleanupOldClips() {
const cutoff = new Date(Date.now() - CLIP_MAX_AGE_MS).toISOString();
const stale = db.prepare(
"SELECT id, outputFile FROM jobs WHERE createdAt < ? AND status IN ('ready','error','pending')"
).all(cutoff);
for (const row of stale) {
if (row.outputFile) fs.unlink(row.outputFile, () => {});
// Remove any temp raw file left by an interrupted job
fs.unlink(path.join(CLIP_TEMP_DIR, `raw_${row.id}.mp4`), () => {});
stmtDelete.run(row.id);
}
if (stale.length > 0) {
console.log(`[Clipper] Auto-cleanup: removed ${stale.length} stale clip(s) (>= ${process.env.CLIP_MAX_AGE_HOURS || 1}h old)`);
}
}
// Run immediately on startup, then every 30 minutes
cleanupOldClips();
setInterval(cleanupOldClips, 30 * 60_000).unref();
/**
* Sanitise a channel handle / username:
* - strip leading/trailing whitespace
* - cap length at 128 chars
* - remove characters that are illegal in filenames or HTTP headers
*/
function sanitizeUsername(raw) {
if (typeof raw !== 'string') throw new Error('username must be a string');
const s = raw.trim();
if (!s) throw new Error('username is empty');
if (s.length > 128) throw new Error('username too long (max 128 chars)');
// Keep word chars, @, :, ., /, -, and URL query-string chars (?, =, &) — everything else becomes _
return s.replace(/[^\w@:./?=&-]/g, '_');
}
/**
* SSRF guard — if the caller supplied a full URL, ensure it points to one of
* the known-good streaming hostnames and uses HTTPS.
*/
function assertSafeUrl(url) {
let parsed;
try { parsed = new URL(url); } catch (_) { throw new Error(`Invalid URL: ${url}`); }
if (parsed.protocol !== 'https:') {
throw new Error(`Only HTTPS URLs are allowed (got ${parsed.protocol})`);
}
if (!ALLOWED_STREAM_HOSTS.has(parsed.hostname)) {
throw new Error(`URL hostname not allowed: ${parsed.hostname}`);
}
}
/**
* Validate that a jobId looks like a v4 UUID before hitting the DB.
*/
function assertValidJobId(id) {
if (!UUID_RE.test(id)) {
const err = new Error('Invalid job ID');
err.status = 400;
throw err;
}
}
/**
* Escape a value for use in a Content-Disposition filename parameter.
*/
function safeFilename(name) {
return '"' + name.replace(/[\\"/\r\n]/g, '_') + '"';
}
/**
* Derive a short, filesystem-safe label from a username or stream URL.
* Full URLs like https://www.youtube.com/watch?v=XJ3Je8RxOiY are collapsed
* to just the meaningful identifier (video ID, channel slug, etc.) so that
* generated filenames stay readable.
*/
function shortLabel(raw) {
try {
const u = new URL(raw);
// YouTube watch URLs → video ID
const v = u.searchParams.get('v');
if (v) return v.replace(/[^\w-]/g, '_');
// Any other URL → last non-empty path segment
const seg = u.pathname.split('/').filter(Boolean).pop();
if (seg) return seg.replace(/[^\w@.-]/g, '_').slice(0, 40);
} catch (_) { /* not a URL — fall through */ }
// Plain username — strip URL-like chars that crept in via sanitizeUsername
return raw.replace(/[^\w@.-]/g, '_').slice(0, 40);
}
/**
* Given a full stream URL, return the human-readable username/channel identifier.
* Falls back to the raw input if it isn't a recognisable URL.
*
* Examples:
* YouTube https://www.youtube.com/@mkbhd/live → "mkbhd"
* YouTube https://www.youtube.com/watch?v=ABC → "ABC" (video ID)
* Twitch https://www.twitch.tv/xqc → "xqc"
* Kick https://kick.com/xqc → "xqc"
*/
function extractUsernameFromUrl(raw, platform) {
if (typeof raw !== 'string' || !raw.startsWith('http')) return raw;
let parsed;
try { parsed = new URL(raw); } catch (_) { return raw; }
const hostname = parsed.hostname.replace(/^www\./, '');
const segments = parsed.pathname.split('/').filter(Boolean);
if (hostname === 'youtube.com' || hostname === 'm.youtube.com') {
// watch?v=VIDEO_ID
const v = parsed.searchParams.get('v');
if (v) return v;
// /@handle or /@handle/live
const handle = segments.find(s => s.startsWith('@'));
if (handle) return handle.slice(1); // strip leading @
// /channel/CHANNEL_ID or /c/name
if (segments.length >= 2 && ['channel', 'c', 'user'].includes(segments[0])) return segments[1];
if (segments[0]) return segments[0];
}
if (hostname === 'twitch.tv') {
// https://www.twitch.tv/<channel>
if (segments[0]) return segments[0];
}
if (hostname === 'kick.com') {
// https://kick.com/<slug>
if (segments[0]) return segments[0];
}
// Generic fallback: last non-empty path segment
return segments[segments.length - 1] || raw;
}
/**
* Removes `outputFile` (absolute disk path) to avoid filesystem disclosure.
*/
function publicJob(job) {
if (!job) return null;
const { outputFile: _omit, ...rest } = job;
return rest;
}
/* ── Simple in-memory rate limiter (per-IP, configurable ceiling) ── */
const _rateBuckets = new Map(); // `${ip}:${key}` → { count, resetAt }
/**
* Build a rate-limit middleware with a specific ceiling.
* Using a key lets clip-creation and poll requests share the same bucket
* map but maintain independent counters per IP.
*/
function makeRateLimiter(maxReq, bucketKey = 'default') {
return function rateLimitMiddleware(req, res, next) {
const ip = req.ip || req.socket?.remoteAddress || 'unknown';
const bkey = `${ip}:${bucketKey}`;
const now = Date.now();
let bucket = _rateBuckets.get(bkey);
if (!bucket || now > bucket.resetAt) {
bucket = { count: 0, resetAt: now + RATE_LIMIT_WINDOW_MS };
_rateBuckets.set(bkey, bucket);
}
bucket.count++;
if (bucket.count > maxReq) {
res.setHeader('Retry-After', Math.ceil((bucket.resetAt - now) / 1000));
return res.status(429).json({ error: 'Too many requests — slow down' });
}
next();
};
}
// Strict: limits how many new clip jobs an IP can start per minute.
const clipCreationLimiter = makeRateLimiter(RATE_LIMIT_MAX_CLIPS, 'clip');
// Loose: high enough that polling every 2 s across 5 active jobs never hits it.
const pollLimiter = makeRateLimiter(RATE_LIMIT_MAX_POLLS, 'poll');
// Prune stale buckets periodically to avoid memory growth
setInterval(() => {
const now = Date.now();
for (const [k, b] of _rateBuckets) { if (now > b.resetAt) _rateBuckets.delete(k); }
}, 300_000).unref();
/* ── API-key guard (always enforced) ─────────────────────── */
function apiKeyMiddleware(req, res, next) {
const authHeader = req.headers['authorization'] || '';
// Accept server-side API key (Bearer) for programmatic/admin access.
const bearerToken = authHeader.replace(/^Bearer\s+/i, '');
if (bearerToken && (bearerToken === API_KEY || bearerToken === BROWSER_KEY)) {
return next();
}
// Also accept a browser session token (Session <token>) issued by /config.
// This keeps the real API key off the wire entirely.
const sessionToken = authHeader.startsWith('Session ') ? authHeader.slice(8).trim() : '';
if (sessionToken && isValidSession(sessionToken)) {
return next();
}
return res.status(401).json({ error: 'Unauthorized — valid API key or session required' });
}
/* ── Active-job concurrency counter ──────────────────────── */
let _activeJobs = 0;
/* ============================================================
PLATFORM: STREAM-URL RESOLVERS
============================================================ */
/**
* YouTube — uses the Data API to resolve a handle to a live video ID,
* then returns type:'ytdlp' with the direct watch?v= URL.
*
* The yt-dlp download path uses player_client=android which hits YouTube's InnerTube API
* mobile innertube API and avoids the [youtube:tab] channel-page scraper
* that 404s when the live tab is absent or the video is unlisted.
*/
async function resolveYouTube(username) {
if (username.startsWith('http')) {
assertSafeUrl(username);
// Fall through with this as watchUrl so it gets the same HLS pre-resolution below.
const watchUrl = username;
try {
const hlsUrl = await ytDlpGetUrl(watchUrl, [
'--extractor-args', 'youtube:player_client=android',
'--format', 'best[protocol^=m3u8][height<=1080]/best[protocol^=m3u8]/best',
]);
console.log(`[YouTube] Resolved HLS URL for ${watchUrl}`);
return { type: 'hls', url: hlsUrl };
} catch (err) {
console.warn(`[YouTube] --get-url failed (${err.message}), falling back to ytdlp mode`);
return { type: 'ytdlp', url: watchUrl };
}
}
const handle = username.replace(/^@/, '');
let watchUrl = null;
if (YOUTUBE_API_KEY) {
try {
const chRes = await fetch(
`${YOUTUBE_API_BASE}/channels?part=id&forHandle=${encodeURIComponent(handle)}&key=${YOUTUBE_API_KEY}`
);
if (chRes.ok) {
const channelId = (await chRes.json())?.items?.[0]?.id;
if (channelId) {
const srRes = await fetch(
`${YOUTUBE_API_BASE}/search?part=id&channelId=${encodeURIComponent(channelId)}&eventType=live&type=video&key=${YOUTUBE_API_KEY}`
);
if (srRes.ok) {
const videoId = (await srRes.json())?.items?.[0]?.id?.videoId;
if (videoId) {
console.log(`[YouTube] Data API: @${handle} -> watch?v=${videoId}`);
watchUrl = `https://www.youtube.com/watch?v=${videoId}`;
}
}
}
}
} catch (err) {
console.warn(`[YouTube] Data API failed (${err.message})`);
}
}
if (!watchUrl) {
console.warn(`[YouTube] Falling back to @${handle}/live`);
watchUrl = `https://www.youtube.com/@${encodeURIComponent(handle)}/live`;
}
// Pre-resolve to a direct HLS manifest URL.
//
// Reasons:
// 1. Avoids the [youtube:tab] channel-page scraper entirely — ios+web player
// clients hit YouTube's innertube API directly and work even when the tab
// endpoint 404s.
// 2. Lets captureClip use ffmpeg -t (reliable live clipping) instead of
// yt-dlp --download-sections (designed for VODs, unreliable on live HLS).
try {
const hlsUrl = await ytDlpGetUrl(watchUrl, [
'--extractor-args', 'youtube:player_client=android',
'--format', 'best[protocol^=m3u8][height<=1080]/best[protocol^=m3u8]/best',
]);
console.log(`[YouTube] Resolved HLS URL for ${watchUrl}`);
return { type: 'hls', url: hlsUrl };
} catch (err) {
// Last-ditch fallback: hand the page URL to yt-dlp and let it figure it out.
console.warn(`[YouTube] --get-url failed (${err.message}), falling back to ytdlp mode`);
return { type: 'ytdlp', url: watchUrl };
}
}
/**
* Twitch — pre-resolve to a direct HLS URL so captureClip can use
* ffmpeg -t (live-edge clipping) instead of yt-dlp --download-sections.
*/
async function resolveTwitch(username) {
const handle = encodeURIComponent(username.replace(/^https?:\/\/[^/]+\//i, '').split('/')[0]);
const pageUrl = `${TWITCH_WEB_BASE}/${handle}`;
try {
const hlsUrl = await ytDlpGetUrl(pageUrl, ['--format', 'best[protocol^=m3u8]/best']);
console.log(`[Twitch] Resolved HLS URL for ${handle}`);
return { type: 'hls', url: hlsUrl };
} catch (err) {
console.warn(`[Twitch] --get-url failed (${err.message}), falling back to ytdlp mode`);
return { type: 'ytdlp', url: pageUrl };
}
}
async function resolveKick(username) {
let slug;
if (username.startsWith('http')) {
assertSafeUrl(username);
slug = new URL(username).pathname.replace(/^\//, '').split('/')[0];
} else {
slug = username.replace(/^@/, '').split('/')[0].trim();
}
const pageUrl = `${KICK_WEB_BASE}/${encodeURIComponent(slug)}`;
try {
const hlsUrl = await ytDlpGetUrl(pageUrl, ['--format', 'best[protocol^=m3u8]/best']);
console.log(`[Kick] Resolved HLS URL for ${slug}`);
return { type: 'hls', url: hlsUrl };
} catch (err) {
console.warn(`[Kick] --get-url failed (${err.message}), falling back to ytdlp mode`);
return { type: 'ytdlp', url: pageUrl };
}
}
/* ============================================================
yt-dlp HELPER — get a direct stream URL without downloading
============================================================ */
/**
* Runs yt-dlp --get-url and resolves with the first URL printed.
*/
function ytDlpGetUrl(pageUrl, extraArgs = []) {
return new Promise((resolve, reject) => {
const args = [
'--get-url',
'--no-playlist',
...(USER_AGENT ? ['--user-agent', USER_AGENT] : []),
...extraArgs,
pageUrl,
];
const proc = spawn('yt-dlp', args);
let stdout = '';
let stderr = '';
proc.stdout.on('data', d => { stdout += d.toString(); });
proc.stderr.on('data', d => { stderr += d.toString(); });
proc.on('close', code => {
const url = stdout.trim().split('\n')[0];
if (code !== 0 || !url) {
reject(new Error(`yt-dlp failed (${code}): ${stderr.trim().slice(0, 200)}`));
} else {
resolve(url);
}
});
proc.on('error', err => reject(new Error(`yt-dlp spawn error: ${err.message}`)));
});
}
/* ============================================================
CLIPPING ENGINE
============================================================ */
/**
* Unified platform dispatcher — returns { type, url } for a live stream.
*/
async function resolveStreamUrl(platform, username) {
const p = platform.toLowerCase();
switch (p) {
case 'youtube': return resolveYouTube(username);
case 'twitch': return resolveTwitch(username);
case 'kick': return resolveKick(username);
default: throw new Error(`Unsupported platform: "${platform}"`);
}
}
/**
* Fetch a live HLS media playlist and return the total duration of its
* buffered segments (i.e. the DVR window length) in seconds.
*
* This is used to compute the correct seek position for rewind:
* seek = dvr_duration − rewind_offset − elapsed
* which places the capture start at exactly (click_time − rewind_offset)
* relative to the live edge at the moment the user pressed Capture.
*
* @param {string} playlistUrl Direct URL to an HLS media playlist (.m3u8)
* @returns {Promise<number>} Total buffered duration in seconds
* @throws if the fetch fails or the playlist contains no #EXTINF tags
*/
async function getHlsDvrDuration(playlistUrl) {
const resp = await fetch(playlistUrl, {
headers: USER_AGENT ? { 'User-Agent': USER_AGENT } : {},
});
if (!resp.ok) throw new Error(`HLS playlist HTTP ${resp.status}`);
const text = await resp.text();
let total = 0;
for (const m of text.matchAll(/#EXTINF:([\d.]+)/g)) {
total += parseFloat(m[1]);
}
if (total === 0) throw new Error('No #EXTINF tags found in playlist');
return total;
}
/**
* Cut a clip from an HLS or FLV stream.
*
* For HLS streams we use yt-dlp (handles manifests, retries, auth).
* For FLV we pipe ffmpeg directly — yt-dlp can't download raw FLV by time.
*
* @param {string} jobId
* @param {{ type: 'hls'|'flv'|'ytdlp', url: string }} stream
* @param {number} duration seconds
* @param {'low'|'medium'|'high'} quality
* @returns {Promise<string>} absolute path to the finished mp4
*/
async function captureClip(jobId, stream, duration, quality = 'medium', startOffset = 0) {
const outFile = path.join(CLIP_OUTPUT_DIR, `clip_${jobId}.mp4`);
const tempRaw = path.join(CLIP_TEMP_DIR, `raw_${jobId}`);
if (stream.type === 'flv' || stream.type === 'hls') {
// --- Direct-URL path: feed stream URL straight into ffmpeg ---
// Covers:
// 'flv' — raw FLV CDN streams
// 'hls' — m3u8 URLs resolved via platform APIs or yt-dlp --get-url
// ffmpeg's own HTTP stack is used, bypassing libcurl entirely.
return new Promise((resolve, reject) => {
updateJob(jobId, { status: 'capturing', progress: 5 });
const sizeFilter = quality === 'low' ? '640:-2'
: quality === 'high' ? '1280:-2'
: '854:-2';
// -live_start_index 0 → read from the oldest available HLS segment (DVR buffer)
// -ss startOffset → jump forward by the seconds lost to URL resolution,
// so the captured content begins at the moment the user
// clicked "Capture" rather than when ffmpeg finally started.
const inputOptions = [
// Reconnect on dropped segments — essential for live HLS
'-reconnect', '1',
'-reconnect_streamed', '1',
'-reconnect_delay_max', '5',
// Seek into the DVR buffer to the click moment
'-live_start_index', '0',
];
if (startOffset > 0) {
inputOptions.push('-ss', String(startOffset));
}
inputOptions.push('-t', String(duration));
// Track last written progress so we never go backwards
let lastPct = 5;
ffmpeg(stream.url)
.inputOptions(inputOptions)
.videoCodec('libx264')
.audioCodec('aac')
.audioBitrate('128k')
.videoFilter(`scale=${sizeFilter}`)
.outputOptions([
'-preset veryfast',
'-movflags +faststart',
'-avoid_negative_ts make_zero',
...(FFMPEG_THREADS > 0 ? [`-threads ${FFMPEG_THREADS}`] : []),
])
.output(outFile)
.on('progress', prog => {
// prog.percent is always 0 for live streams (no known total duration).
// Derive real progress from timemark (HH:MM:SS.ms) instead.
// Only update when we have a real timemark AND progress moves forward.
if (!prog.timemark) return;
const p = prog.timemark.split(':');
const secs = (+p[0]) * 3600 + (+p[1]) * 60 + parseFloat(p[2] || 0);
if (secs <= 0) return;
const pct = Math.min(95, Math.round((secs / duration) * 100));
if (pct <= lastPct) return; // never go backwards
lastPct = pct;
updateJob(jobId, { status: 'capturing', progress: pct });
})
.on('end', () => {
updateJob(jobId, { status: 'ready', progress: 100, outputFile: outFile });
resolve(outFile);
})
.on('error', err => {
updateJob(jobId, { status: 'error', error: err.message });
reject(err);
})
.run();
});
}
// --- HLS / yt-dlp path: yt-dlp download → ffmpeg re-encode ---
const formatArg = quality === 'low'
? 'worst[protocol^=m3u8][height>=360]/worst[protocol^=m3u8]/worst[height>=360]/worst'
: quality === 'high'
? 'best[protocol^=m3u8][height<=1080]/best[protocol^=m3u8]/best[height<=1080]/best'
: 'best[protocol^=m3u8][height<=720]/best[protocol^=m3u8]/best[height<=720]/best';
const tempFile = `${tempRaw}.mp4`;
await new Promise((resolve, reject) => {
updateJob(jobId, { status: 'capturing', progress: 2 });
// startOffset shifts the section window to match the click time:
// *startOffset-(startOffset+duration) captures the segment that was live
// when the user pressed Capture, not when URL resolution finished.
const sectionStart = startOffset;
const sectionEnd = startOffset + duration;
const args = [
'--no-playlist',
'--socket-timeout', '20',
'--retries', '3',
'--fragment-retries', '3',
'--concurrent-fragments', String(YTDLP_CONCURRENT_FRAGS),
...(USER_AGENT ? ['--user-agent', USER_AGENT] : []),
'--format', formatArg,
// android player_client uses InnerTube without requiring a PO Token,
// which ios and web both now demand on VPS/datacenter IPs.
'--extractor-args', 'youtube:player_client=android',
'--downloader', 'native',
'--download-sections', `*${sectionStart}-${sectionEnd}`,
'-o', tempFile,
stream.url,
];
const proc = spawn('yt-dlp', args);
let stderr = '';
let lastDlPct = 2; // never let progress go backwards
proc.stdout.on('data', data => {
const out = data.toString();
const m = out.match(/(\d+\.?\d*)%/);
if (m) {
// Map download progress to 2–70%
const pct = Math.round(2 + Math.min(68, parseFloat(m[1]) * 0.68));
if (pct > lastDlPct) {
lastDlPct = pct;
updateJob(jobId, { progress: pct });
}
}
});
proc.stderr.on('data', d => { stderr += d.toString(); });
proc.on('close', code => {
if (code !== 0) reject(new Error(`yt-dlp exited ${code}: ${stderr.slice(0, 2000)}`));
else resolve();
});
proc.on('error', err => reject(new Error(`yt-dlp spawn: ${err.message}`)));
});
// Re-encode to normalised mp4
await new Promise((resolve, reject) => {
updateJob(jobId, { status: 'encoding', progress: 72 });
const sizeFilter = quality === 'low' ? '640:-2'
: quality === 'high' ? '1280:-2'
: '854:-2';
let lastEncPct = 72; // never go backwards during encode
ffmpeg(tempFile)
.videoCodec('libx264')
.audioCodec('aac')
.audioBitrate('128k')
.videoFilter(`scale=${sizeFilter}`)
.outputOptions([
'-preset veryfast',
'-movflags +faststart',
...(FFMPEG_THREADS > 0 ? [`-threads ${FFMPEG_THREADS}`] : []),
])
.output(outFile)
.on('progress', prog => {
const pct = Math.round(72 + Math.min(23, (prog.percent || 0) * 0.23));
if (pct > lastEncPct) {
lastEncPct = pct;
updateJob(jobId, { progress: pct });
}
})
.on('end', () => {
// Cleanup temp file
fs.unlink(tempFile, () => {});
updateJob(jobId, { status: 'ready', progress: 100, outputFile: outFile });
resolve();
})
.on('error', err => {
fs.unlink(tempFile, () => {});
updateJob(jobId, { status: 'error', error: err.message });
reject(err);
})
.run();
});
return outFile;
}
/* ============================================================
PUBLIC API — start a clip job
============================================================ */
/**
* Start a clip job asynchronously. Returns the job object immediately.
*
* @param {Object} opts
* @param {string} opts.platform 'youtube'|'twitch'|'kick'
* @param {string} [opts.url] full stream URL (preferred; username extracted automatically)
* @param {string} [opts.username] channel handle / URL (legacy; use url instead)
* @param {number} [opts.duration] seconds to capture (capped at MAX_CLIP_SECONDS)
* @param {'low'|'medium'|'high'} [opts.quality]
* @returns {ClipJob}
*/
function startClip({ platform, url, username, duration, quality = 'medium', rewindOffset = 0 }) {
// Accept either `url` (new) or `username` (legacy) — `url` takes precedence.
const rawInput = url || username;
if (!platform || !rawInput) throw new Error('platform and url are required');
const normalPlatform = platform.toLowerCase();
if (!VALID_PLATFORMS.includes(normalPlatform)) {
throw new Error(`Unsupported platform: "${platform}"`);
}
const normalQuality = (quality || 'medium').toLowerCase();
if (!VALID_QUALITIES.includes(normalQuality)) {
throw new Error(`Invalid quality "${quality}". Valid: ${VALID_QUALITIES.join(', ')}`);
}
// If a full URL was supplied, extract the channel/video identifier from it
// so the DB stores a clean, human-readable username rather than a raw URL.
const extractedUsername = extractUsernameFromUrl(rawInput, normalPlatform);
const safeUser = sanitizeUsername(extractedUsername);
// Preserve the original URL (if one was given) for storage alongside the username.
const originalUrl = rawInput.startsWith('http') ? rawInput : null;
const secs = Math.min(
MAX_CLIP_SECONDS,
Math.max(5, Number(duration) || DEFAULT_CLIP_SECS)
);
if (_activeJobs >= MAX_CONCURRENT_JOBS) {
throw Object.assign(
new Error(`Server busy — max ${MAX_CONCURRENT_JOBS} concurrent jobs`),
{ status: 503 }
);
}
const job = createJob(normalPlatform, safeUser, secs);
_activeJobs++;
// Fire-and-forget — caller polls /clip/:id for status
(async () => {
try {
const downloadUrl = `/clips/clip_${job.id}.mp4`;
updateJob(job.id, { status: 'resolving', progress: 1, downloadUrl });
// Resolve the stream URL, noting the exact start time so we can account
// for all elapsed time (resolution + m3u8 fetch) in the seek calculation.
const resolveStart = Date.now();
// Use the original URL (or plain username) for stream resolution so that
// watch?v= URLs reach yt-dlp intact. safeUser is only for DB storage.
const stream = await resolveStreamUrl(normalPlatform, rawInput);
// ── Compute DVR seek position ──────────────────────────────────────
// With -live_start_index 0, ffmpeg always reads from the *oldest* segment
// in the HLS playlist. -ss X then seeks X seconds forward from there.
//
// To land the clip start at exactly (clickTime − rewindOffset):
// seek = DVR_duration − rewindOffset − totalElapsed
//
// where:
// DVR_duration = total duration of buffered segments in the playlist
// rewindOffset = seconds the user wants to go back from click time
// totalElapsed = seconds spent on URL resolution + m3u8 fetch
// (the live edge advances by this much before ffmpeg starts)
//
// Example — DVR=180s, rewind=120s, elapsed=6s:
// seek = 180 − 120 − 6 = 54 → oldest segment is at T−180, +54s = T−126 ≈ T−120 ✓
//
// For yt-dlp fallback streams we cannot parse the playlist in advance;
// fall back to compensating for resolution delay only.
let startOffset = 0;
if (stream.type === 'hls') {
try {
const dvrDuration = await getHlsDvrDuration(stream.url);
const totalElapsed = Math.round((Date.now() - resolveStart) / 1000);
startOffset = Math.max(0, Math.round(dvrDuration - rewindOffset - totalElapsed));
console.log(
`[Clipper] Job ${job.id}: DVR=${Math.round(dvrDuration)}s ` +
`rewind=${rewindOffset}s elapsed=${totalElapsed}s → seek=${startOffset}s`
);
} catch (err) {
console.warn(
`[Clipper] Job ${job.id}: DVR parse failed (${err.message}) — ` +
`starting from oldest available segment`
);
// startOffset stays 0: ffmpeg starts from the oldest DVR segment
}