-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
222 lines (199 loc) · 6.72 KB
/
Copy pathserver.js
File metadata and controls
222 lines (199 loc) · 6.72 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
'use strict';
const express = require('express');
const fs = require('fs');
const path = require('path');
const os = require('os');
const crypto = require('crypto');
const { grade, validateExercise } = require('./lib/grader');
const LAN_MODE = process.argv.includes('--lan') || process.env.LAN === '1';
const PORT = Number(process.env.PORT) || 3000;
const HOST = LAN_MODE ? '0.0.0.0' : '127.0.0.1';
const DATA_DIR = path.join(__dirname, 'data');
const INDEX_FILE = path.join(DATA_DIR, 'index.json');
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || '';
fs.mkdirSync(DATA_DIR, { recursive: true });
// ---------- 存储 ----------
function readIndex() {
try {
return JSON.parse(fs.readFileSync(INDEX_FILE, 'utf8'));
} catch {
return [];
}
}
function writeIndex(list) {
fs.writeFileSync(INDEX_FILE, JSON.stringify(list, null, 2));
}
function exercisePath(id) {
return path.join(DATA_DIR, `exercise-${id}.json`);
}
function readExercise(id) {
if (!/^[a-f0-9]{12}$/.test(id)) return null;
try {
return JSON.parse(fs.readFileSync(exercisePath(id), 'utf8'));
} catch {
return null;
}
}
function seedSample() {
if (readIndex().length > 0) return;
const samplePath = path.join(__dirname, 'samples', 'sentence_analysis_template.json');
try {
const data = JSON.parse(fs.readFileSync(samplePath, 'utf8'));
saveExercise('示例练习:Wikipedia Rabbit Hole', data);
console.log('已导入示例练习');
} catch (e) {
console.warn('示例练习导入失败:', e.message);
}
}
function saveExercise(title, data) {
const id = crypto.randomBytes(6).toString('hex');
const exercise = {
id,
title: title || `练习 ${new Date().toLocaleString('zh-CN')}`,
createdAt: new Date().toISOString(),
sentences: data.sentences.map((s, i) => ({
sentence_id: s.sentence_id != null ? s.sentence_id : i + 1,
text: s.text,
components: s.components,
})),
};
fs.writeFileSync(exercisePath(id), JSON.stringify(exercise, null, 2));
const index = readIndex();
index.unshift({
id,
title: exercise.title,
createdAt: exercise.createdAt,
sentenceCount: exercise.sentences.length,
});
writeIndex(index);
return exercise;
}
// ---------- 应用 ----------
const app = express();
app.use(express.json({ limit: '5mb' }));
app.use(express.static(path.join(__dirname, 'public')));
function requireAdmin(req, res, next) {
if (!ADMIN_PASSWORD) return next();
if (req.get('x-admin-password') === ADMIN_PASSWORD) return next();
res.status(401).json({ error: '管理员口令错误(请求头 x-admin-password)' });
}
// 练习列表
app.get('/api/exercises', (req, res) => {
res.json({ exercises: readIndex(), adminProtected: Boolean(ADMIN_PASSWORD) });
});
// 练习内容 —— 只返回原文,正确答案保留在后台
app.get('/api/exercises/:id', (req, res) => {
const ex = readExercise(req.params.id);
if (!ex) return res.status(404).json({ error: '练习不存在' });
res.json({
id: ex.id,
title: ex.title,
sentences: ex.sentences.map((s) => ({ sentence_id: s.sentence_id, text: s.text })),
});
});
// 提交标注,后台批改
app.post('/api/exercises/:id/submit', (req, res) => {
const ex = readExercise(req.params.id);
if (!ex) return res.status(404).json({ error: '练习不存在' });
const annotations = req.body && req.body.annotations;
if (!Array.isArray(annotations)) {
return res.status(400).json({ error: '请求体需要 annotations 数组' });
}
res.json(grade(ex, annotations));
});
// 管理员:上传 JSON 生成练习
app.post('/api/admin/exercises', requireAdmin, (req, res) => {
const { title, data } = req.body || {};
const check = validateExercise(data);
if (!check.ok) {
return res.status(400).json({ error: 'JSON 格式有误', details: check.errors });
}
const ex = saveExercise(title, data);
res.json({
id: ex.id,
title: ex.title,
sentenceCount: ex.sentences.length,
warnings: check.warnings,
});
});
// 管理员:读取完整练习(含答案),用于编辑
app.get('/api/admin/exercises/:id', requireAdmin, (req, res) => {
const ex = readExercise(req.params.id);
if (!ex) return res.status(404).json({ error: '练习不存在' });
res.json({
id: ex.id,
title: ex.title,
createdAt: ex.createdAt,
updatedAt: ex.updatedAt || null,
data: { sentences: ex.sentences },
});
});
// 管理员:修改练习(标题和/或答案 JSON),整体校验后覆盖保存
app.put('/api/admin/exercises/:id', requireAdmin, (req, res) => {
const ex = readExercise(req.params.id);
if (!ex) return res.status(404).json({ error: '练习不存在' });
const { title, data } = req.body || {};
const check = validateExercise(data);
if (!check.ok) {
return res.status(400).json({ error: 'JSON 格式有误', details: check.errors });
}
const updated = {
id: ex.id,
title: (title && String(title).trim()) || ex.title,
createdAt: ex.createdAt,
updatedAt: new Date().toISOString(),
sentences: data.sentences.map((s, i) => ({
sentence_id: s.sentence_id != null ? s.sentence_id : i + 1,
text: s.text,
components: s.components,
})),
};
fs.writeFileSync(exercisePath(ex.id), JSON.stringify(updated, null, 2));
const index = readIndex();
const entry = index.find((e) => e.id === ex.id);
if (entry) {
entry.title = updated.title;
entry.sentenceCount = updated.sentences.length;
entry.updatedAt = updated.updatedAt;
writeIndex(index);
}
res.json({
id: updated.id,
title: updated.title,
sentenceCount: updated.sentences.length,
warnings: check.warnings,
});
});
// 管理员:删除练习
app.delete('/api/admin/exercises/:id', requireAdmin, (req, res) => {
const id = req.params.id;
const index = readIndex();
const next = index.filter((e) => e.id !== id);
if (next.length === index.length) return res.status(404).json({ error: '练习不存在' });
writeIndex(next);
try {
fs.unlinkSync(exercisePath(id));
} catch {}
res.json({ ok: true });
});
seedSample();
app.listen(PORT, HOST, () => {
console.log('');
console.log(' 英语语法结构标注练习');
console.log(' ------------------------------------');
console.log(` 本机访问: http://localhost:${PORT}`);
if (LAN_MODE) {
const nets = os.networkInterfaces();
for (const name of Object.keys(nets)) {
for (const net of nets[name] || []) {
if (net.family === 'IPv4' && !net.internal) {
console.log(` 局域网访问: http://${net.address}:${PORT} (${name})`);
}
}
}
console.log(' 已开启局域网模式,同一网络下的手机 / 平板 / 电脑均可访问');
} else {
console.log(' 提示: 使用 npm run lan 可开启局域网多终端访问');
}
console.log('');
});