-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServer.js
More file actions
598 lines (515 loc) · 21 KB
/
Copy pathServer.js
File metadata and controls
598 lines (515 loc) · 21 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
import cors from 'cors';
import multer from 'multer';
import express from 'express';
import { createCanvas, loadImage } from 'canvas';
import { Logger } from './Scripts/Logger.js';
import { fetchMojangProfile, fetchSkinWebsiteProfile } from './Scripts/Network.js';
import { renderAvatar, renderBackground, regulateAvatar } from './Scripts/Index.js';
import { initializeCache } from './Scripts/Cache.js';
import { config } from './Config.js';
// 初始化缓存
const avatarCache = initializeCache(config);
const app = express();
const version = '1.0.3';
// 中间件
app.use(cors());
app.use(express.json());
// 文件上传配置
const upload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 2 * 1024 * 1024 }, // 2MB限制
fileFilter: (_req, file, cb) => {
if (file.mimetype.startsWith('image/')) cb(null, true);
else cb(new Error('只支持图片文件'), false);
}
});
async function getSkinImage(method, data) {
Logger.log('SkinLoader', `开始获取皮肤,方式:${method}`);
switch (method) {
case 'mojang':
Logger.log('SkinLoader', `Mojang 模式 - 用户名 ${data.username}`);
const profile = await fetchMojangProfile(data.username);
if (!profile) {
Logger.error('SkinLoader', `未找到玩家信息:${data.username}`);
throw new Error('未找到该玩家信息');
}
const textureResponse = await fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${profile.id}?unsigned=false`);
if (!textureResponse.ok)
throw new Error(`获取纹理信息失败:${textureResponse.status}`);
const textureData = await textureResponse.json();
if (!textureData.properties || !textureData.properties[0])
throw new Error('纹理数据不存在!');
const textureInfo = JSON.parse(Buffer.from(textureData.properties[0].value, 'base64').toString());
const skinUrl = textureInfo.textures.SKIN.url;
const skinImage = await loadImage(skinUrl);
Logger.log('SkinLoader', `皮肤加载成功 - ${skinImage.width}x${skinImage.height}`);
return skinImage;
case 'website':
Logger.log('SkinLoader', `皮肤站模式 - ${data.website}/${data.username}`);
const website = data.website.startsWith('https://') ? data.website : 'https://' + data.website;
const skinData = await fetchSkinWebsiteProfile(website, data.username);
if (!skinData || !skinData.skins) {
Logger.error('SkinLoader', `皮肤站未找到玩家:${data.username}`);
throw new Error('未找到该玩家的皮肤数据');
}
const texturePath = Object.values(skinData.skins)[0];
const textureUrl = `${website}/textures/${texturePath}`;
const websiteSkinImage = await loadImage(textureUrl);
Logger.log('SkinLoader', `皮肤站图片加载成功 - ${websiteSkinImage.width}x${websiteSkinImage.height}`);
return websiteSkinImage;
case 'upload':
Logger.log('SkinLoader', `上传模式 - ${data.skinBuffer?.length || 0} Bytes`);
if (!data.skinBuffer) {
Logger.error('SkinLoader', '上传模式但未找到文件数据');
throw new Error('未找到上传的皮肤文件');
}
const uploadSkinImage = await loadImage(data.skinBuffer);
Logger.log('SkinLoader', `上传图片加载成功 - ${uploadSkinImage.width}x${uploadSkinImage.height}`);
return uploadSkinImage;
case 'url':
Logger.log('SkinLoader', `URL 模式 - ${data.skinUrl}`);
if (!data.skinUrl) {
Logger.error('SkinLoader', 'URL 模式但未提供皮肤链接');
throw new Error('请提供有效的皮肤图片链接');
}
const urlSkinImage = await loadImage(data.skinUrl);
Logger.log('SkinLoader', `URL 图片加载成功 - ${urlSkinImage.width}x${urlSkinImage.height}`);
return urlSkinImage;
default:
Logger.error('SkinLoader', `不支持的获取方式:${method}`);
throw new Error('请提供有效的皮肤获取方式(Mojang、Website、Upload)');
}
}
// 统一错误处理函数
function handleApiError(error, res, context = 'Generator') {
Logger.error(context, '操作失败', error);
let statusCode = 500;
let errorMessage = error.message;
if (error.message.includes('未找到该玩家信息'))
statusCode = 404;
else if (error.message.includes('参数错误') || error.message.includes('格式错误') || error.message.includes('选项格式错误'))
statusCode = 400;
else if (error.message.includes('ECONNRESET') || error.message.includes('fetch failed'))
errorMessage = '网络连接失败,请稍后重试';
else if (error.message.includes('ETIMEDOUT'))
errorMessage = '请求超时,请稍后重试';
res.status(statusCode).json({
success: false,
message: errorMessage
});
}
// 生成头像图片的核心函数(带缓存)
async function generateAvatarImage(method, skinData, modelType, generateOptions, backgroundOptions) {
Logger.log('Generator', `开始生成头像 - 模型:${modelType},方式:${method}`);
// 如果缓存被禁用,直接生成
if (!config.cacheEnabled) {
Logger.log('Generator', '缓存已禁用,直接生成头像');
return await generateAvatarImageDirect(method, skinData, modelType, generateOptions, backgroundOptions);
}
// 尝试从缓存获取
const cachedBuffer = await avatarCache.get(method, skinData, modelType, generateOptions, backgroundOptions);
if (cachedBuffer) {
Logger.log('Generator', `缓存命中,直接返回 - ${cachedBuffer.length} Bytes`);
return cachedBuffer;
}
// 缓存未命中,生成新头像
Logger.log('Generator', '缓存未命中,开始生成新头像');
const buffer = await generateAvatarImageDirect(method, skinData, modelType, generateOptions, backgroundOptions);
// 异步保存到缓存(不阻塞响应)
if (config.cacheEnabled) {
avatarCache.set(method, skinData, modelType, generateOptions, backgroundOptions, buffer)
.catch(error => Logger.error('Generator', '保存缓存失败', error));
}
return buffer;
}
// 直接生成头像图片(不使用缓存)
async function generateAvatarImageDirect(method, skinData, modelType, generateOptions, backgroundOptions) {
// 获取皮肤图片
const skinImage = await getSkinImage(method, skinData);
// 生成头像
Logger.log('Generator', `开始渲染 - 模型:${modelType}`);
const avatarCanvas = renderAvatar(skinImage, modelType, generateOptions);
const regulatedAvatarCanvas = regulateAvatar(avatarCanvas, generateOptions);
let finalCanvas;
// 根据 backgroundOptions 是否为空决定是否添加背景
if (backgroundOptions && Object.keys(backgroundOptions).length > 0) {
Logger.log('Generator', '生成背景');
const backgroundCanvas = renderBackground(modelType, backgroundOptions);
finalCanvas = createCanvas(1000, 1000);
const context = finalCanvas.getContext('2d');
context.drawImage(backgroundCanvas, 0, 0);
context.drawImage(regulatedAvatarCanvas, 0, 0);
} else {
Logger.log('Generator', '无背景模式');
finalCanvas = regulatedAvatarCanvas;
}
// 返回图片buffer
const buffer = finalCanvas.toBuffer('image/png');
Logger.log('Generator', `生成完成 - ${buffer.length} Bytes`);
return buffer;
}
// 请求日志验证中间件
app.use((req, res, next) => {
const startTime = Date.now();
const ip = req.headers['x-forwarded-for'] || req.ip || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress || 'Unknown IP';
Logger.log('Server', `(${ip}) ${req.method} ${req.url}`);
// 记录响应时间
res.on('finish', () => {
const duration = Date.now() - startTime;
Logger.log('Server', `(${ip}) ${res.statusCode} - ${duration}ms ${req.url}`);
});
if (config.apiToken || config.cacheApiToken) {
const token = (req.headers['Authorization'].replace('Bearer ', '') || req.query.token || req.body.token) ?? '';
if ((config.apiToken && config.apiToken != token) || (config.cacheApiToken && req.url.includes('cache') && config.cacheApiToken != token)) {
res.status(502).json({
success: false,
message: '无效的 API Token 请检查!'
});
return;
}
}
next();
});
app.get('/health', async (_req, res) => {
const memoryUsage = process.memoryUsage();
const uptime = process.uptime();
try {
const cacheStats = await avatarCache.getStats();
res.json({
status: 'ok',
version,
message: 'Minecraft 头像生成器服务运行正常!',
uptime: `${Math.floor(uptime / 60)}分${Math.floor(uptime % 60)}秒`,
memory: {
used: `${Math.round(memoryUsage.heapUsed / 1024 / 1024)}MB`,
total: `${Math.round(memoryUsage.heapTotal / 1024 / 1024)}MB`
},
cache: cacheStats ? {
diskFiles: cacheStats.diskCache.files,
diskSize: cacheStats.diskCache.sizeFormatted,
memoryItems: cacheStats.memoryCache.items
} : null,
timestamp: new Date().toISOString()
});
} catch (error) {
// 如果获取缓存统计失败,仍然返回基本健康信息
res.json({
status: 'ok',
version,
message: 'Minecraft 头像生成器服务运行正常!',
uptime: `${Math.floor(uptime / 60)}分${Math.floor(uptime % 60)}秒`,
memory: {
used: `${Math.round(memoryUsage.heapUsed / 1024 / 1024)}MB`,
total: `${Math.round(memoryUsage.heapTotal / 1024 / 1024)}MB`
},
cache: null,
timestamp: new Date().toISOString()
});
}
});
// 生成头像API
app.post('/api/generate', upload.single('skin'), async (req, res) => {
Logger.log('Generator', '开始处理头像生成请求!');
try {
const {
method,
username,
website,
modelType = 'minimal',
generateOptions = {},
backgroundOptions = {},
} = req.body;
if (!method) {
Logger.error('Generator', '参数错误:缺少 Method 参数');
return res.status(400).json({
success: false,
message: '请指定皮肤获取方式 (Mojang、Website、Upload) !'
});
}
// 验证必填参数
if (method === 'mojang' && !username) {
Logger.error('Generator', 'Mojang 模式缺少 Username');
return res.status(400).json({
success: false,
message: 'Mojang 模式需要提供 Username 参数!'
});
}
if (method === 'website' && (!username || !website)) {
Logger.error('Generator', 'Website 模式缺少必要参数');
return res.status(400).json({
success: false,
message: 'Website 模式需要提供 Username 和 Website 参数'
});
}
if (method === 'upload' && !req.file) {
Logger.error('Generator', 'Upload 模式缺少文件');
return res.status(400).json({
success: false,
message: 'Upload 模式需要上传皮肤文件'
});
}
// 解析JSON字符串参数
const parsedGenerateOptions = typeof generateOptions === 'string' ? JSON.parse(generateOptions) : generateOptions;
const parsedBackgroundOptions = typeof backgroundOptions === 'string' ? JSON.parse(backgroundOptions) : backgroundOptions;
// 设置默认选项
const defaultGenerateOptions = {
type: 'head',
scale: 100,
shadow: 50,
texture: true,
color: '#FFFFFF',
border: 1,
...parsedGenerateOptions
};
// 处理背景选项 - 空对象或null时不生成背景
const finalBackgroundOptions = parsedBackgroundOptions && Object.keys(parsedBackgroundOptions).length > 0
? parsedBackgroundOptions
: null;
// 准备皮肤数据
const skinData = { username, website, skinBuffer: req.file?.buffer };
// 生成头像图片
const buffer = await generateAvatarImage(
method,
skinData,
modelType,
defaultGenerateOptions,
finalBackgroundOptions
);
res.set({
'Content-Type': 'image/png',
'Content-Length': buffer.length,
'Cache-Control': 'public, max-age=3600'
});
res.send(buffer);
} catch (error) {
// 特殊处理JSON解析错误
if (error instanceof SyntaxError && error.message.includes('JSON'))
return res.status(400).json({
success: false,
message: '选项格式错误,请提供有效的 JSON'
});
handleApiError(error, res, 'Generator');
}
});
// GET模式头像生成API - 支持URL参数
app.get('/api/generate/:modelType/:method/:username', async (req, res) => {
Logger.log('Generator', '开始处理 GET 模式头像生成请求');
try {
const { method, username, modelType } = req.params;
const {
scale = 100,
shadow = 50,
texture = 'true',
color = '#FFFFFF',
border = 1,
type = 'head',
angle = 45,
colors = '["#87CEEB", "#FFB6C1"]',
stripes = 5,
vignette = 30,
skinUrl = null
} = req.query;
// 验证method参数
if (!['mojang', 'website', 'url'].includes(method)) {
return res.status(400).json({
success: false,
message: 'GET 模式只支持 Mojang、Website、URL 三种方式'
});
}
// 验证必填参数
if (method === 'mojang' && !username) {
return res.status(400).json({
success: false,
message: 'Mojang 模式需要提供 Username 参数'
});
}
if (method === 'website' && !username) {
return res.status(400).json({
success: false,
message: 'Website 模式需要提供 Username 参数'
});
}
if (method === 'url' && !skinUrl) {
return res.status(400).json({
success: false,
message: 'URL 模式需要提供 SkinUrl 参数'
});
}
// 解析参数
const generateOptions = {
type: type === 'half' ? 'half' : type === 'full' ? 'full' : 'head',
scale: Math.max(50, Math.min(200, parseInt(scale) || 100)),
shadow: Math.max(0, Math.min(100, parseInt(shadow) || 50)),
texture: texture === 'true',
color: color,
border: Math.max(0, Math.min(50, parseInt(border) || 1))
};
// 只有当提供了背景相关参数时才生成背景
// 检查是否有任何背景参数被明确设置(不是默认值)
const hasBackgroundParams = req.query.angle || req.query.colors || req.query.stripes || req.query.vignette;
const backgroundOptions = hasBackgroundParams ? {
angle: Math.max(0, Math.min(360, parseInt(angle) || 45)),
colors: JSON.parse(colors),
stripes: Math.max(1, Math.min(20, parseInt(stripes) || 5)),
vignette: Math.max(0, Math.min(100, parseInt(vignette) || 30)),
image: null
} : null;
// 准备皮肤数据
let skinData;
if (method === 'url') skinData = { skinUrl };
else if (method === 'website') skinData = { username, website: 'minecraft.net' };
else skinData = { username };
// 生成头像图片
const buffer = await generateAvatarImage(
method,
skinData,
modelType,
generateOptions,
backgroundOptions
);
res.set({
'Content-Type': 'image/png',
'Content-Length': buffer.length,
'Cache-Control': 'public, max-age=3600'
});
res.send(buffer);
} catch (error) {
// 特殊处理JSON解析错误
if (error instanceof SyntaxError && error.message.includes('JSON')) {
return res.status(400).json({
success: false,
message: '参数格式错误,请提供有效的 JSON'
});
}
handleApiError(error, res, 'GET Generator');
}
});
// 获取支持的模型类型
app.get('/api/models', (_req, res) => {
res.status(200).json({
models: [
{
type: 'minimal',
name: '简约风格',
description: '灵感来源:噪音回放',
options: {
type: ['head', 'half', 'full'],
scale: { min: 50, max: 200, default: 100 },
shadow: { min: 0, max: 100, default: 50 }
}
},
{
type: 'vintage',
name: '复古风格',
description: '灵感来源:Minecraft Skin Avatar',
options: {
scale: { min: 50, max: 200, default: 100 },
border: { min: 0, max: 50, default: 10 },
color: 'string'
}
},
{
type: 'side',
name: '侧面风格',
description: '灵感来源:Henry Packs',
options: {
scale: { min: 50, max: 200, default: 100 },
shadow: { min: 0, max: 100, default: 50 },
texture: { type: 'boolean', default: true }
}
}
]
});
});
// 缓存管理 API
app.get('/api/cache/stats', async (_req, res) => {
try {
const stats = await avatarCache.getStats();
res.json({
success: true,
data: stats
});
} catch (error) {
Logger.error('Cache', '获取缓存统计失败', error);
res.status(500).json({
success: false,
message: '获取缓存统计失败'
});
}
});
// 清空缓存
app.delete('/api/cache', async (_req, res) => {
try {
await avatarCache.clear();
res.json({
success: true,
message: '缓存已清空'
});
} catch (error) {
Logger.error('Cache', '清空缓存失败', error);
res.status(500).json({
success: false,
message: '清空缓存失败'
});
}
});
// 手动触发缓存清理
app.post('/api/cache/cleanup', async (_req, res) => {
try {
await avatarCache.cleanup();
res.json({
success: true,
message: '缓存清理完成'
});
} catch (error) {
Logger.error('Cache', '手动清理缓存失败', error);
res.status(500).json({
success: false,
message: '缓存清理失败'
});
}
});
// 错误处理中间件
app.use((error, req, res, _next) => {
Logger.error('Server', `服务器错误:${req.method} ${req.url}`, error);
if (error instanceof multer.MulterError) {
if (error.code === 'LIMIT_FILE_SIZE')
return res.status(400).json({
success: false,
message: '文件太大!图片不能超过 2MB 的限制。'
});
if (error.code === 'LIMIT_UNEXPECTED_FILE')
return res.status(400).json({
success: false,
message: '文件字段错误!请使用 Skin 字段上传文件。'
});
return res.status(400).json({
success: false,
message: error.message
});
}
// 其他错误
res.status(500).json({
success: false,
message: '服务器处理请求时发生错误,请稍后重试!'
});
});
// 404处理
app.use((_req, res) => {
res.status(404).json({
success: false,
message: '接口不存在!请检查请求路径是否正确。'
});
});
// 启动服务器
app.listen(config.port, () => {
Logger.log('Server', `服务器启动 - http://0.0.0.0:${config.port}`);
// 定期内存监控(每5分钟)
setInterval(() => {
const memoryUsage = process.memoryUsage();
const heapUsedMB = Math.round(memoryUsage.heapUsed / 1024 / 1024);
// 内存使用过高警告
if (heapUsedMB > 500) Logger.warn('Monitor', `内存使用过高:${heapUsedMB}MB`);
}, 5 * 60 * 1000);
});
export default app;