-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
738 lines (600 loc) · 20.3 KB
/
server.js
File metadata and controls
738 lines (600 loc) · 20.3 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
const express = require('express');
const fs = require('fs');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
// 数据目录
const DATA_DIR = path.join(__dirname, 'data');
const KNOWLEDGE_DIR = path.join(DATA_DIR, 'knowledge');
const KNOWLEDGE_IMAGES_DIR = path.join(KNOWLEDGE_DIR, 'images');
// 确保数据目录存在
if (!fs.existsSync(DATA_DIR)) {
fs.mkdirSync(DATA_DIR);
}
// 确保知识库目录存在
if (!fs.existsSync(KNOWLEDGE_DIR)) {
fs.mkdirSync(KNOWLEDGE_DIR);
}
// 确保知识库图片目录存在
if (!fs.existsSync(KNOWLEDGE_IMAGES_DIR)) {
fs.mkdirSync(KNOWLEDGE_IMAGES_DIR);
}
// 中间件
app.use(express.json());
app.use(express.static('public'));
// 读取JSON文件的辅助函数
function readJSON(filename) {
const filepath = path.join(DATA_DIR, filename);
if (fs.existsSync(filepath)) {
return JSON.parse(fs.readFileSync(filepath, 'utf-8'));
}
return null;
}
// 写入JSON文件的辅助函数
function writeJSON(filename, data) {
const filepath = path.join(DATA_DIR, filename);
fs.writeFileSync(filepath, JSON.stringify(data, null, 2), 'utf-8');
}
// 验证键名是否安全(防止原型污染)
function isSafeKey(key) {
return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
}
// API路由 - 家庭成员
app.get('/api/members', (req, res) => {
const members = readJSON('members.json') || [];
res.json(members);
});
app.post('/api/members', (req, res) => {
const members = readJSON('members.json') || [];
const newMember = {
id: Date.now().toString(),
...req.body,
createdAt: new Date().toISOString()
};
members.push(newMember);
writeJSON('members.json', members);
res.json(newMember);
});
app.put('/api/members/:id', (req, res) => {
const members = readJSON('members.json') || [];
const index = members.findIndex(m => m.id === req.params.id);
if (index !== -1) {
members[index] = { ...members[index], ...req.body };
writeJSON('members.json', members);
res.json(members[index]);
} else {
res.status(404).json({ error: '成员不存在' });
}
});
app.delete('/api/members/:id', (req, res) => {
let members = readJSON('members.json') || [];
members = members.filter(m => m.id !== req.params.id);
writeJSON('members.json', members);
res.json({ success: true });
});
// API路由 - 家庭成员属性定义
app.get('/api/attribute-definitions', (req, res) => {
const definitions = readJSON('attribute-definitions.json') || [];
res.json(definitions);
});
app.post('/api/attribute-definitions', (req, res) => {
const definitions = readJSON('attribute-definitions.json') || [];
const newDef = {
id: Date.now().toString(),
...req.body,
createdAt: new Date().toISOString()
};
definitions.push(newDef);
writeJSON('attribute-definitions.json', definitions);
res.json(newDef);
});
app.delete('/api/attribute-definitions/:id', (req, res) => {
let definitions = readJSON('attribute-definitions.json') || [];
definitions = definitions.filter(d => d.id !== req.params.id);
writeJSON('attribute-definitions.json', definitions);
res.json({ success: true });
});
// API路由 - 成员属性值
app.get('/api/member-attributes', (req, res) => {
const attributes = readJSON('member-attributes.json') || {};
res.json(attributes);
});
app.put('/api/member-attributes/:memberId/:attrId', (req, res) => {
const memberId = req.params.memberId;
const attrId = req.params.attrId;
// 验证键名安全性
if (!isSafeKey(memberId) || !isSafeKey(attrId)) {
return res.status(400).json({ error: '无效的参数' });
}
const attributes = readJSON('member-attributes.json') || {};
if (!attributes[memberId]) {
attributes[memberId] = {};
}
attributes[memberId][attrId] = req.body.value;
writeJSON('member-attributes.json', attributes);
res.json({ success: true });
});
// API路由 - 待做任务
app.get('/api/todos', (req, res) => {
const todos = readJSON('todos.json') || [];
res.json(todos);
});
app.post('/api/todos', (req, res) => {
const todos = readJSON('todos.json') || [];
const deadlineDays = req.body.deadlineDays || 1;
const deadline = new Date();
deadline.setDate(deadline.getDate() + deadlineDays);
const newTodo = {
id: Date.now().toString(),
...req.body,
deadline: deadline.toISOString(),
addedAt: new Date().toISOString()
};
todos.push(newTodo);
writeJSON('todos.json', todos);
res.json(newTodo);
});
app.put('/api/todos/:id', (req, res) => {
const todos = readJSON('todos.json') || [];
const index = todos.findIndex(t => t.id === req.params.id);
if (index !== -1) {
todos[index] = { ...todos[index], ...req.body };
writeJSON('todos.json', todos);
res.json(todos[index]);
} else {
res.status(404).json({ error: '任务不存在' });
}
});
app.delete('/api/todos/:id', (req, res) => {
let todos = readJSON('todos.json') || [];
todos = todos.filter(t => t.id !== req.params.id);
writeJSON('todos.json', todos);
res.json({ success: true });
});
// API路由 - 周期任务
app.get('/api/periodic-tasks', (req, res) => {
const tasks = readJSON('periodic-tasks.json') || [];
res.json(tasks);
});
app.post('/api/periodic-tasks', (req, res) => {
const tasks = readJSON('periodic-tasks.json') || [];
const newTask = {
id: Date.now().toString(),
...req.body,
deadlineDays: req.body.deadlineDays || 1,
createdAt: new Date().toISOString(),
generatedCount: 0
};
tasks.push(newTask);
writeJSON('periodic-tasks.json', tasks);
res.json(newTask);
});
app.put('/api/periodic-tasks/:id', (req, res) => {
const tasks = readJSON('periodic-tasks.json') || [];
const index = tasks.findIndex(t => t.id === req.params.id);
if (index !== -1) {
tasks[index] = { ...tasks[index], ...req.body };
writeJSON('periodic-tasks.json', tasks);
res.json(tasks[index]);
} else {
res.status(404).json({ error: '周期任务不存在' });
}
});
app.delete('/api/periodic-tasks/:id', (req, res) => {
let tasks = readJSON('periodic-tasks.json') || [];
tasks = tasks.filter(t => t.id !== req.params.id);
writeJSON('periodic-tasks.json', tasks);
res.json({ success: true });
});
// 周期任务生成待做任务的功能
app.post('/api/periodic-tasks/:id/generate', (req, res) => {
const tasks = readJSON('periodic-tasks.json') || [];
const todos = readJSON('todos.json') || [];
const task = tasks.find(t => t.id === req.params.id);
if (!task) {
return res.status(404).json({ error: '周期任务不存在' });
}
if (task.maxGenerations && task.generatedCount >= task.maxGenerations) {
return res.status(400).json({ error: '已达到最大生成次数' });
}
const deadlineDays = task.deadlineDays || 1;
const deadline = new Date();
deadline.setDate(deadline.getDate() + deadlineDays);
const newTodo = {
id: Date.now().toString(),
content: task.content,
addedBy: task.addedBy || '系统',
executor: task.executor || '',
status: '待处理',
addedAt: new Date().toISOString(),
deadline: deadline.toISOString(),
fromPeriodicTask: task.id
};
todos.push(newTodo);
task.generatedCount = (task.generatedCount || 0) + 1;
writeJSON('todos.json', todos);
writeJSON('periodic-tasks.json', tasks);
res.json({ todo: newTodo, task });
});
// ========== 知识库 API ==========
// 扫描知识库目录结构
function scanKnowledgeBase() {
const categories = [];
if (!fs.existsSync(KNOWLEDGE_DIR)) {
return categories;
}
const rootItems = fs.readdirSync(KNOWLEDGE_DIR, { withFileTypes: true });
for (const item of rootItems) {
if (item.isDirectory() && item.name !== 'images') {
const categoryPath = path.join(KNOWLEDGE_DIR, item.name);
const category = {
name: item.name,
path: item.name,
children: scanCategory(categoryPath, item.name)
};
categories.push(category);
}
}
return categories;
}
// 递归扫描分类目录
function scanCategory(dirPath, relativePath) {
const items = [];
if (!fs.existsSync(dirPath)) {
return items;
}
const dirItems = fs.readdirSync(dirPath, { withFileTypes: true });
for (const item of dirItems) {
if (item.isDirectory()) {
// 子目录
const itemPath = path.join(dirPath, item.name);
const itemRelativePath = `${relativePath}/${item.name}`;
items.push({
type: 'category',
name: item.name,
path: itemRelativePath,
children: scanCategory(itemPath, itemRelativePath)
});
} else if (item.isFile() && item.name.endsWith('.json')) {
// JSON文件作为二级分类
const itemPath = path.join(dirPath, item.name);
const itemRelativePath = `${relativePath}/${item.name}`;
const categoryName = item.name.replace('.json', '');
try {
const data = JSON.parse(fs.readFileSync(itemPath, 'utf-8'));
items.push({
type: 'file',
name: categoryName,
path: itemRelativePath,
knowledgeItems: data.items || []
});
} catch (error) {
console.error(`读取知识库文件失败: ${itemPath}`, error);
}
}
}
return items;
}
// 获取知识库结构
app.get('/api/knowledge/structure', (req, res) => {
try {
const structure = scanKnowledgeBase();
res.json(structure);
} catch (error) {
console.error('获取知识库结构失败:', error);
res.status(500).json({ error: '获取知识库结构失败' });
}
});
// 获取知识库配置(当前学习人、目标属性)
app.get('/api/knowledge/config', (req, res) => {
const config = readJSON('knowledge-config.json') || {
currentLearners: [],
targetAttributes: {}
};
res.json(config);
});
// 保存知识库配置
app.put('/api/knowledge/config', (req, res) => {
writeJSON('knowledge-config.json', req.body);
res.json({ success: true });
});
// 创建根分类(大分类)
app.post('/api/knowledge/category', (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: '分类名称不能为空' });
}
const categoryPath = path.join(KNOWLEDGE_DIR, name);
if (fs.existsSync(categoryPath)) {
return res.status(400).json({ error: '分类已存在' });
}
fs.mkdirSync(categoryPath, { recursive: true });
res.json({ success: true });
});
// 删除分类
app.delete('/api/knowledge/category', (req, res) => {
const { categoryPath } = req.body;
if (!categoryPath) {
return res.status(400).json({ error: '分类路径不能为空' });
}
const fullPath = path.join(KNOWLEDGE_DIR, categoryPath);
if (!fs.existsSync(fullPath)) {
return res.status(404).json({ error: '分类不存在' });
}
// 递归删除目录
fs.rmSync(fullPath, { recursive: true, force: true });
res.json({ success: true });
});
// 创建子分类或知识项文件
app.post('/api/knowledge/subcategory', (req, res) => {
const { parentPath, name, isFile } = req.body;
if (!parentPath || !name) {
return res.status(400).json({ error: '参数不完整' });
}
const parentFullPath = path.join(KNOWLEDGE_DIR, parentPath);
if (!fs.existsSync(parentFullPath)) {
return res.status(404).json({ error: '父分类不存在' });
}
if (isFile) {
// 创建知识项JSON文件
const filePath = path.join(parentFullPath, `${name}.json`);
if (fs.existsSync(filePath)) {
return res.status(400).json({ error: '文件已存在' });
}
writeJSON(`knowledge/${parentPath}/${name}.json`, { items: [] });
} else {
// 创建子目录
const dirPath = path.join(parentFullPath, name);
if (fs.existsSync(dirPath)) {
return res.status(400).json({ error: '目录已存在' });
}
fs.mkdirSync(dirPath, { recursive: true });
}
res.json({ success: true });
});
// 获取知识项列表
app.get('/api/knowledge/items', (req, res) => {
const { filePath } = req.query;
if (!filePath) {
return res.status(400).json({ error: '文件路径不能为空' });
}
const data = readJSON(`knowledge/${filePath}`) || { items: [] };
res.json(data.items || []);
});
// 添加或更新知识项
app.post('/api/knowledge/item', (req, res) => {
const { filePath, item } = req.body;
if (!filePath || !item) {
return res.status(400).json({ error: '参数不完整' });
}
const data = readJSON(`knowledge/${filePath}`) || { items: [] };
if (item.id) {
// 更新现有项
const index = data.items.findIndex(i => i.id === item.id);
if (index !== -1) {
data.items[index] = item;
}
} else {
// 添加新项
item.id = Date.now().toString();
item.createdAt = new Date().toISOString();
data.items.push(item);
}
writeJSON(`knowledge/${filePath}`, data);
res.json(item);
});
// 删除知识项
app.delete('/api/knowledge/item', (req, res) => {
const { filePath, itemId } = req.body;
if (!filePath || !itemId) {
return res.status(400).json({ error: '参数不完整' });
}
const data = readJSON(`knowledge/${filePath}`) || { items: [] };
data.items = data.items.filter(i => i.id !== itemId);
writeJSON(`knowledge/${filePath}`, data);
res.json({ success: true });
});
// 增加学习次数
app.post('/api/knowledge/item/learn', (req, res) => {
const { filePath, itemId, learners, targetAttributes } = req.body;
if (!filePath || !itemId) {
return res.status(400).json({ error: '参数不完整' });
}
const data = readJSON(`knowledge/${filePath}`) || { items: [] };
const item = data.items.find(i => i.id === itemId);
if (!item) {
return res.status(404).json({ error: '知识项不存在' });
}
// 更新知识项
item.learnCount = (item.learnCount || 0) + 1;
item.lastLearnTime = new Date().toISOString();
writeJSON(`knowledge/${filePath}`, data);
// 更新学习人属性
if (learners && learners.length > 0 && targetAttributes) {
const memberAttributes = readJSON('member-attributes.json') || {};
for (const learnerId of learners) {
if (!memberAttributes[learnerId]) {
memberAttributes[learnerId] = {};
}
for (const attrId of Object.keys(targetAttributes)) {
const currentValue = memberAttributes[learnerId][attrId] || 0;
memberAttributes[learnerId][attrId] = parseInt(currentValue) + 1;
}
}
writeJSON('member-attributes.json', memberAttributes);
}
res.json(item);
});
// 增加忘记次数
app.post('/api/knowledge/item/forget', (req, res) => {
const { filePath, itemId } = req.body;
if (!filePath || !itemId) {
return res.status(400).json({ error: '参数不完整' });
}
const data = readJSON(`knowledge/${filePath}`) || { items: [] };
const item = data.items.find(i => i.id === itemId);
if (!item) {
return res.status(404).json({ error: '知识项不存在' });
}
item.forgetCount = (item.forgetCount || 0) + 1;
writeJSON(`knowledge/${filePath}`, data);
res.json(item);
});
// 导入知识数据
app.post('/api/knowledge/import', (req, res) => {
const { data } = req.body;
if (!Array.isArray(data)) {
return res.status(400).json({ error: '数据格式错误' });
}
let imported = 0;
for (const item of data) {
const { levelRootName, level1Name, level2Name, level3Name, ...knowledgeItem } = item;
if (!levelRootName || !level1Name) {
continue;
}
// 构建路径
let filePath = `${levelRootName}/${level1Name}`;
// 确保目录存在
const rootPath = path.join(KNOWLEDGE_DIR, levelRootName);
if (!fs.existsSync(rootPath)) {
fs.mkdirSync(rootPath, { recursive: true });
}
const level1Path = path.join(rootPath, level1Name);
if (!fs.existsSync(level1Path)) {
fs.mkdirSync(level1Path, { recursive: true });
}
// 如果有level2Name,添加到路径
if (level2Name) {
const level2Path = path.join(level1Path, level2Name);
if (!fs.existsSync(level2Path)) {
fs.mkdirSync(level2Path, { recursive: true });
}
filePath = `${levelRootName}/${level1Name}/${level2Name}`;
// 如果有level3Name,这是文件名
if (level3Name) {
filePath = `${filePath}/${level3Name}.json`;
} else {
// level2Name是文件名
filePath = `${levelRootName}/${level1Name}/${level2Name}.json`;
}
} else {
// level1Name是文件名
filePath = `${levelRootName}/${level1Name}.json`;
}
// 读取现有数据
const fileData = readJSON(`knowledge/${filePath}`) || { items: [] };
// 添加知识项
knowledgeItem.id = Date.now().toString() + Math.random().toString(36).substr(2, 9);
knowledgeItem.createdAt = new Date().toISOString();
knowledgeItem.learnCount = knowledgeItem.learnCount || 0;
knowledgeItem.forgetCount = knowledgeItem.forgetCount || 0;
fileData.items.push(knowledgeItem);
writeJSON(`knowledge/${filePath}`, fileData);
imported++;
}
res.json({ success: true, imported });
});
// ========== 游戏分数 API ==========
// 获取本周一的日期字符串
function getWeekStart(date) {
const dayOfWeek = date.getDay();
const mondayOffset = dayOfWeek === 0 ? 6 : dayOfWeek - 1;
const monday = new Date(date);
monday.setDate(date.getDate() - mondayOffset);
return monday.toISOString().split('T')[0];
}
// 获取游戏分数
app.get('/api/game-scores/:gameId', (req, res) => {
const gameId = req.params.gameId;
// 验证键名安全性
if (!isSafeKey(gameId)) {
return res.status(400).json({ error: '无效的游戏ID' });
}
const scores = readJSON('game-scores.json') || {};
const gameScores = scores[gameId] || {
dailyBest: { score: 0, date: null },
weeklyBest: { score: 0, weekStart: null },
allTimeBest: { score: 0, date: null },
history: []
};
// 检查是否需要重置每日/每周最高分
const now = new Date();
const today = now.toISOString().split('T')[0];
const weekStart = getWeekStart(now);
// 重置每日最高分(如果是新的一天)
if (gameScores.dailyBest.date !== today) {
gameScores.dailyBest = { score: 0, date: today };
}
// 重置每周最高分(如果是新的一周)
if (gameScores.weeklyBest.weekStart !== weekStart) {
gameScores.weeklyBest = { score: 0, weekStart: weekStart };
}
res.json(gameScores);
});
// 提交游戏分数
app.post('/api/game-scores/:gameId', (req, res) => {
const gameId = req.params.gameId;
const { score } = req.body;
// 验证键名安全性
if (!isSafeKey(gameId)) {
return res.status(400).json({ error: '无效的游戏ID' });
}
if (typeof score !== 'number' || score < 0) {
return res.status(400).json({ error: '无效的分数' });
}
const scores = readJSON('game-scores.json') || {};
const now = new Date();
const today = now.toISOString().split('T')[0];
const weekStart = getWeekStart(now);
if (!scores[gameId]) {
scores[gameId] = {
dailyBest: { score: 0, date: today },
weeklyBest: { score: 0, weekStart: weekStart },
allTimeBest: { score: 0, date: null },
history: []
};
}
const gameScores = scores[gameId];
// 重置每日最高分(如果是新的一天)
if (gameScores.dailyBest.date !== today) {
gameScores.dailyBest = { score: 0, date: today };
}
// 重置每周最高分(如果是新的一周)
if (gameScores.weeklyBest.weekStart !== weekStart) {
gameScores.weeklyBest = { score: 0, weekStart: weekStart };
}
// 更新分数
let isNewRecord = false;
if (score > gameScores.dailyBest.score) {
gameScores.dailyBest.score = score;
isNewRecord = true;
}
if (score > gameScores.weeklyBest.score) {
gameScores.weeklyBest.score = score;
isNewRecord = true;
}
if (score > gameScores.allTimeBest.score) {
gameScores.allTimeBest.score = score;
gameScores.allTimeBest.date = now.toISOString();
isNewRecord = true;
}
// 添加到历史记录(保留最近50条)
gameScores.history.unshift({
score,
date: now.toISOString()
});
if (gameScores.history.length > 50) {
gameScores.history = gameScores.history.slice(0, 50);
}
writeJSON('game-scores.json', scores);
res.json({
success: true,
isNewRecord,
dailyBest: gameScores.dailyBest.score,
weeklyBest: gameScores.weeklyBest.score,
allTimeBest: gameScores.allTimeBest.score
});
});
app.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});