Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
179 lines (167 loc) · 5.03 KB
/
Copy pathserver.js
File metadata and controls
179 lines (167 loc) · 5.03 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
const http = require('http');
const https = require('https');
const fs = require('fs');
const path = require('path');
const { URL } = require('url');
const PORT = process.env.PORT || 3000;
const ROOT = __dirname;
const MIME = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.webp': 'image/webp',
'.ico': 'image/x-icon'
};
function extractBvid(input) {
if (!input) return null;
const match = String(input).match(/BV[0-9A-Za-z]{10}/i);
return match ? match[0].toUpperCase() : null;
}
function normalizeUrl(input) {
if (!input) return '';
const trimmed = String(input).trim();
if (trimmed.startsWith('http://') || trimmed.startsWith('https://')) return trimmed;
return `https://${trimmed}`;
}
function resolveRedirect(inputUrl, limit = 5) {
return new Promise((resolve, reject) => {
const urlObj = new URL(inputUrl);
const lib = urlObj.protocol === 'http:' ? http : https;
const req = lib.request(urlObj, { method: 'GET', headers: { 'User-Agent': 'Mozilla/5.0' } }, res => {
const status = res.statusCode || 0;
if (status >= 300 && status < 400 && res.headers.location && limit > 0) {
const nextUrl = new URL(res.headers.location, urlObj).toString();
res.resume();
resolve(resolveRedirect(nextUrl, limit - 1));
return;
}
if (status >= 200 && status < 400) {
res.resume();
resolve(urlObj.toString());
return;
}
res.resume();
reject(new Error(`Redirect failed: ${status}`));
});
req.on('error', reject);
req.end();
});
}
function fetchJson(url) {
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const lib = urlObj.protocol === 'http:' ? http : https;
const req = lib.request(urlObj, {
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0',
'Referer': 'https://www.bilibili.com'
}
}, res => {
const chunks = [];
res.on('data', chunk => chunks.push(chunk));
res.on('end', () => {
try {
const text = Buffer.concat(chunks).toString('utf-8');
resolve(JSON.parse(text));
} catch (err) {
reject(err);
}
});
});
req.on('error', reject);
req.end();
});
}
async function getBilibiliMeta(input) {
let bvid = extractBvid(input);
let finalUrl = input;
if (!bvid && /b23\.tv/i.test(String(input))) {
finalUrl = await resolveRedirect(normalizeUrl(input));
bvid = extractBvid(finalUrl);
}
if (!bvid) return null;
const apiUrl = `https://api.bilibili.com/x/web-interface/view?bvid=${bvid}`;
const json = await fetchJson(apiUrl);
if (!json || json.code !== 0 || !json.data) return null;
return {
bvid,
title: json.data.title || '',
pic: json.data.pic || '',
url: `https://www.bilibili.com/video/${bvid}`
};
}
function sendJson(res, status, body) {
res.writeHead(status, {
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*'
});
res.end(JSON.stringify(body));
}
function serveStatic(req, res) {
const reqUrl = new URL(req.url, `http://${req.headers.host}`);
let pathname = decodeURIComponent(reqUrl.pathname);
if (pathname === '/') pathname = '/index.html';
const filePath = path.normalize(path.join(ROOT, pathname));
if (!filePath.startsWith(ROOT)) {
res.writeHead(403);
res.end();
return;
}
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(404);
res.end();
return;
}
const ext = path.extname(filePath);
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream' });
res.end(content);
});
}
function createServer() {
return http.createServer(async (req, res) => {
const reqUrl = new URL(req.url, `http://${req.headers.host}`);
if (reqUrl.pathname === '/api/bilibili') {
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'GET, OPTIONS'
});
res.end();
return;
}
const input = reqUrl.searchParams.get('input') || '';
if (!input) {
sendJson(res, 400, { error: 'missing input' });
return;
}
try {
const meta = await getBilibiliMeta(input);
if (!meta) {
sendJson(res, 404, { error: 'not found' });
return;
}
sendJson(res, 200, meta);
} catch (_) {
sendJson(res, 502, { error: 'upstream error' });
}
return;
}
serveStatic(req, res);
});
}
module.exports = { extractBvid, normalizeUrl, getBilibiliMeta, createServer };
if (require.main === module) {
const server = createServer();
server.listen(PORT, () => {
process.stdout.write(`http://localhost:${PORT}\n`);
});
}