Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
203 lines (167 loc) · 5.05 KB
/
Copy pathserver.js
File metadata and controls
203 lines (167 loc) · 5.05 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
const express = require('express');
const { v4: uuidv4 } = require('uuid');
const path = require('path');
const fs = require('fs').promises;
const app = express();
const PORT = process.env.PORT || 8080;
const NOTES_DIR = path.join(__dirname, 'notes');
const EXPIRY_DAYS = 7;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// API 路由应该在静态文件中间件之前定义
app.get('/api/notes/:id', async (req, res) => {
try {
const noteId = req.params.id;
const notePath = path.join(NOTES_DIR, `${noteId}.json`);
try {
const data = await fs.readFile(notePath, 'utf-8');
const note = JSON.parse(data);
const now = Date.now();
const expiryDate = new Date(note.expiresAt).getTime();
if (now > expiryDate) {
await fs.unlink(notePath);
return res.status(404).json({ error: 'Note has expired' });
}
res.json(note);
} catch (error) {
if (error.code === 'ENOENT') {
return res.status(404).json({ error: 'Note not found' });
}
throw error;
}
} catch (error) {
console.error('Error retrieving note data:', error);
res.status(500).json({ error: 'Failed to retrieve note' });
}
});
// 静态文件中间件
app.use(express.static('public'));
const forbiddenWords = [
'暴力',
'色情',
'赌博',
'毒品',
'诈骗',
'黑客',
'攻击',
'炸弹',
'恐怖',
'极端',
'邪教',
'分裂',
'颠覆',
'反动',
'违禁',
'非法',
'犯罪',
'洗钱',
'走私'
];
function checkForbiddenWords(content) {
const foundWords = [];
for (const word of forbiddenWords) {
if (content.includes(word)) {
foundWords.push(word);
}
}
return foundWords;
}
async function ensureNotesDir() {
try {
await fs.mkdir(NOTES_DIR, { recursive: true });
} catch (error) {
console.error('Error creating notes directory:', error);
}
}
async function cleanExpiredNotes() {
try {
const files = await fs.readdir(NOTES_DIR);
const now = Date.now();
for (const file of files) {
const filePath = path.join(NOTES_DIR, file);
const stats = await fs.stat(filePath);
const age = now - stats.mtimeMs;
const maxAge = EXPIRY_DAYS * 24 * 60 * 60 * 1000;
if (age > maxAge) {
await fs.unlink(filePath);
console.log(`Deleted expired note: ${file}`);
}
}
} catch (error) {
console.error('Error cleaning expired notes:', error);
}
}
setInterval(cleanExpiredNotes, 60 * 60 * 1000);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.post('/api/notes', async (req, res) => {
try {
const { content } = req.body;
if (!content || content.trim() === '') {
return res.status(400).json({ error: 'Content cannot be empty' });
}
const foundWords = checkForbiddenWords(content);
if (foundWords.length > 0) {
return res.status(400).json({
error: `内容包含违禁词:${foundWords.join('、')}`,
forbiddenWords: foundWords
});
}
const noteId = uuidv4();
const notePath = path.join(NOTES_DIR, `${noteId}.json`);
const noteData = {
id: noteId,
content: content,
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + EXPIRY_DAYS * 24 * 60 * 60 * 1000).toISOString()
};
await fs.writeFile(notePath, JSON.stringify(noteData, null, 2));
res.json({
id: noteId,
url: `/note/${noteId}`,
expiresAt: noteData.expiresAt
});
} catch (error) {
console.error('Error creating note:', error);
res.status(500).json({ error: 'Failed to create note' });
}
});
app.get('/note/:id', async (req, res) => {
try {
const noteId = req.params.id;
// 验证 noteId 是否为有效的 UUID 格式
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
if (!uuidRegex.test(noteId)) {
return res.status(404).sendFile(path.join(__dirname, 'public', 'notfound.html'));
}
const notePath = path.join(NOTES_DIR, `${noteId}.json`);
try {
const data = await fs.readFile(notePath, 'utf-8');
const note = JSON.parse(data);
const now = Date.now();
const expiryDate = new Date(note.expiresAt).getTime();
if (now > expiryDate) {
await fs.unlink(notePath);
return res.status(404).sendFile(path.join(__dirname, 'public', 'expired.html'));
}
res.sendFile(path.join(__dirname, 'public', 'note.html'));
} catch (error) {
if (error.code === 'ENOENT') {
return res.status(404).sendFile(path.join(__dirname, 'public', 'notfound.html'));
}
throw error;
}
} catch (error) {
console.error('Error retrieving note:', error);
res.status(500).json({ error: 'Failed to retrieve note' });
}
});
async function startServer() {
await ensureNotesDir();
await cleanExpiredNotes();
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
}
startServer();