-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathserver.js
More file actions
2139 lines (1868 loc) · 66.1 KB
/
Copy pathserver.js
File metadata and controls
2139 lines (1868 loc) · 66.1 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
require('dotenv').config();
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const path = require('path');
const moment = require('moment');
const fs = require('fs');
const cron = require('node-cron');
const app = express();
const PORT = process.env.PORT || 3000;
const CHATLOG_API_BASE = 'http://127.0.0.1:5030/api/v1';
// DeepSeek API配置
const DEEPSEEK_API_KEY = process.env.DEEPSEEK_API_KEY || 'your-deepseek-api-key-here';
const DEEPSEEK_API_BASE = 'https://api.deepseek.com/v1';
// 定时任务配置 - 使用动态变量
let SCHEDULED_ANALYSIS_TIME = process.env.SCHEDULED_ANALYSIS_TIME || '0 0 8 * * *'; // 默认每天早上8点
let ENABLE_SCHEDULED_ANALYSIS = process.env.ENABLE_SCHEDULED_ANALYSIS === 'true';
let currentCronJob = null; // 保存当前的定时任务实例
// 中间件配置
app.use(cors());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(express.static(path.join(__dirname, 'public')));
// 设置模板引擎
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// 配置moment中文支持
moment.locale('zh-cn');
// CSV解析工具函数
function parseCSV(csvText) {
const lines = csvText.trim().split('\n');
if (lines.length <= 1) return [];
const headers = lines[0].split(',');
const result = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',');
if (values.length === headers.length) {
const obj = {};
headers.forEach((header, index) => {
obj[header.trim()] = values[index].trim();
});
// 过滤掉空行或无效数据
if (obj.UserName || obj.Name || obj.NickName) {
result.push(obj);
}
}
}
return result;
}
// 转换联系人数据格式
function formatContactData(contacts) {
return contacts.map(contact => ({
wxid: contact.UserName || '',
displayName: contact.Remark || contact.NickName || contact.Alias || contact.UserName || '未知联系人',
nickname: contact.NickName || '',
remark: contact.Remark || '',
alias: contact.Alias || ''
})).filter(contact => contact.wxid); // 过滤掉没有wxid的数据
}
// 转换群聊数据格式
function formatChatroomData(chatrooms) {
return chatrooms.map(chatroom => ({
wxid: chatroom.Name || '',
displayName: chatroom.Remark || chatroom.NickName || chatroom.Name || '未知群聊',
nickname: chatroom.NickName || '',
remark: chatroom.Remark || '',
owner: chatroom.Owner || '',
userCount: chatroom.UserCount || '0'
})).filter(chatroom => chatroom.wxid); // 过滤掉没有wxid的数据
}
// 首页路由
app.get('/', (req, res) => {
res.render('index');
});
// API代理路由
// 获取聊天记录
app.get('/api/chatlog', async (req, res) => {
try {
const { time, talker, limit, offset = 0, format = 'json' } = req.query;
const params = new URLSearchParams();
if (time) params.append('time', time);
if (talker) params.append('talker', talker);
// 只有当明确指定limit时才添加该参数(支持不限制查询)
if (limit !== undefined && limit !== '') {
params.append('limit', limit);
}
if (offset) params.append('offset', offset);
if (format) params.append('format', format);
console.log('请求聊天记录 API:', `${CHATLOG_API_BASE}/chatlog?${params}`);
const response = await axios.get(`${CHATLOG_API_BASE}/chatlog?${params}`);
// 调试:记录原始响应的前几条数据
if (Array.isArray(response.data) && response.data.length > 0) {
console.log('聊天记录原始数据示例:', JSON.stringify(response.data[0], null, 2));
console.log('数据字段:', Object.keys(response.data[0]));
} else {
console.log('返回数据格式:', typeof response.data, response.data);
}
res.json(response.data);
} catch (error) {
console.error('获取聊天记录失败:', error.message);
if (error.response) {
console.error('API错误响应:', error.response.status, error.response.data);
}
res.status(500).json({
error: '获取聊天记录失败',
message: error.response?.data?.message || error.message
});
}
});
// 获取联系人列表
app.get('/api/contacts', async (req, res) => {
try {
const response = await axios.get(`${CHATLOG_API_BASE}/contact`);
const csvData = response.data;
const parsedData = parseCSV(csvData);
const formattedData = formatContactData(parsedData);
console.log(`获取到 ${formattedData.length} 个联系人`);
res.json(formattedData);
} catch (error) {
console.error('获取联系人列表失败:', error.message);
res.status(500).json({
error: '获取联系人列表失败',
message: error.response?.data?.message || error.message
});
}
});
// 获取群聊列表
app.get('/api/chatrooms', async (req, res) => {
try {
const response = await axios.get(`${CHATLOG_API_BASE}/chatroom`);
const csvData = response.data;
const parsedData = parseCSV(csvData);
const formattedData = formatChatroomData(parsedData);
console.log(`获取到 ${formattedData.length} 个群聊`);
res.json(formattedData);
} catch (error) {
console.error('获取群聊列表失败:', error.message);
res.status(500).json({
error: '获取群聊列表失败',
message: error.response?.data?.message || error.message
});
}
});
// 获取会话列表
app.get('/api/sessions', async (req, res) => {
try {
const response = await axios.get(`${CHATLOG_API_BASE}/session`);
res.json(response.data);
} catch (error) {
console.error('获取会话列表失败:', error.message);
res.status(500).json({
error: '获取会话列表失败',
message: error.response?.data?.message || error.message
});
}
});
// 获取多媒体内容
app.get('/api/media', async (req, res) => {
try {
const { msgid } = req.query;
if (!msgid) {
return res.status(400).json({ error: '缺少消息ID参数' });
}
const response = await axios.get(`${CHATLOG_API_BASE}/media?msgid=${msgid}`, {
responseType: 'stream'
});
// 设置响应头
if (response.headers['content-type']) {
res.set('Content-Type', response.headers['content-type']);
}
response.data.pipe(res);
} catch (error) {
console.error('获取多媒体内容失败:', error.message);
res.status(500).json({
error: '获取多媒体内容失败',
message: error.response?.data?.message || error.message
});
}
});
// 历史记录管理
const HISTORY_DIR = path.join(__dirname, 'ai_analysis_history');
if (!fs.existsSync(HISTORY_DIR)) {
fs.mkdirSync(HISTORY_DIR, { recursive: true });
}
// 保存分析历史记录
function saveAnalysisHistory(metadata, analysisContent) {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `${metadata.groupName.replace(/[^a-zA-Z0-9\u4e00-\u9fff]/g, '_')}_${metadata.timeRange.replace(/[^0-9-]/g, '_')}_${timestamp}.json`;
const filepath = path.join(HISTORY_DIR, filename);
const historyRecord = {
...metadata,
content: analysisContent,
savedAt: new Date().toISOString()
};
fs.writeFileSync(filepath, JSON.stringify(historyRecord, null, 2), 'utf8');
return filename.replace('.json', '');
}
// 获取分析历史记录列表
function getAnalysisHistory() {
try {
const files = fs.readdirSync(HISTORY_DIR)
.filter(file => file.endsWith('.json'))
.map(file => {
const filepath = path.join(HISTORY_DIR, file);
const content = JSON.parse(fs.readFileSync(filepath, 'utf8'));
return {
id: file.replace('.json', ''),
title: `${content.groupName} - ${content.timeRange}`,
timestamp: content.savedAt,
analysisType: content.analysisType,
messageCount: content.messageCount,
groupName: content.groupName,
timeRange: content.timeRange
};
})
.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
return files;
} catch (error) {
console.error('获取历史记录失败:', error);
return [];
}
}
// AI分析相关函数
async function getChatData(talker, timeRange = '2024-01-01~2025-12-31') {
try {
const params = new URLSearchParams();
params.append('time', timeRange);
params.append('talker', talker);
params.append('limit', '500'); // 获取更多数据用于分析
params.append('format', 'json');
const response = await axios.get(`${CHATLOG_API_BASE}/chatlog?${params}`);
return response.data;
} catch (error) {
console.error('获取聊天数据失败:', error.message);
throw error;
}
}
// 通用AI调用函数
async function callAI(prompt, systemPrompt, retryCount = 0) {
const maxRetries = 3;
const baseDelay = 5000; // 5秒基础延迟
try {
console.log(`🤖 AI调用 (第${retryCount + 1}次尝试)`);
console.log('发送到AI的提示词长度:', prompt.length);
// 不进行数据删减,保持完整性
console.log('📊 提示词长度:', prompt.length, '字符');
// 读取模型设置
const modelConfig = await getModelConfig();
const provider = modelConfig.provider;
const config = modelConfig.config;
let response;
let timeoutDuration = 300000; // 5分钟基础超时
// 根据提示词长度动态调整超时时间
if (prompt.length > 50000) {
timeoutDuration = 600000; // 10分钟
console.log('📏 检测到大数据量,超时时间调整为10分钟');
}
if (provider === 'DeepSeek') {
response = await axios.post('https://api.deepseek.com/v1/chat/completions', {
model: config.model,
messages: [
{
role: 'system',
content: systemPrompt
},
{
role: 'user',
content: prompt
}
],
temperature: 1.0,
max_tokens: 64000,
stream: false
}, {
headers: {
'Authorization': `Bearer ${config.apiKey}`,
'Content-Type': 'application/json'
},
timeout: timeoutDuration,
// 添加连接配置优化
httpAgent: new (require('http').Agent)({
keepAlive: true,
maxSockets: 1,
timeout: timeoutDuration
}),
httpsAgent: new (require('https').Agent)({
keepAlive: true,
maxSockets: 1,
timeout: timeoutDuration
})
});
return response.data.choices[0].message.content;
} else if (provider === 'Gemini') {
// Gemini特殊处理:分段发送大数据
let finalPrompt = `${systemPrompt}\n\n${prompt}`;
// 保持数据完整性,不进行分段处理
console.log('📊 Gemini处理完整数据,长度:', finalPrompt.length, '字符');
response = await axios.post(`https://generativelanguage.googleapis.com/v1beta/models/${config.model}:generateContent?key=${config.apiKey}`, {
contents: [{
parts: [{
text: finalPrompt
}]
}],
generationConfig: {
temperature: 1.0,
maxOutputTokens: 32768
},
safetySettings: [
{
category: "HARM_CATEGORY_HARASSMENT",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_HATE_SPEECH",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
threshold: "BLOCK_NONE"
},
{
category: "HARM_CATEGORY_DANGEROUS_CONTENT",
threshold: "BLOCK_NONE"
}
]
}, {
headers: {
'Content-Type': 'application/json'
},
timeout: timeoutDuration,
// 添加连接配置优化
httpAgent: new (require('http').Agent)({
keepAlive: true,
maxSockets: 1,
timeout: timeoutDuration
}),
httpsAgent: new (require('https').Agent)({
keepAlive: true,
maxSockets: 1,
timeout: timeoutDuration
})
});
return response.data.candidates[0].content.parts[0].text;
}
throw new Error('不支持的AI提供商');
} catch (error) {
console.error(`❌ AI API调用失败 (第${retryCount + 1}次):`, error.message);
// 判断是否需要重试
const shouldRetry = retryCount < maxRetries && (
error.code === 'ECONNABORTED' ||
error.message.includes('socket hang up') ||
error.message.includes('ECONNRESET') ||
error.message.includes('ETIMEDOUT') ||
(error.response?.status >= 500 && error.response?.status < 600) ||
error.response?.status === 429
);
if (shouldRetry) {
const delay = baseDelay * Math.pow(2, retryCount); // 指数退避
console.log(`⏳ ${delay/1000}秒后进行第${retryCount + 2}次重试...`);
await new Promise(resolve => setTimeout(resolve, delay));
return await callAI(prompt, systemPrompt, retryCount + 1);
}
// 记录详细错误信息
if (error.response) {
console.error('API错误响应:', error.response.status, error.response.data);
}
throw error;
}
}
// 数据完整性优先:不进行任何内容删减或采样
// 所有聊天数据将完整保留,确保分析结果的准确性
// 向后兼容的DeepSeek API调用函数
async function callDeepSeekAPI(prompt, systemPrompt) {
return await callAI(prompt, systemPrompt);
}
// AI模型负载检测和推荐
async function checkAIModelHealth() {
const results = {
deepseek: { available: false, responseTime: null, error: null },
gemini: { available: false, responseTime: null, error: null }
};
// 测试DeepSeek
try {
const startTime = Date.now();
await axios.post('https://api.deepseek.com/v1/chat/completions', {
model: 'deepseek-chat',
messages: [{ role: 'user', content: 'test' }],
max_tokens: 1
}, {
headers: {
'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`,
'Content-Type': 'application/json'
},
timeout: 10000
});
results.deepseek.available = true;
results.deepseek.responseTime = Date.now() - startTime;
} catch (error) {
results.deepseek.error = error.message;
}
// 测试Gemini
try {
const startTime = Date.now();
await axios.post(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent?key=${process.env.GEMINI_API_KEY}`, {
contents: [{ parts: [{ text: 'test' }] }],
generationConfig: { maxOutputTokens: 1 }
}, {
headers: { 'Content-Type': 'application/json' },
timeout: 10000
});
results.gemini.available = true;
results.gemini.responseTime = Date.now() - startTime;
} catch (error) {
results.gemini.error = error.message;
}
return results;
}
// AI模型推荐接口
app.get('/api/ai-model-recommendation', async (req, res) => {
try {
const health = await checkAIModelHealth();
let recommendation = {
recommended: 'deepseek', // 默认推荐
reason: '默认推荐',
details: health
};
// 基于响应时间和可用性推荐
if (health.deepseek.available && health.gemini.available) {
if (health.deepseek.responseTime < health.gemini.responseTime) {
recommendation.recommended = 'deepseek';
recommendation.reason = `DeepSeek响应更快 (${health.deepseek.responseTime}ms vs ${health.gemini.responseTime}ms)`;
} else {
recommendation.recommended = 'gemini';
recommendation.reason = `Gemini响应更快 (${health.gemini.responseTime}ms vs ${health.deepseek.responseTime}ms)`;
}
} else if (health.deepseek.available) {
recommendation.recommended = 'deepseek';
recommendation.reason = 'Gemini当前不可用';
} else if (health.gemini.available) {
recommendation.recommended = 'gemini';
recommendation.reason = 'DeepSeek当前不可用';
} else {
recommendation.recommended = null;
recommendation.reason = '所有AI模型当前都不可用';
}
res.json({ success: true, recommendation });
} catch (error) {
console.error('AI模型健康检查失败:', error);
res.json({
success: false,
error: '无法检查AI模型状态',
recommendation: { recommended: 'deepseek', reason: '默认推荐' }
});
}
});
// 获取当前模型配置
async function getModelConfig() {
try {
const fs = require('fs');
const path = require('path');
const modelSettingsPath = path.join(__dirname, 'model-settings.json');
if (fs.existsSync(modelSettingsPath)) {
const settings = JSON.parse(fs.readFileSync(modelSettingsPath, 'utf8'));
const provider = settings.modelProvider;
return {
provider: provider,
config: settings[provider.toLowerCase()]
};
} else {
// 返回默认配置(使用环境变量中的DeepSeek配置)
return {
provider: 'DeepSeek',
config: {
model: 'deepseek-reasoner',
apiKey: DEEPSEEK_API_KEY
}
};
}
} catch (error) {
console.error('读取模型配置失败:', error);
// 返回默认配置
return {
provider: 'DeepSeek',
config: {
model: 'deepseek-reasoner',
apiKey: DEEPSEEK_API_KEY
}
};
}
}
function generatePromptTemplate(analysisType, chatData, customPrompt = '') {
// 不做任何限制,保留完整数据
const validMessages = chatData.filter(msg => msg.content && msg.content.trim().length > 0);
const userStats = {};
// 统计用户发言次数
validMessages.forEach(msg => {
if (msg.senderName) {
userStats[msg.senderName] = (userStats[msg.senderName] || 0) + 1;
}
});
const basicInfo = `
聊天数据概况:
- 群聊名称: ${chatData[0]?.talkerName || '未知群聊'}
- 消息总数: ${chatData.length} (有效文本消息: ${validMessages.length})
- 时间范围: ${chatData[0]?.time} 到 ${chatData[chatData.length-1]?.time}
- 活跃用户数: ${Object.keys(userStats).length}
- 主要发言用户: ${Object.entries(userStats).sort((a,b) => b[1] - a[1]).slice(0, 5).map(([name, count]) => `${name}(${count}条)`).join(', ')}
完整聊天数据:
${validMessages.map(msg => `${msg.time} [${msg.senderName}]: ${msg.content}`).join('\n')}
`;
// 如果有自定义提示词,直接使用
if (customPrompt && customPrompt.trim()) {
return `${basicInfo}
${customPrompt}`;
}
// 如果没有自定义提示词,返回基础信息
return `${basicInfo}
请基于以上聊天数据进行分析。`;
}
// AI分析接口(修改为返回historyId)
app.post('/api/ai-analysis', async (req, res) => {
try {
const { groupName, analysisType, customPrompt, timeRange } = req.body;
console.log('AI分析请求:', { groupName, analysisType, customPrompt, timeRange });
if (!groupName) {
return res.status(400).json({ error: '请指定群聊名称' });
}
// 获取聊天数据
const chatData = await getChatData(groupName, timeRange || '2024-01-01~2025-12-31');
if (!chatData || chatData.length === 0) {
return res.json({
success: false,
error: '未找到聊天数据,请检查时间范围和群聊名称是否正确'
});
}
// 生成提示词
const prompt = generatePromptTemplate(analysisType, chatData, customPrompt);
const systemPrompt = `你是一个专业的数据分析师和前端开发工程师。请根据提供的聊天数据,生成一个完整的、可直接运行的HTML页面。
要求:
1. HTML页面必须完整,包含DOCTYPE、html、head、body等标签
2. CSS样式直接写在<style>标签内
3. JavaScript代码直接写在<script>标签内
4. 使用CDN引入必要的图表库(如Chart.js、D3.js等)
5. 页面要美观、专业、响应式
6. 包含真实的数据分析和可视化
7. 不要使用任何外部文件引用
8. 使用暖色系设计风格
直接返回完整的HTML代码,不要有任何其他说明文字。`;
// 调用AI分析
const analysisResult = await callAI(prompt, systemPrompt);
// 保存到历史记录
const metadata = {
groupName,
analysisType,
timeRange,
messageCount: chatData.length,
timestamp: new Date().toISOString(),
title: `${groupName} - ${getAnalysisTitle(analysisType)}`
};
const historyId = saveAnalysisHistory(metadata, analysisResult);
res.json({
success: true,
historyId: historyId,
title: metadata.title,
metadata: metadata
});
} catch (error) {
console.error('AI分析失败:', error.message);
let errorMessage = 'AI分析失败: ' + error.message;
let suggestions = [];
if (error.code === 'ECONNABORTED') {
errorMessage = '分析超时,数据量过大导致处理时间过长';
suggestions = [
'建议缩小时间范围',
'尝试分批次分析',
'或稍后重试'
];
} else if (error.message.includes('socket hang up')) {
errorMessage = 'AI服务连接中断,通常是由于服务器负载过高';
suggestions = [
'🔄 系统已自动重试3次,建议稍等1-2分钟后再试',
'🔀 建议切换到DeepSeek模型(通常更稳定且支持更大数据量)',
'⏰ 避开高峰时段(如晚上8-10点)进行分析',
'📱 检查网络连接是否稳定',
'🎯 DeepSeek模型对大数据量分析更加稳定可靠'
];
} else if (error.response?.status === 429) {
errorMessage = 'API调用频率过高,请稍后重试';
suggestions = [
'等待1-2分钟后重试',
'避免连续快速请求'
];
} else if (error.response?.status === 413) {
errorMessage = '请求数据过大,超出API限制';
suggestions = [
'减少分析的时间范围',
'选择消息较少的群聊进行测试'
];
}
res.json({
success: false,
error: errorMessage,
suggestions: suggestions,
errorCode: error.code,
httpStatus: error.response?.status
});
}
});
function getAnalysisTitle(analysisType) {
const titles = {
'programming': '编程技术分析',
'science': '科学学习分析',
'reading': '阅读讨论分析',
'custom': '自定义分析'
};
return titles[analysisType] || '聊天数据分析';
}
// 获取分析历史记录接口
app.get('/api/analysis-history', (req, res) => {
try {
const history = getAnalysisHistory();
res.json({ success: true, history });
} catch (error) {
console.error('获取历史记录失败:', error);
res.json({ success: false, error: '获取历史记录失败' });
}
});
// 获取特定分析记录接口
app.get('/api/analysis-history/:id', (req, res) => {
try {
const { id } = req.params;
const filepath = path.join(HISTORY_DIR, `${id}.json`);
if (!fs.existsSync(filepath)) {
return res.status(404).json({ success: false, error: '分析记录不存在' });
}
const content = JSON.parse(fs.readFileSync(filepath, 'utf8'));
res.json({ success: true, data: content });
} catch (error) {
console.error('获取分析记录失败:', error);
res.status(500).json({ success: false, error: '获取分析记录失败' });
}
});
// 删除分析记录接口
app.delete('/api/analysis-history/:id', (req, res) => {
try {
const { id } = req.params;
const filepath = path.join(HISTORY_DIR, `${id}.json`);
if (!fs.existsSync(filepath)) {
return res.status(404).json({ success: false, error: '分析记录不存在' });
}
// 删除文件
fs.unlinkSync(filepath);
console.log(`删除分析记录: ${id}`);
res.json({ success: true, message: '分析记录已删除' });
} catch (error) {
console.error('删除分析记录失败:', error);
res.status(500).json({ success: false, error: '删除分析记录失败' });
}
});
// 获取分析记录的原始聊天数据(用于导出聊天记录)
app.get('/api/analysis-chatlog/:id', async (req, res) => {
try {
const { id } = req.params;
const filepath = path.join(HISTORY_DIR, `${id}.json`);
if (!fs.existsSync(filepath)) {
return res.status(404).json({ success: false, error: '分析记录不存在' });
}
const record = JSON.parse(fs.readFileSync(filepath, 'utf8'));
// 从记录中获取群组名称和时间范围,重新查询聊天数据
const groupName = record.groupName || record.metadata?.groupName;
const timeRange = record.timeRange || record.metadata?.timeRange;
if (!groupName) {
return res.status(400).json({ success: false, error: '分析记录中缺少群组信息' });
}
try {
// 重新获取聊天数据
const chatData = await getChatData(groupName, timeRange);
res.json({ success: true, data: chatData });
} catch (error) {
console.error('获取聊天数据失败:', error);
res.status(500).json({ success: false, error: '获取聊天数据失败: ' + error.message });
}
} catch (error) {
console.error('获取分析聊天记录失败:', error);
res.status(500).json({ success: false, error: '获取分析聊天记录失败' });
}
});
// 获取分析记录的HTML内容(用于导出分析报告)
app.get('/api/analysis-content/:id', (req, res) => {
try {
const { id } = req.params;
const filepath = path.join(HISTORY_DIR, `${id}.json`);
if (!fs.existsSync(filepath)) {
return res.status(404).json({ success: false, error: '分析记录不存在' });
}
const record = JSON.parse(fs.readFileSync(filepath, 'utf8'));
let content = record.content || '';
// 检查内容是否被markdown代码块包装
if (content.trim().startsWith('```html') && content.trim().endsWith('```')) {
// 移除markdown代码块包装
content = content.trim().slice(7, -3).trim();
}
// 如果内容不是完整的HTML页面,需要包装
if (!content.trim().toLowerCase().startsWith('<!doctype html') &&
!content.trim().toLowerCase().startsWith('<html')) {
// 简单的Markdown到HTML转换(复用现有逻辑)
let htmlContent = content
.replace(/\n/g, '<br>')
.replace(/#{6}\s*(.*?)(<br>|$)/g, '<h6>$1</h6>')
.replace(/#{5}\s*(.*?)(<br>|$)/g, '<h5>$1</h5>')
.replace(/#{4}\s*(.*?)(<br>|$)/g, '<h4>$1</h4>')
.replace(/#{3}\s*(.*?)(<br>|$)/g, '<h3>$1</h3>')
.replace(/#{2}\s*(.*?)(<br>|$)/g, '<h2>$1</h2>')
.replace(/#{1}\s*(.*?)(<br>|$)/g, '<h1>$1</h1>')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/`(.*?)`/g, '<code>$1</code>');
// 包装为完整的HTML页面
content = `
<!DOCTYPE html>
<html>
<head>
<title>${record.title || 'AI分析结果'}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
line-height: 1.6;
color: #333;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f8f9fa;
}
.container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }
h2 { color: #34495e; border-bottom: 2px solid #ecf0f1; padding-bottom: 8px; margin-top: 30px; }
h3 { color: #7f8c8d; margin-top: 25px; }
h4, h5, h6 { color: #95a5a6; margin-top: 20px; }
</style>
</head>
<body>
<div class="container">
${htmlContent}
</div>
</body>
</html>
`;
}
res.json({ success: true, content: content });
} catch (error) {
console.error('获取分析内容失败:', error);
res.status(500).json({ success: false, error: '获取分析内容失败' });
}
});
// 新页面展示分析结果
app.get('/analysis/:id', (req, res) => {
try {
const { id } = req.params;
const filepath = path.join(HISTORY_DIR, `${id}.json`);
if (!fs.existsSync(filepath)) {
return res.status(404).send(`
<!DOCTYPE html>
<html>
<head>
<title>分析记录不存在</title>
<meta charset="utf-8">
</head>
<body style="font-family: Arial, sans-serif; text-align: center; padding: 50px;">
<h1>❌ 分析记录不存在</h1>
<p>请检查链接是否正确</p>
<button onclick="window.close()">关闭窗口</button>
</body>
</html>
`);
}
const record = JSON.parse(fs.readFileSync(filepath, 'utf8'));
let content = record.content || '';
// 检查内容是否被markdown代码块包装
if (content.trim().startsWith('```html') && content.trim().endsWith('```')) {
// 移除markdown代码块包装
content = content.trim().slice(7, -3).trim(); // 移除开头的```html和结尾的```
}
// 检查内容是否已经是完整的HTML页面
if (content.trim().toLowerCase().startsWith('<!doctype html') ||
content.trim().toLowerCase().startsWith('<html')) {
// 如果是完整的HTML页面,直接返回
res.setHeader('Content-Type', 'text/html; charset=utf-8');
return res.send(content);
}
// 否则,将Markdown内容转换为HTML并包装在完整的HTML页面中
const markdownContent = content;
// 简单的Markdown到HTML转换
let htmlContent = markdownContent
.replace(/\n/g, '<br>')
.replace(/#{6}\s*(.*?)(<br>|$)/g, '<h6>$1</h6>')
.replace(/#{5}\s*(.*?)(<br>|$)/g, '<h5>$1</h5>')
.replace(/#{4}\s*(.*?)(<br>|$)/g, '<h4>$1</h4>')
.replace(/#{3}\s*(.*?)(<br>|$)/g, '<h3>$1</h3>')
.replace(/#{2}\s*(.*?)(<br>|$)/g, '<h2>$1</h2>')
.replace(/#{1}\s*(.*?)(<br>|$)/g, '<h1>$1</h1>')
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
.replace(/`(.*?)`/g, '<code>$1</code>')
.replace(/>\s*(.*?)(<br>|$)/g, '<blockquote>$1</blockquote>')
.replace(/\|(.+?)\|/g, (match, content) => {
const cells = content.split('|').map(cell => `<td>${cell.trim()}</td>`).join('');
return `<tr>${cells}</tr>`;
});
// 包装表格
htmlContent = htmlContent.replace(/(<tr>.*?<\/tr>)+/g, '<table border="1" style="border-collapse: collapse; width: 100%; margin: 10px 0;">$&</table>');
// 处理列表项
htmlContent = htmlContent.replace(/^-\s+(.*?)(<br>|$)/gm, '<li>$1</li>');
htmlContent = htmlContent.replace(/(<li>.*?<\/li>)+/g, '<ul>$&</ul>');
// 处理数字列表
htmlContent = htmlContent.replace(/^\d+\.\s+(.*?)(<br>|$)/gm, '<li>$1</li>');
htmlContent = htmlContent.replace(/(<li>.*?<\/li>)+/g, '<ol>$&</ol>');
const fullHtml = `
<!DOCTYPE html>
<html>
<head>
<title>${record.title || 'AI分析结果'}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
line-height: 1.6;
color: #333;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f8f9fa;
}
.container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }
h2 { color: #34495e; border-bottom: 2px solid #ecf0f1; padding-bottom: 8px; margin-top: 30px; }
h3 { color: #7f8c8d; margin-top: 25px; }
h4, h5, h6 { color: #95a5a6; margin-top: 20px; }
table {
border-collapse: collapse;
width: 100%;
margin: 15px 0;
background: white;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #f8f9fa;
font-weight: bold;
color: #2c3e50;
}
blockquote {
border-left: 4px solid #3498db;