-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
169 lines (150 loc) · 6.02 KB
/
Copy pathserver.js
File metadata and controls
169 lines (150 loc) · 6.02 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
// Bonto entry point for the Altspace Video Player.
//
// Serves the snippet bundle and the player page, and proxies the lookups a
// space page cannot do itself (YouTube search/playlists through innertube or
// the Data API, link classification, Google Drive streaming). Plain node:http,
// no dependencies: the container is small and restarts on every file write.
import http from 'node:http';
import { createReadStream, statSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { youtube } from './lib/youtube.js';
import { driveMediaUrl, resolveInput } from './lib/sources.js';
import { ApiError, clamp } from './lib/util.js';
const ROOT = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC_DIR = path.join(ROOT, 'public');
const PORT = Number(process.env.PORT) || 3000;
const CONTENT_TYPES = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.map': 'application/json; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.ico': 'image/x-icon',
'.txt': 'text/plain; charset=utf-8',
};
// The snippet and the player page are fetched once per space load and must
// never be cached across deploys. Cloudflare sits in front of Bonto and rewrites
// `no-cache` on scripts to a 4 hour TTL, but it honours `no-store`, so that is
// what the files we redeploy have to send. The vendored hls.js build changes
// only with a dependency bump, so it may be cached.
const CACHE_CONTROL = {
'/snippet.js': 'no-store',
'/player.js': 'no-store',
'/player.html': 'no-store',
'/vendor/hls.min.js': 'public, max-age=3600',
};
function cors(res) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Max-Age', '86400');
}
function sendJson(res, status, body) {
cors(res);
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
res.end(JSON.stringify(body));
}
function sendError(res, err) {
if (err instanceof ApiError) {
sendJson(res, err.status, { error: err.message, code: err.code });
return;
}
console.error('[server] unhandled', err);
sendJson(res, 500, { error: 'Internal error', code: 'internal' });
}
function serveStatic(req, res, urlPath) {
const decoded = decodeURIComponent(urlPath);
const resolved = path.normalize(path.join(PUBLIC_DIR, decoded));
// Reject anything that escapes public/ after normalisation.
if (!resolved.startsWith(PUBLIC_DIR + path.sep) && resolved !== PUBLIC_DIR) return false;
let stat;
try {
stat = statSync(resolved);
} catch {
return false;
}
if (!stat.isFile()) return false;
const ext = path.extname(resolved).toLowerCase();
cors(res);
res.writeHead(200, {
'content-type': CONTENT_TYPES[ext] || 'application/octet-stream',
'content-length': stat.size,
'cache-control': CACHE_CONTROL[decoded] || 'public, max-age=60',
});
if (req.method === 'HEAD') {
res.end();
return true;
}
createReadStream(resolved).pipe(res);
return true;
}
async function handleApi(req, res, url) {
const segments = url.pathname.split('/').filter(Boolean); // ['api', ...]
const route = segments[1];
if (route === 'search') {
const result = await youtube.search(url.searchParams.get('q'), clamp(Number(url.searchParams.get('limit')) || 12, 1, 25));
return sendJson(res, 200, result);
}
if (route === 'playlist' && segments[2]) {
const id = segments[2];
if (!/^[A-Za-z0-9_-]{10,}$/.test(id)) throw new ApiError(400, 'bad_request', 'Invalid playlist id');
if (id.startsWith('RD')) throw new ApiError(400, 'unsupported', 'YouTube mixes cannot be imported');
const result = await youtube.playlist(id, clamp(Number(url.searchParams.get('limit')) || 300, 1, 300));
return sendJson(res, 200, result);
}
if (route === 'resolve') {
const input = url.searchParams.get('input');
if (!input || !input.trim()) throw new ApiError(400, 'bad_request', 'input is required');
if (input.length > 2048) throw new ApiError(400, 'bad_request', 'input is too long');
const result = await resolveInput(input, { youtube });
return sendJson(res, 200, result);
}
if (route === 'drive' && segments[2] && segments[3] === 'media') {
const id = segments[2];
if (!/^[A-Za-z0-9_-]{20,}$/.test(id)) throw new ApiError(400, 'bad_request', 'Invalid Drive file id');
const location = await driveMediaUrl(id);
cors(res);
res.writeHead(302, { location, 'cache-control': 'no-store' });
return res.end();
}
throw new ApiError(404, 'not_found', 'Unknown API route');
}
const server = http.createServer(async (req, res) => {
const started = Date.now();
const url = new URL(req.url, 'http://localhost');
res.on('finish', () => {
console.log(`[server] ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - started}ms`);
});
try {
if (req.method === 'OPTIONS') {
cors(res);
res.writeHead(204);
return res.end();
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
throw new ApiError(405, 'bad_request', 'Method not allowed');
}
if (url.pathname === '/healthz') {
return sendJson(res, 200, {
ok: true,
providers: { innertube: true, dataapi: !!youtube.apiKey(), drive: youtube.apiKey() ? 'api' : 'legacy' },
uptime: Math.round(process.uptime()),
});
}
if (url.pathname.startsWith('/api/')) {
return await handleApi(req, res, url);
}
const staticPath = url.pathname === '/' ? '/player.html' : url.pathname;
if (serveStatic(req, res, staticPath)) return;
throw new ApiError(404, 'not_found', 'Not found');
} catch (err) {
sendError(res, err);
}
});
server.listen(PORT, () => {
console.log(`[server] Altspace Video Player listening on :${PORT} (Data API key ${youtube.apiKey() ? 'configured' : 'absent'})`);
});