-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.js
More file actions
1446 lines (1255 loc) · 50.6 KB
/
Copy pathserver.js
File metadata and controls
1446 lines (1255 loc) · 50.6 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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;
const axios = require('axios');
const NewAPIClient = require('./lib/NewAPIClient');
const sharedModelCache = require('./lib/sharedModelCache');
const { getInstance: getMonitor } = require('./lib/ScheduledMonitor');
const app = express();
const PORT = process.env.PORT || 8083;
const CONFIG_DIR = process.env.CONFIG_DIR
? path.resolve(process.env.CONFIG_DIR)
: __dirname;
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');
const MONITOR_CONFIG_FILE = path.join(CONFIG_DIR, 'monitor-config.json');
const DEFAULT_SECRET_KEY = 'newapi-sync-tool-2024';
const SECRET_KEY = process.env.SECRET_KEY || DEFAULT_SECRET_KEY;
const USING_DEFAULT_SECRET = SECRET_KEY === DEFAULT_SECRET_KEY;
// Startup timestamp
const startTime = Date.now();
// One-click update jobs (in-memory)
const oneClickJobs = new Map(); // jobId -> job
const ONE_CLICK_JOB_TTL_MS = 30 * 60 * 1000; // 30 min
const ONE_CLICK_JOB_MAX_LOGS = 2000;
// Sync checkpoints (in-memory)
const syncCheckpoints = new Map(); // checkpointId -> snapshot
const CHECKPOINT_TTL_MS = 2 * 60 * 60 * 1000; // 2 hours
const CHECKPOINT_MAX = 20;
let latestCheckpointId = null;
const ensureConfigDir = async () => {
await fs.mkdir(CONFIG_DIR, { recursive: true });
};
const createJobId = () => {
return `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
};
const createCheckpointId = () => {
return `cp_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
};
const cleanupExpiredJobs = () => {
const now = Date.now();
for (const [jobId, job] of oneClickJobs.entries()) {
if (!job) {
oneClickJobs.delete(jobId);
continue;
}
const base = job.finishedAt || job.startedAt || job.createdAt || 0;
if (base && now - base > ONE_CLICK_JOB_TTL_MS) {
oneClickJobs.delete(jobId);
}
}
};
const cleanupExpiredCheckpoints = () => {
const now = Date.now();
for (const [checkpointId, checkpoint] of syncCheckpoints.entries()) {
if (!checkpoint) {
syncCheckpoints.delete(checkpointId);
continue;
}
const createdAt = checkpoint.createdAt || 0;
if (createdAt && now - createdAt > CHECKPOINT_TTL_MS) {
syncCheckpoints.delete(checkpointId);
}
}
if (syncCheckpoints.size > CHECKPOINT_MAX) {
const ordered = Array.from(syncCheckpoints.values()).sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0));
const removeCount = Math.max(0, ordered.length - CHECKPOINT_MAX);
for (let i = 0; i < removeCount; i++) {
syncCheckpoints.delete(ordered[i].id);
}
}
if (latestCheckpointId && !syncCheckpoints.has(latestCheckpointId)) {
const newest = Array.from(syncCheckpoints.values()).sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))[0];
latestCheckpointId = newest ? newest.id : null;
}
};
const normalizeBaseUrl = (baseUrl) => String(baseUrl || '').replace(/\/+$/, '');
const cleanToken = (token) => String(token || '').trim().replace(/[\n\r\t]/g, '');
const resolveAuthHeaderType = (authHeaderType) => {
const mapping = {
NEW_API: 'New-Api-User',
VELOERA: 'Veloera-User'
};
const key = String(authHeaderType || 'NEW_API').toUpperCase();
return mapping[key] || mapping.NEW_API;
};
const runWithConcurrency = async (items, concurrency, worker) => {
const results = new Array(items.length);
let index = 0;
const workerCount = Math.min(concurrency, items.length);
const runners = Array.from({ length: workerCount }, async () => {
while (true) {
const current = index;
index += 1;
if (current >= items.length) return;
results[current] = await worker(items[current], current);
}
});
await Promise.all(runners);
return results;
};
const fetchAllChannels = async (client, pageSize = 1000) => {
const parsedPageSize = Number(pageSize);
const safePageSize = Number.isFinite(parsedPageSize) && parsedPageSize > 0
? Math.max(1, Math.min(1000, Math.floor(parsedPageSize)))
: 1000;
const firstPage = await client.getChannels(1, safePageSize);
if (!firstPage.success) {
return firstPage;
}
let channels = Array.isArray(firstPage.data) ? firstPage.data : [];
const total = Number(firstPage.total) || channels.length;
if (total > channels.length) {
const totalPages = Math.ceil(total / safePageSize);
for (let page = 2; page <= totalPages; page += 1) {
const pageResult = await client.getChannels(page, safePageSize);
if (!pageResult.success) {
return pageResult;
}
if (Array.isArray(pageResult.data)) {
channels = channels.concat(pageResult.data);
}
}
}
return {
success: true,
data: channels,
total: channels.length,
page: 1
};
};
const collectChannelIds = async (context, channelIds) => {
if (Array.isArray(channelIds) && channelIds.length > 0) {
return Array.from(new Set(channelIds.map(id => String(id)).filter(Boolean)));
}
const client = new NewAPIClient({
baseUrl: context.baseUrl,
token: context.token,
userId: context.userId,
authHeaderType: context.authHeaderType
});
const channelsResult = await fetchAllChannels(client, 1000);
if (!channelsResult.success) {
throw new Error(`Failed to fetch channels: ${channelsResult.message}`);
}
const channels = Array.isArray(channelsResult.data) ? channelsResult.data : [];
return Array.from(new Set(channels.map(ch => String(ch.id)).filter(Boolean)));
};
const fetchChannelDetail = async (context, channelId) => {
const baseUrl = normalizeBaseUrl(context.baseUrl);
const url = `${baseUrl}/api/channel/${channelId}`;
const headers = {
Authorization: `Bearer ${context.token}`,
'Content-Type': 'application/json',
[resolveAuthHeaderType(context.authHeaderType)]: context.userId
};
const response = await axios.get(url, { headers, timeout: 15000 });
const data = response?.data?.data;
if (!data) {
throw new Error(`Invalid channel detail response: ${channelId}`);
}
if (data.id == null) {
data.id = channelId;
}
return data;
};
const normalizeModels = (models) => {
if (Array.isArray(models)) {
return models.map(m => String(m).trim()).filter(Boolean).join(',');
}
if (models == null) return '';
return String(models);
};
const normalizeModelMapping = (modelMapping) => {
if (modelMapping == null) return null;
if (typeof modelMapping === 'string') {
const trimmed = modelMapping.trim();
return trimmed ? trimmed : null;
}
try {
return JSON.stringify(modelMapping);
} catch (error) {
return null;
}
};
const buildChannelUpdatePayload = (channelData) => {
return {
id: channelData.id,
models: normalizeModels(channelData.models),
status: channelData.status ?? 1,
type: channelData.type ?? 1,
test_model: channelData.test_model ?? 'gpt-3.5-turbo',
base_url: channelData.base_url ?? '',
key: channelData.key ?? '',
name: channelData.name ?? '',
weight: channelData.weight ?? 0,
model_mapping: normalizeModelMapping(channelData.model_mapping),
...(channelData.priority !== undefined && { priority: channelData.priority }),
...(channelData.auto_ban !== undefined && { auto_ban: channelData.auto_ban }),
...(channelData.tag !== undefined && { tag: channelData.tag }),
...(channelData.group !== undefined && { group: channelData.group })
};
};
const updateChannelSnapshot = async (context, channelData) => {
const baseUrl = normalizeBaseUrl(context.baseUrl);
const url = `${baseUrl}/api/channel/`;
const headers = {
Authorization: `Bearer ${context.token}`,
'Content-Type': 'application/json',
[resolveAuthHeaderType(context.authHeaderType)]: context.userId
};
const payload = buildChannelUpdatePayload(channelData);
await axios.put(url, payload, { headers, timeout: 20000 });
};
// Middlewares
// CORS: restrict to an explicit allowlist when ALLOWED_ORIGINS is set
// (comma-separated). Defaults to the previous permissive behaviour so existing
// deployments are unaffected, but exposing the API publicly should set this.
const allowedOrigins = String(process.env.ALLOWED_ORIGINS || '')
.split(',')
.map((s) => s.trim())
.filter(Boolean);
app.use(cors(allowedOrigins.length > 0
? {
origin: (origin, callback) => {
// Allow same-origin / non-browser requests (no Origin header)
if (!origin || allowedOrigins.includes(origin)) {
return callback(null, true);
}
return callback(new Error('Not allowed by CORS'));
}
}
: undefined));
app.use(express.json({ charset: 'utf-8' }));
app.use(express.urlencoded({ extended: true, charset: 'utf-8' }));
app.use(express.static(path.join(__dirname, 'public')));
// 设置响应头确保 UTF-8 编码
app.use((req, res, next) => {
res.setHeader('Content-Type', 'application/json; charset=utf-8');
next();
});
// Simple request logger
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
next();
});
// Read and decrypt the persisted config (returns null when absent/invalid).
const getStoredConfig = async () => {
try {
const configData = await fs.readFile(CONFIG_FILE, 'utf8');
const encrypted = JSON.parse(configData);
return NewAPIClient.decryptConfig(encrypted, SECRET_KEY);
} catch (error) {
return null;
}
};
// Credential fallback: the access token is only ever persisted server-side
// (AES-encrypted in config.json). The browser sends requests without a token,
// and we fill it in from the stored config here. The stored token is injected
// only when the request targets the same baseUrl it was saved for, so it can
// never be leaked to a different server supplied by the client.
app.use(async (req, res, next) => {
if (req.method === 'GET') return next();
if (!req.path.startsWith('/api/')) return next();
// /api/config saves credentials (needs the real token in the body) and
// /api/monitor/* uses its own stored config — skip both.
if (req.path === '/api/config' || req.path.startsWith('/api/monitor')) return next();
const src = req.body;
if (!src || typeof src !== 'object') return next();
const hasToken = src.token != null && String(src.token).trim() !== '';
if (hasToken) return next();
try {
const stored = await getStoredConfig();
if (!stored || !stored.token) return next();
// Only inject the stored token for its own server.
if (src.baseUrl && normalizeBaseUrl(src.baseUrl) !== normalizeBaseUrl(stored.baseUrl)) {
return next();
}
if (!src.baseUrl) src.baseUrl = stored.baseUrl;
if (!src.userId) src.userId = stored.userId;
if (src.authHeaderType == null && stored.authHeaderType) src.authHeaderType = stored.authHeaderType;
src.token = stored.token;
} catch (error) {
// Fall through with whatever the client supplied.
}
next();
});
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Status endpoint (for frontend compatibility)
app.get('/api/status', async (req, res) => {
try {
res.json({
success: true,
message: '服务器正常运行',
data: {
version: '4.0.0',
timestamp: new Date().toISOString(),
uptime: Math.floor((Date.now() - startTime) / 1000)
}
});
} catch (error) {
res.status(500).json({ success: false, message: '状态检查失败', error: error.message });
}
});
// Channel list endpoint (GET for frontend compatibility)
app.get('/api/channel/', async (req, res) => {
try {
let { baseUrl, token, userId, authHeaderType } = req.query;
// Fall back to the stored, server-side encrypted token when absent.
if (!token) {
const stored = await getStoredConfig();
if (stored && stored.token && (!baseUrl || normalizeBaseUrl(baseUrl) === normalizeBaseUrl(stored.baseUrl))) {
baseUrl = baseUrl || stored.baseUrl;
userId = userId || stored.userId;
authHeaderType = authHeaderType || stored.authHeaderType;
token = stored.token;
}
}
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType });
const requestedPageSize = req.query.pageSize || req.query.page_size;
const result = await fetchAllChannels(client, requestedPageSize || 1000);
res.json(result);
} catch (error) {
res.status(500).json({ success: false, message: '获取渠道失败', error: error.message });
}
});
// Health (enhanced)
app.get('/api/health', (req, res) => {
const uptime = Math.floor((Date.now() - startTime) / 1000);
const memoryUsage = process.memoryUsage();
res.json({
success: true,
message: '服务器正常运行',
timestamp: new Date().toISOString(),
version: '4.0.0',
uptime,
memory: {
rss: Math.round(memoryUsage.rss / 1024 / 1024),
heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024),
heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024),
},
nodeVersion: process.version,
platform: process.platform,
});
});
// Config management
app.get('/api/config', async (req, res) => {
try {
const configData = await fs.readFile(CONFIG_FILE, 'utf8');
const encrypted = JSON.parse(configData);
const config = NewAPIClient.decryptConfig(encrypted, SECRET_KEY);
const safeConfig = {
baseUrl: config.baseUrl,
userId: config.userId,
hasConfig: true,
};
res.json({ success: true, config: safeConfig });
} catch (error) {
res.json({ success: true, config: { hasConfig: false } });
}
});
app.post('/api/config', async (req, res) => {
try {
const { baseUrl, token, userId } = req.body;
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const config = { baseUrl, token, userId };
const encrypted = NewAPIClient.encryptConfig(config, SECRET_KEY);
await ensureConfigDir();
await fs.writeFile(CONFIG_FILE, JSON.stringify(encrypted, null, 2), 'utf8');
res.json({ success: true, message: '配置保存成功' });
} catch (error) {
res.status(500).json({ success: false, message: '配置保存失败', error: error.message });
}
});
// Connection test
app.post('/api/test-connection', async (req, res) => {
try {
const { baseUrl, token, userId, quickTest, authHeaderType } = req.body;
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType });
const result = quickTest ? await client.quickConnectionTest() : await client.testConnection();
res.json(result);
} catch (error) {
res.status(500).json({ success: false, message: '连接测试失败', error: error.message });
}
});
// Channels list
app.post('/api/channels', async (req, res) => {
try {
const { baseUrl, token, userId, authHeaderType, pageSize } = req.body;
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType });
const result = await fetchAllChannels(client, pageSize || 1000);
res.json(result);
} catch (error) {
res.status(500).json({ success: false, message: '获取渠道失败', error: error.message });
}
});
// Sync models
app.post('/api/sync-models', async (req, res) => {
try {
const { baseUrl, token, userId, modelMapping, authHeaderType, modelUpdateMode, channelIds } = req.body;
console.log('📊 收到同步请求:');
console.log('- modelMapping keys数量:', Object.keys(modelMapping || {}).length);
console.log('- modelMapping前5个:', Object.entries(modelMapping || {}).slice(0, 5));
console.log('- modelUpdateMode:', modelUpdateMode || 'append');
console.log('- 指定渠道数量:', channelIds ? channelIds.length : '未指定(同步所有渠道)');
if (!baseUrl || !token || !userId || !modelMapping) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType });
const result = await client.syncModels(modelMapping, modelUpdateMode || 'append', channelIds);
console.log('✅ 同步完成, 结果:', {
success: result.success,
stats: result.stats
});
res.json(result);
} catch (error) {
console.error('❌ 同步失败:', error);
res.status(500).json({ success: false, message: '模型同步失败', error: error.message });
}
});
// Create sync checkpoint
app.post('/api/checkpoint/create', async (req, res) => {
try {
cleanupExpiredCheckpoints();
const { baseUrl, token, userId, authHeaderType, channelIds, tag, concurrency } = req.body || {};
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const context = {
baseUrl: normalizeBaseUrl(baseUrl),
token: cleanToken(token),
userId,
authHeaderType: authHeaderType || 'NEW_API'
};
const resolvedIds = await collectChannelIds(context, channelIds);
if (!resolvedIds || resolvedIds.length === 0) {
return res.json({ success: false, message: '无可创建检查点的渠道' });
}
const concurrencyRaw = Number(concurrency);
const workerCount = Number.isFinite(concurrencyRaw)
? Math.max(1, Math.min(10, Math.floor(concurrencyRaw)))
: 6;
const snapshots = [];
const errors = [];
await runWithConcurrency(resolvedIds, workerCount, async (channelId) => {
try {
const detail = await fetchChannelDetail(context, channelId);
snapshots.push({
id: detail.id,
name: detail.name,
models: detail.models,
model_mapping: detail.model_mapping,
status: detail.status,
type: detail.type,
test_model: detail.test_model,
base_url: detail.base_url,
key: detail.key,
weight: detail.weight,
priority: detail.priority,
auto_ban: detail.auto_ban,
tag: detail.tag,
group: detail.group
});
} catch (e) {
errors.push({ channelId: String(channelId), error: e.message });
}
});
if (snapshots.length === 0) {
return res.json({ success: false, message: '检查点创建失败,未成功获取任何渠道', errors });
}
const checkpointId = createCheckpointId();
const checkpoint = {
id: checkpointId,
createdAt: Date.now(),
count: snapshots.length,
channelIds: snapshots.map(snapshot => String(snapshot.id)),
baseUrl: context.baseUrl,
userId: String(context.userId),
authHeaderType: context.authHeaderType || 'NEW_API',
tag: tag ? String(tag).trim() : null,
data: snapshots
};
syncCheckpoints.set(checkpointId, checkpoint);
latestCheckpointId = checkpointId;
cleanupExpiredCheckpoints();
res.json({
success: true,
checkpointId,
createdAt: checkpoint.createdAt,
count: checkpoint.count,
failed: errors.length,
errors
});
} catch (error) {
res.status(500).json({ success: false, message: '创建检查点失败', error: error.message });
}
});
// Restore sync checkpoint
app.post('/api/checkpoint/restore', async (req, res) => {
try {
cleanupExpiredCheckpoints();
const { baseUrl, token, userId, authHeaderType, checkpointId, concurrency } = req.body || {};
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const resolvedId = checkpointId || latestCheckpointId;
if (!resolvedId) {
return res.status(404).json({ success: false, message: '未找到可用的检查点' });
}
const checkpoint = syncCheckpoints.get(resolvedId);
if (!checkpoint) {
return res.status(404).json({ success: false, message: '检查点不存在或已过期' });
}
const context = {
baseUrl: normalizeBaseUrl(baseUrl),
token: cleanToken(token),
userId,
authHeaderType: authHeaderType || 'NEW_API'
};
if (checkpoint.baseUrl && normalizeBaseUrl(checkpoint.baseUrl) !== context.baseUrl) {
return res.status(400).json({ success: false, message: '检查点与当前服务器不一致,已取消回退' });
}
if (checkpoint.userId && String(checkpoint.userId) !== String(context.userId)) {
return res.status(400).json({ success: false, message: '检查点与当前用户不一致,已取消回退' });
}
const snapshots = Array.isArray(checkpoint.data) ? checkpoint.data : [];
if (snapshots.length === 0) {
return res.json({ success: false, message: '检查点无可回退数据' });
}
const concurrencyRaw = Number(concurrency);
const workerCount = Number.isFinite(concurrencyRaw)
? Math.max(1, Math.min(10, Math.floor(concurrencyRaw)))
: 6;
const errors = [];
let restored = 0;
await runWithConcurrency(snapshots, workerCount, async (snapshot) => {
try {
await updateChannelSnapshot(context, snapshot);
restored += 1;
} catch (e) {
errors.push({ channelId: String(snapshot.id), error: e.message });
}
});
res.json({
success: restored > 0,
checkpointId: resolvedId,
restored,
failed: errors.length,
errors,
message: restored > 0 ? '回退完成' : '回退失败'
});
} catch (error) {
res.status(500).json({ success: false, message: '回退检查点失败', error: error.message });
}
});
// Get latest checkpoint
app.get('/api/checkpoint/latest', (req, res) => {
cleanupExpiredCheckpoints();
if (!latestCheckpointId || !syncCheckpoints.has(latestCheckpointId)) {
return res.json({ success: false, message: '无可用的检查点' });
}
const checkpoint = syncCheckpoints.get(latestCheckpointId);
res.json({
success: true,
checkpoint: {
id: checkpoint.id,
createdAt: checkpoint.createdAt,
count: checkpoint.count,
channelIds: checkpoint.channelIds,
tag: checkpoint.tag
}
});
});
// Channel models (prefer fetch_models, fallback)
app.post('/api/channel-models', async (req, res) => {
try {
const { baseUrl, token, userId, channelId, authHeaderType, fetchAll = true, includeDisabled = true, fetchSelectedOnly = false, fetchChannelConfig = false, forceRefresh = false } = req.body;
if (!baseUrl || !token || !userId || !channelId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const cleanToken = String(token).trim().replace(/[\n\r\t]/g, '');
const resolvedAuthHeaderType = authHeaderType || 'NEW_API';
// 如果是获取渠道配置(用于重定向检查)
if (fetchChannelConfig) {
const channelUrl = `${baseUrl.replace(/\/+$/, '')}/api/channel/${channelId}`;
console.log(`[DEBUG] 获取渠道详细配置: ${channelUrl}`);
try {
const response = await axios.get(channelUrl, {
headers: {
Authorization: `Bearer ${cleanToken}`,
'New-Api-User': userId,
'Content-Type': 'application/json',
},
timeout: 15000,
});
const data = response.data;
if (data && data.data) {
console.log(`[DEBUG] 成功获取渠道配置,包含模型映射: ${!!data.data.model_mapping}`);
res.json({
success: true,
data: {
id: channelId,
name: data.data.name || `渠道 ${channelId}`,
model_mapping: data.data.model_mapping || {},
models: data.data.models,
status: data.data.status
},
message: '成功获取渠道详细配置'
});
return;
}
console.log('[DEBUG] 渠道配置响应无有效数据');
} catch (e) {
console.log(`[DEBUG] 获取渠道配置失败: ${e.message}`);
}
res.json({ success: false, message: '无法获取渠道详细配置' });
return;
}
// 如果是获取已选择的模型,使用不同的端点
if (fetchSelectedOnly) {
const selectedUrl = `${baseUrl.replace(/\/+$/, '')}/api/channel/${channelId}`;
console.log(`[DEBUG] 获取已选择的模型: ${selectedUrl}`);
try {
const response = await axios.get(selectedUrl, {
headers: {
Authorization: `Bearer ${cleanToken}`,
'New-Api-User': userId,
'Content-Type': 'application/json',
},
timeout: 15000,
});
const data = response.data;
if (data && data.data && data.data.models) {
// 处理已选择的模型
let selectedModels = [];
if (typeof data.data.models === 'string') {
selectedModels = data.data.models.split(',').map(m => m.trim()).filter(m => m);
} else if (Array.isArray(data.data.models)) {
selectedModels = data.data.models;
}
console.log(`[DEBUG] 成功获取 ${selectedModels.length} 个已选择的模型:`, selectedModels.slice(0, 5));
res.json({ success: true, data: selectedModels, message: `成功获取 ${selectedModels.length} 个已选择的模型` });
return;
}
} catch (e) {
console.log(`[DEBUG] 获取已选择模型失败: ${e.message}`);
// 如果获取已选择模型失败,返回空数组
res.json({ success: true, data: [], message: '未找到已选择的模型' });
return;
}
}
const cacheContext = { baseUrl, token: cleanToken, userId, authHeaderType: resolvedAuthHeaderType, channelId };
if (forceRefresh) {
sharedModelCache.deleteProviderModels(cacheContext);
} else {
const cached = sharedModelCache.getProviderModels(cacheContext);
if (cached && cached.length > 0) {
console.log(`[DEBUG] 使用共享缓存获取 ${cached.length} 个模型`);
res.json({ success: true, data: cached, message: `从缓存获取 ${cached.length} 个模型`, source: 'shared-cache' });
return;
}
}
const client = new NewAPIClient({ baseUrl, token: cleanToken, userId, authHeaderType: resolvedAuthHeaderType });
const providerResult = await client.fetchActualProviderModels(channelId, { forceRefresh: Boolean(forceRefresh) });
if (providerResult && providerResult.success) {
const models = Array.isArray(providerResult.data) ? providerResult.data : [];
res.json({ success: true, data: models, message: `成功获取 ${models.length} 个模型`, source: providerResult.source || 'fetch_models' });
return;
}
const result = await client.getChannelModels(channelId, Boolean(forceRefresh));
res.json(result);
} catch (error) {
console.error(`[ERROR] 获取渠道模型失败: ${error.message}`);
res.status(500).json({ success: false, message: '获取渠道模型失败', error: error.message });
}
});
// Channel detail (for redirect checking)
app.post('/api/channel-detail', async (req, res) => {
try {
const { baseUrl, token, userId, channelId, authHeaderType } = req.body;
if (!baseUrl || !token || !userId || !channelId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const cleanToken = String(token).trim().replace(/[\n\r\t]/g, '');
const channelUrl = `${baseUrl.replace(/\/+$/, '')}/api/channel/${channelId}`;
console.log(`[DEBUG] 获取渠道详细配置: ${channelUrl}`);
try {
const response = await axios.get(channelUrl, {
headers: {
Authorization: `Bearer ${cleanToken}`,
'New-Api-User': userId,
'Content-Type': 'application/json',
},
timeout: 15000,
});
const data = response.data;
if (data && data.data) {
console.log(`[DEBUG] 成功获取渠道配置,包含模型映射: ${!!data.data.model_mapping}`);
res.json({
success: true,
data: {
id: channelId,
name: data.data.name || `渠道 ${channelId}`,
model_mapping: data.data.model_mapping || {},
// 其他可能的配置字段
models: data.data.models,
status: data.data.status
},
message: '成功获取渠道详细配置'
});
return;
}
console.log('[DEBUG] 渠道配置响应无有效数据');
} catch (e) {
console.log(`[DEBUG] 获取渠道配置失败: ${e.message}`);
}
res.json({ success: false, message: '无法获取渠道详细配置' });
} catch (error) {
console.error(`[ERROR] 获取渠道详细配置失败: ${error.message}`);
res.status(500).json({ success: false, message: '获取渠道详细配置失败', error: error.message });
}
});
// Global models
app.post('/api/global-models', async (req, res) => {
try {
const { baseUrl, token, userId, authHeaderType } = req.body;
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType });
const result = await client.getAllModels();
res.json(result);
} catch (error) {
res.status(500).json({ success: false, message: '获取全局模型失败', error: error.message });
}
});
// Debug API endpoints
app.post('/api/debug-api', async (req, res) => {
try {
const { baseUrl, token, userId, authHeaderType } = req.body;
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType });
const result = await client.debugAPIEndpoints();
res.json(result);
} catch (error) {
res.status(500).json({ success: false, message: 'API 调试失败', error: error.message });
}
});
// One-click update models - 一键更新模型
app.post('/api/one-click-update', async (req, res) => {
try {
const { baseUrl, token, userId, authHeaderType, channelIds, dryRun, options = {} } = req.body;
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
console.log('🚀 收到一键更新请求:');
console.log('- 指定渠道:', channelIds ? channelIds.length : '全部');
console.log('- 预览模式:', dryRun ? '是' : '否');
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType, debug: Boolean(options.debug) });
const result = dryRun
? await client.previewOneClickUpdate(channelIds, options)
: await client.oneClickUpdateModels(channelIds, options);
console.log('✅ 一键更新完成:', {
success: result.success,
scanned: result.results?.scannedChannels,
updated: result.results?.updatedChannels,
fixed: result.results?.fixedMappings
});
res.json(result);
} catch (error) {
console.error('❌ 一键更新失败:', error);
res.status(500).json({ success: false, message: '一键更新失败', error: error.message });
}
});
// Preview one-click update - 预览一键更新
app.post('/api/preview-one-click-update', async (req, res) => {
try {
const { baseUrl, token, userId, authHeaderType, channelIds, options = {} } = req.body;
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
console.log('🔍 收到一键更新预览请求');
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType, debug: Boolean(options.debug) });
const result = await client.previewOneClickUpdate(channelIds, options);
console.log('✅ 预览完成:', {
brokenMappings: result.results?.brokenMappings?.length || 0,
newMappings: result.results?.newMappings?.length || 0
});
res.json(result);
} catch (error) {
console.error('❌ 预览失败:', error);
res.status(500).json({ success: false, message: '预览失败', error: error.message });
}
});
// ==================== One-click update job APIs ====================
// Start a one-click preview/update job (async)
app.post('/api/one-click-update-job', async (req, res) => {
try {
cleanupExpiredJobs();
const {
baseUrl,
token,
userId,
authHeaderType,
channelIds,
dryRun = true,
fromPreviewJobId,
options = {},
rules = null, // 用户规则参数
selectedMappings = null // 新增:选中的映射列表
} = req.body || {};
if (!baseUrl || !token || !userId) {
return res.status(400).json({ success: false, message: '请填写完整的配置信息' });
}
// 日志记录规则信息
if (rules) {
console.log('📋 收到用户规则:');
console.log('- 名称匹配规则:', rules.nameMatch?.length || 0);
console.log('- 合并规则:', rules.merge?.length || 0);
console.log('- 自定义规则:', rules.custom?.length || 0);
}
const jobId = createJobId();
const createdAt = Date.now();
const job = {
id: jobId,
type: dryRun ? 'preview' : 'execute',
sourcePreviewJobId: fromPreviewJobId || null,
createdAt,
startedAt: Date.now(),
finishedAt: null,
cancelled: false,
status: 'running', // running | completed | failed | cancelled
message: '',
progress: { current: 0, total: 0, percent: 0, stage: dryRun ? 'preview' : 'execute' },
logs: [],
results: null,
error: null
};
const appendLog = (msg, type = 'info') => {
const entry = { ts: Date.now(), type, msg: String(msg ?? '') };
job.logs.push(entry);
if (job.logs.length > ONE_CLICK_JOB_MAX_LOGS) {
job.logs.splice(0, job.logs.length - ONE_CLICK_JOB_MAX_LOGS);
}
};
oneClickJobs.set(jobId, job);
// Fire and forget async work
(async () => {
try {
const client = new NewAPIClient({ baseUrl, token, userId, authHeaderType, debug: Boolean(options.debug) });
const runOptions = {
...options,
rules, // 传递用户规则
onLog: (msg, type) => appendLog(msg, type),
onProgress: (p) => { job.progress = { ...job.progress, ...p }; },
shouldAbort: () => job.cancelled
};