-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
451 lines (415 loc) · 11.7 KB
/
server.js
File metadata and controls
451 lines (415 loc) · 11.7 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
const express = require('express');
const cors = require('cors');
const path = require('path');
const multer = require('multer');
const fs = require('fs');
const mc = require('minecraft-protocol');
const app = express();
const port = process.env.PORT || 3000;
// 配置文件上传
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadDir = path.join('public', file.fieldname === 'resourcepack' ? 'resourcepacks' : 'uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
cb(null, uploadDir);
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
cb(null, uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 50 * 1024 * 1024 // 限制50MB
},
fileFilter: function (req, file, cb) {
if (file.fieldname === 'icon') {
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('不支持的文件类型'));
}
} else if (file.fieldname === 'resourcepack') {
// 资源包文件类型检查
if (file.mimetype === 'application/zip' || file.mimetype === 'application/x-zip-compressed') {
cb(null, true);
} else {
cb(new Error('资源包必须是ZIP格式'));
}
} else {
cb(new Error('未知的文件类型'));
}
}
});
// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));
// 错误处理中间件
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
error: '服务器内部错误',
message: process.env.NODE_ENV === 'development' ? err.message : undefined
});
});
// 模拟数据
const servers = [
{
id: 1,
name: '生存服务器',
ip: 'mc.example.com',
description: '原版生存服务器,支持多人游戏,定期举办活动',
image: '/images/default-server.svg',
ping: 35,
version: '1.20.4',
players: {
online: 128,
max: 200
},
features: ['生存', '经济系统', '领地', '副本'],
resourcepack: null // 添加资源包字段
},
{
id: 2,
name: '创造服务器',
ip: 'creative.example.com',
description: '创造模式服务器,自由建造,支持世界编辑',
image: '/images/default-server.svg',
ping: 42,
version: '1.20.4',
players: {
online: 64,
max: 100
},
features: ['创造', '世界编辑', '建筑比赛']
},
{
id: 3,
name: '小游戏服务器',
ip: 'minigames.example.com',
description: '各种有趣的小游戏,包括空岛战争、躲猫猫等',
image: '/images/default-server.svg',
ping: 56,
version: '1.20.4',
players: {
online: 256,
max: 500
},
features: ['小游戏', '排位系统', '组队系统']
}
];
// 模拟入驻申请数据
let applications = [
{
id: 1,
applicant: '张三',
serverName: '测试服务器',
serverIP: 'test.example.com',
version: '1.20.4',
description: '这是一个测试服务器',
features: ['生存', '小游戏'],
contact: '12345678901',
status: '待审核',
createdAt: '2024-01-20T08:00:00.000Z'
}
];
// MC ping 功能
async function pingMinecraftServer(host, port = 25565) {
return new Promise((resolve, reject) => {
mc.ping({ host, port }, (err, response) => {
if (err) {
reject(err);
} else {
resolve({
version: response.version.name,
protocol: response.version.protocol,
players: {
online: response.players.online,
max: response.players.max,
sample: response.players.sample
},
description: response.description,
favicon: response.favicon
});
}
});
});
}
// API路由
// 获取服务器列表
app.get('/api/servers', (req, res) => {
try {
const { search, sort } = req.query;
let filteredServers = [...servers];
// 搜索过滤
if (search) {
const searchLower = search.toLowerCase();
filteredServers = filteredServers.filter(server =>
server.name.toLowerCase().includes(searchLower) ||
server.description.toLowerCase().includes(searchLower) ||
server.features.some(feature => feature.toLowerCase().includes(searchLower))
);
}
// 排序
if (sort) {
switch (sort) {
case 'players':
filteredServers.sort((a, b) => b.players.online - a.players.online);
break;
case 'ping':
filteredServers.sort((a, b) => a.ping - b.ping);
break;
case 'name':
filteredServers.sort((a, b) => a.name.localeCompare(b.name));
break;
}
}
res.json(filteredServers);
} catch (error) {
next(error);
}
});
// 获取单个服务器信息
app.get('/api/servers/:id', (req, res) => {
try {
const server = servers.find(s => s.id === parseInt(req.params.id));
if (server) {
res.json(server);
} else {
res.status(404).json({ error: '服务器未找到' });
}
} catch (error) {
next(error);
}
});
// 添加服务器
app.post('/api/servers', (req, res) => {
try {
const newServer = {
id: servers.length + 1,
...req.body,
image: '/images/default-server.svg',
ping: Math.floor(Math.random() * 100),
players: {
online: 0,
max: req.body.players?.max || 100
}
};
servers.push(newServer);
res.status(201).json(newServer);
} catch (error) {
next(error);
}
});
// 更新服务器
app.put('/api/servers/:id', (req, res) => {
try {
const index = servers.findIndex(s => s.id === parseInt(req.params.id));
if (index !== -1) {
servers[index] = {
...servers[index],
...req.body
};
res.json(servers[index]);
} else {
res.status(404).json({ error: '服务器未找到' });
}
} catch (error) {
next(error);
}
});
// 删除服务器
app.delete('/api/servers/:id', (req, res) => {
try {
const index = servers.findIndex(s => s.id === parseInt(req.params.id));
if (index !== -1) {
servers.splice(index, 1);
res.status(204).end();
} else {
res.status(404).json({ error: '服务器未找到' });
}
} catch (error) {
next(error);
}
});
// 获取服务器状态
app.get('/api/servers/:id/status', async (req, res) => {
try {
const server = servers.find(s => s.id === parseInt(req.params.id));
if (server) {
try {
// 解析服务器 IP 和端口
const [host, port] = server.ip.split(':');
const mcStatus = await pingMinecraftServer(host, parseInt(port) || 25565);
const status = {
online: true,
version: mcStatus.version,
players: mcStatus.players,
description: mcStatus.description,
favicon: mcStatus.favicon,
lastUpdate: new Date().toISOString()
};
res.json(status);
} catch (error) {
// 如果 ping 失败,返回离线状态
res.json({
online: false,
error: '服务器可能离线',
lastUpdate: new Date().toISOString()
});
}
} else {
res.status(404).json({ error: '服务器未找到' });
}
} catch (error) {
next(error);
}
});
// 获取入驻申请列表
app.get('/api/applications', (req, res) => {
try {
res.json(applications);
} catch (error) {
next(error);
}
});
// 提交入驻申请
app.post('/api/applications', (req, res) => {
try {
const newApplication = {
id: applications.length + 1,
...req.body,
status: '待审核',
createdAt: new Date().toISOString()
};
applications.push(newApplication);
res.status(201).json(newApplication);
} catch (error) {
next(error);
}
});
// 上传服务器图标
app.post('/api/upload', upload.single('icon'), (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: '没有上传文件' });
}
const filePath = '/uploads/' + req.file.filename;
res.json({ url: filePath });
} catch (error) {
next(error);
}
});
// 更新申请状态并同步服务器
app.put('/api/applications/:id', (req, res) => {
try {
const index = applications.findIndex(a => a.id === parseInt(req.params.id));
if (index !== -1) {
const { status } = req.body;
// 如果申请已经有了最终状态(已通过或已拒绝),则不允许再次修改
if (applications[index].status === '已通过' || applications[index].status === '已拒绝') {
return res.status(400).json({ error: '该申请已经处理过了' });
}
// 更新申请状态
applications[index] = {
...applications[index],
status: status === 'approved' ? '已通过' : '已拒绝',
updatedAt: new Date().toISOString()
};
// 如果申请通过,自动创建服务器
if (status === 'approved') {
const newServer = {
id: servers.length + 1,
name: applications[index].serverName,
ip: applications[index].serverIP,
description: applications[index].description,
version: applications[index].version,
features: applications[index].features,
image: applications[index].icon || '/images/default-server.svg',
ping: Math.floor(Math.random() * 100),
players: {
online: 0,
max: 100
}
};
servers.push(newServer);
// 返回同步后的数据
res.json({
application: applications[index],
server: newServer
});
} else {
res.json(applications[index]);
}
} else {
res.status(404).json({ error: '申请未找到' });
}
} catch (error) {
next(error);
}
});
// 上传资源包
app.post('/api/servers/:id/resourcepack', upload.single('resourcepack'), (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: '没有上传文件' });
}
const server = servers.find(s => s.id === parseInt(req.params.id));
if (!server) {
// 删除已上传的文件
fs.unlinkSync(path.join(__dirname, 'public', req.file.path));
return res.status(404).json({ error: '服务器未找到' });
}
// 如果服务器之前有资源包,删除旧文件
if (server.resourcepack) {
const oldPath = path.join(__dirname, 'public', server.resourcepack);
if (fs.existsSync(oldPath)) {
fs.unlinkSync(oldPath);
}
}
// 更新服务器的资源包路径
const resourcepackPath = '/resourcepacks/' + req.file.filename;
server.resourcepack = resourcepackPath;
res.json({
url: resourcepackPath,
filename: req.file.originalname
});
} catch (error) {
next(error);
}
});
// 获取资源包信息
app.get('/api/servers/:id/resourcepack', (req, res) => {
try {
const server = servers.find(s => s.id === parseInt(req.params.id));
if (!server) {
return res.status(404).json({ error: '服务器未找到' });
}
if (!server.resourcepack) {
return res.status(404).json({ error: '该服务器没有资源包' });
}
res.json({
url: server.resourcepack,
filename: path.basename(server.resourcepack)
});
} catch (error) {
next(error);
}
});
// 处理404错误
app.use((req, res) => {
if (req.path.startsWith('/api')) {
res.status(404).json({ error: '接口未找到' });
} else {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
}
});
// 启动服务器
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});