forked from MakcRe/KuGouMusicApi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
216 lines (185 loc) · 6.38 KB
/
server.js
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
const fs = require('node:fs');
const path = require('node:path');
const express = require('express');
const decode = require('safe-decode-uri-component');
const { cookieToJson } = require('./util/util');
const { createRequest } = require('./util/request');
const dotenv = require('dotenv');
const cache = require('./util/apicache').middleware;
/**
* @typedef {{
* identifier?: string,
* route: string,
* module: any,
* }}ModuleDefinition
*/
/**
* @typedef {{
* server?: import('http').Server,
* }} ExpressExtension
*/
const envPath = path.join(process.cwd(), '.env');
if (fs.existsSync(envPath)) {
dotenv.config(envPath);
}
/**
* 描述:动态获取模块定义
* @param {string} modulesPath 模块路径(TS)
* @param {Record<string, string>} specificRoute 特定模块定义
* @param {boolean} doRequire 如果为 true,则使用 require 加载模块, 否则打印模块路径, 默认为true
* @return { Promise<ModuleDefinition[]> }
* @example getModuleDefinitions("./module", {"album_new.js": "/album/create"})
*/
async function getModulesDefinitions(modulesPath, specificRoute, doRequire = true) {
const files = await fs.promises.readdir(modulesPath);
const parseRoute = (fileName) =>
specificRoute && fileName in specificRoute ? specificRoute[fileName] : `/${fileName.replace(/\.(js)$/i, '').replace(/_/g, '/')}`;
return files
.reverse()
.filter((fileName) => fileName.endsWith('.js') && !fileName.startsWith('_'))
.map((fileName) => {
const identifier = fileName.split('.').shift();
const route = parseRoute(fileName);
const modulePath = path.resolve(modulesPath, fileName);
const module = doRequire ? require(modulePath) : modulePath;
return { identifier, route, module };
});
}
/**
* 创建服务
* @param {ModuleDefinition[]} moduleDefs
* @return {Promise<import('express').Express>}
*/
async function consturctServer(moduleDefs) {
const app = express();
const { CORS_ALLOW_ORIGIN } = process.env;
app.set('trust proxy', true);
/**
* CORS & Preflight request
*/
app.use((req, res, next) => {
if (req.path !== '/' && !req.path.includes('.')) {
res.set({
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': CORS_ALLOW_ORIGIN || req.headers.origin || '*',
'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
'Content-Type': 'application/json; charset=utf-8',
});
}
req.method === 'OPTIONS' ? res.status(204).end() : next();
});
// Cookie Parser
app.use((req, _, next) => {
req.cookies = {};
(req.headers.cookie || '').split(/;\s+|(?<!\s)\s+$/g).forEach((pair) => {
const crack = pair.indexOf('=');
if (crack < 1 || crack === pair.length - 1) {
return;
}
req.cookies[decode(pair.slice(0, crack)).trim()] = decode(pair.slice(crack + 1)).trim();
});
next();
});
// 将当前平台写入Cookie 以方便查看
app.use((req, res, next) => {
const cookies = (req.headers.cookie || '').split(/;\s+|(?<!\s)\s+$/g);
if (!cookies.includes('KUGOU_API_PLATFORM')) {
if (req.protocol === 'https') {
res.append('Set-Cookie', `KUGOU_API_PLATFORM=${process.env.platform}; PATH=/; SameSite=None; Secure`);
} else {
res.append('Set-Cookie', `KUGOU_API_PLATFORM=${process.env.platform}; PATH=/`);
}
}
next();
});
// Body Parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
/**
* Serving static files
*/
app.use(express.static(path.join(__dirname, 'public')));
/**
* docs
*/
app.use('/docs', express.static(path.join(__dirname, 'docs')));
// Cache
app.use(cache('2 minutes', (_, res) => res.statusCode === 200));
const moduleDefinitions = moduleDefs || (await getModulesDefinitions(path.join(__dirname, 'module'), {}));
for (const moduleDef of moduleDefinitions) {
app.use(moduleDef.route, async (req, res) => {
[req.query, req.body].forEach((item) => {
if (typeof item.cookie === 'string') {
item.cookie = cookieToJson(decode(item.cookie));
}
});
const query = Object.assign({}, { cookie: req.cookies }, req.query, { body: req.body });
try {
const moduleResponse = await moduleDef.module(query, (config) => {
let ip = req.ip;
if (ip.substring(0, 7) === '::ffff:') {
ip = ip.substring(7);
}
config.ip = ip;
return createRequest(config);
});
console.log('[OK]', decode(req.originalUrl));
const cookies = moduleResponse.cookie;
if (!query.noCookie) {
if (Array.isArray(cookies) && cookies.length > 0) {
if (req.protocol === 'https') {
// Try to fix CORS SameSite Problem
res.append(
'Set-Cookie',
cookies.map((cookie) => {
return `${cookie}; PATH=/; SameSite=None; Secure`;
})
);
} else {
res.append(
'Set-Cookie',
cookies.map((cookie) => {
return `${cookie}; PATH=/`;
})
);
}
}
}
res.header(moduleResponse.headers).status(moduleResponse.status).send(moduleResponse.body);
} catch (e) {
const moduleResponse = e;
console.log('[ERR]', decode(req.originalUrl), {
status: moduleResponse.status,
body: moduleResponse.body,
});
if (!moduleResponse.body) {
res.status(404).send({
code: 404,
data: null,
msg: 'Not Found',
});
return;
}
res.header(moduleResponse.headers).status(moduleResponse.status).send(moduleResponse.body);
}
});
}
return app;
}
/**
* Serve the KG API
* @returns {Promise<import('express').Express & ExpressExtension>}
*/
async function startService() {
const port = Number(process.env.PORT || '3000');
const host = process.env.HOST || '';
const app = await consturctServer();
/** @type {import('express').Express & ExpressExtension} */
const appExt = app;
appExt.service = app.listen(port, host, () => {
console.log(`server running @ http://${host || 'localhost'}:${port}`);
});
return appExt;
}
module.exports = { startService, getModulesDefinitions };