Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
205 lines (184 loc) · 6.8 KB
/
Copy pathserver.js
File metadata and controls
205 lines (184 loc) · 6.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import express from 'express';
import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { execFile } from 'node:child_process';
import { getTranscript, extractVideoId, engineConfig, TranscriptError } from './lib/transcript.js';
const YTDLP =
process.env.YTDLP_PATH || (process.platform === 'win32' ? 'yt-dlp.exe' : 'yt-dlp');
function checkEngine() {
execFile(YTDLP, ['--version'], { windowsHide: true }, (err, stdout) => {
if (err) {
console.warn(
'\n ⚠ yt-dlp was not found. Transcript extraction will fail.\n' +
' Install it with: pip install -U yt-dlp\n' +
' (or set YTDLP_PATH to its full path)\n'
);
} else {
console.log(` ✓ yt-dlp ${stdout.trim()} detected`);
}
});
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const PORT = process.env.PORT || 3000;
app.disable('x-powered-by');
app.use(express.json({ limit: '64kb' }));
// --- Transcript cache (memory + disk) so repeated lookups are instant -------
// First-fetch of a brand-new video is bound by yt-dlp (~2s); everything we've
// seen before is served from here in ~1ms, and the disk copy survives restarts.
const cache = new Map();
const CACHE_TTL_MS = 1000 * 60 * 60 * 24 * 7; // 7 days — transcripts rarely change
const CACHE_MAX = 500;
const CACHE_DIR = path.join(__dirname, '.cache');
function cacheFile(key) {
return path.join(CACHE_DIR, key.replace(/[^a-zA-Z0-9_-]/g, '_') + '.json');
}
function cacheGet(key) {
const hit = cache.get(key);
if (!hit) return null;
if (Date.now() - hit.at > CACHE_TTL_MS) {
cache.delete(key);
fsp.rm(cacheFile(key), { force: true }).catch(() => {});
return null;
}
return hit.data;
}
function cacheSet(key, data) {
if (cache.size >= CACHE_MAX) {
const oldest = cache.keys().next().value;
cache.delete(oldest);
fsp.rm(cacheFile(oldest), { force: true }).catch(() => {});
}
const entry = { at: Date.now(), data };
cache.set(key, entry);
// Persist (best-effort) so the cache survives restarts.
fsp.writeFile(cacheFile(key), JSON.stringify({ key, ...entry })).catch(() => {});
}
// Restore the on-disk cache into memory on boot, dropping expired/corrupt files.
function loadCacheFromDisk() {
let files;
try {
fs.mkdirSync(CACHE_DIR, { recursive: true });
files = fs.readdirSync(CACHE_DIR);
} catch {
return;
}
const entries = [];
for (const f of files) {
if (!f.endsWith('.json')) continue;
const full = path.join(CACHE_DIR, f);
try {
const raw = JSON.parse(fs.readFileSync(full, 'utf8'));
if (!raw.key || !raw.data || Date.now() - raw.at > CACHE_TTL_MS) {
fs.rmSync(full, { force: true });
continue;
}
entries.push(raw);
} catch {
fs.rmSync(full, { force: true }); // corrupt — discard
}
}
entries.sort((a, b) => a.at - b.at); // oldest first → correct eviction order
for (const e of entries.slice(-CACHE_MAX)) cache.set(e.key, { at: e.at, data: e.data });
if (cache.size) console.log(` ✓ Restored ${cache.size} cached transcript(s) from disk`);
}
// Warm the cache for the homepage example videos so the demo feels instant.
const PREWARM_URLS = [
'https://www.youtube.com/watch?v=jNQXAC9IVRw',
'https://www.youtube.com/watch?v=aircAruvnKk',
'https://www.youtube.com/watch?v=8aGhZQkoFbQ',
];
async function prewarm() {
if (process.env.PREWARM === '0') return;
for (const url of PREWARM_URLS) {
const key = `${extractVideoId(url) || url}::auto`;
if (cacheGet(key)) continue; // already warm (likely restored from disk)
try {
cacheSet(key, await getTranscript(url, {}));
console.log(` ✓ Pre-warmed ${extractVideoId(url)}`);
} catch {
/* best-effort: offline, no captions, engine missing, etc. */
}
}
}
// --- Lightweight per-IP rate limiting --------------------------------------
const hits = new Map();
const WINDOW_MS = 60 * 1000;
const MAX_PER_WINDOW = 30;
function rateLimit(req, res, next) {
const ip = req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.ip;
const now = Date.now();
const entry = hits.get(ip) || { count: 0, reset: now + WINDOW_MS };
if (now > entry.reset) {
entry.count = 0;
entry.reset = now + WINDOW_MS;
}
entry.count++;
hits.set(ip, entry);
if (entry.count > MAX_PER_WINDOW) {
res.set('Retry-After', Math.ceil((entry.reset - now) / 1000));
return res.status(429).json({
error: 'Too many requests. Please slow down for a minute.',
code: 'RATE_LIMITED',
});
}
next();
}
// --- API --------------------------------------------------------------------
app.get('/api/health', (_req, res) =>
res.json({ ok: true, cookies: engineConfig.cookies, proxy: engineConfig.proxy })
);
app.get('/api/transcript', rateLimit, async (req, res) => {
const url = (req.query.url || '').toString();
const lang = (req.query.lang || '').toString() || undefined;
if (!url) {
return res
.status(400)
.json({ error: 'Provide a ?url= parameter.', code: 'MISSING_URL' });
}
// Key by canonical video id so every URL shape for the same video
// (youtu.be/X, watch?v=X, /shorts/X, …) shares one cache entry.
const cacheKey = `${extractVideoId(url) || url}::${lang || 'auto'}`;
const cached = cacheGet(cacheKey);
if (cached) return res.json({ ...cached, cached: true });
try {
const data = await getTranscript(url, { lang });
cacheSet(cacheKey, data);
res.json(data);
} catch (err) {
if (err instanceof TranscriptError) {
return res.status(err.status).json({ error: err.message, code: err.code });
}
console.error('Unexpected error:', err);
res.status(500).json({
error: 'Something went wrong while fetching the transcript.',
code: 'INTERNAL_ERROR',
});
}
});
// --- Static frontend --------------------------------------------------------
app.use(
express.static(path.join(__dirname, 'public'), {
extensions: ['html'],
// No filename hashing here, so a long-lived cache can leave the browser
// running a stale app.js/index.html that no longer matches — which silently
// breaks the page. Revalidate every load (ETag → 304 when unchanged, so
// it stays fast) and always serve the current files.
setHeaders(res) {
res.setHeader('Cache-Control', 'no-cache');
},
})
);
app.listen(PORT, () => {
console.log(`\n Scriptly running → http://localhost:${PORT}`);
checkEngine();
if (engineConfig.cookies) console.log(' ✓ yt-dlp: using cookies for auth');
if (engineConfig.proxy) console.log(' ✓ yt-dlp: routing through proxy');
if (!engineConfig.cookies && !engineConfig.proxy) {
console.log(' ℹ No cookies/proxy set — fine locally, but cloud IPs may hit YouTube bot checks');
}
loadCacheFromDisk();
prewarm();
});