-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
381 lines (310 loc) · 11.3 KB
/
index.js
File metadata and controls
381 lines (310 loc) · 11.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
const express = require('express')
const path = require('path')
const morgan = require('morgan')
const cors = require('cors')
const db = require("./src/config/db")
const Task = require('./src/app/task')
const User = require('./src/app/user')
const Note = require('./src/app/note')
const nodeMail = require('./mailer.js');
const ical = require('node-ical');
const moment = require('moment');
const { JSDOM } = require('jsdom');
const { URL } = require('url');
const jwt = require('jsonwebtoken');
const app = express()
const port = 8080
// const web = "http://localhost:3000/"
const SECRET_KEY = 'your-secret-key';
const web = "https://todo-reactjs-flax.vercel.app/"
app.use(express.static(path.join(__dirname,"src/public")))
app.use(morgan('combined'))
app.use(express.urlencoded({
extended :true
}))
app.use(express.json())
app.use(cors([{
origin: ["http://localhost:3000", "https://todo-reactjs-flax.vercel.app"]
}
]))
db.connect()
app.get('/', async (req, res) => {
res.send('NODEJS')
})
//-----------------------------------------------Task
app.get('/api/tasks', async (req, res) => {
try {
const user_id = req.query.user_id;
const taskDocuments = await Task.find({ user_id: user_id })
res.json(taskDocuments)
} catch (error){
res.status(500).json({error})
}
})
app.get('/api/eventlist', async (req, res) => {
try {
const user_id = req.query.user_id;
const user = await User.findOne({ _id: user_id });
const url = user.canvasUrl;
const data = await fetch(url);
const textData = await data.text();
const events = ical.parseICS(textData);
const eventList = [];
const now = moment();
for (const key in events) {
if (events.hasOwnProperty(key)) {
const event = events[key];
if (event.type === 'VEVENT') {
const endDate = moment(event.end);
if (endDate.isBefore(now)) {
continue;
}
const ddlTimeStr = endDate.format('YYYY-MM-DD HH:mm');
let ddlTime = new Date(ddlTimeStr);
// ddlTime = ddlTime.getTime() + ddlTime.getTimezoneOffset() * 60 * 1000 + 8 * 60 * 60 * 1000;
ddlTime = ddlTime.getTime();
let newEvent = {
name: event.summary,
description: event.description || '',
isComplete: false,
isImportant: false,
deadLine: new Date(ddlTime),
};
eventList.push(newEvent);
}
}
}
user.lastUpdated = new Date();
await user.save();
res.json(eventList);
} catch (error) {
res.status(500).json({error});
}
});
app.post('/insert-task', async (req, res) => {
const task = new Task(req.body)
const savedTask = await task.save()
res.json({ id: savedTask._id })
})
app.post('/update-task', async (req, res) => {
const task = new Task(req.body)
if (task.deadLine === "1970-01-01T00:00:00.000Z") {
delete task.deadLine;
}
Task.updateOne({_id : task._id}, task)
.then(() => res.redirect(web + "task"))
.catch(error => res.status(500).json({error}))
})
app.post('/update-complete', async (req, res) => {
Task.updateOne({_id : req.body._id}, { $set: { isComplete: req.body.isComplete } })
.then(() => res.json({msg: "success"}))
.catch(error => res.status(500).json({error}))
})
app.post('/update-important', async (req, res) => {
Task.updateOne({_id : req.body._id}, { $set: { isImportant: req.body.isImportant } })
.then(() => res.json({msg: "success"}))
.catch(error => res.status(500).json({error}))
})
app.post('/delete-task', async (req, res) => {
const id = req.body._id
await Task.deleteOne({_id : id})
.then(() => res.redirect(web + "task"))
.catch(error => res.status(500).json({error}))
})
app.get('/taskLastUpdated', async (req, res) => {
try {
const user_id = req.query.user_id;
const user = await User.findOne({ _id: user_id });
res.json({ lastUpdated: user.lastUpdated });
} catch (error) {
res.status(500).json({error});
}
});
//----------------------------------------------Note
app.get('/api/notes', async (req, res) => {
try {
const user_id = req.query.user_id;
const taskDocuments = await Note.find({ user_id: user_id })
res.json(taskDocuments)
} catch (error){
res.status(500).json({error})
}
})
app.get('/api/news', async (req, res) => {
try {
const pageUrl = 'https://jwc.sjtu.edu.cn/xwtg/tztg.htm';
// const pageUrl = 'https://jwc.sjtu.edu.cn/index/mxxsdtz.htm'
const response = await fetch(pageUrl)
const data = await response.text()
const dom = new JSDOM(data)
const newsElements = dom.window.document.querySelectorAll('.Newslist .clearfix')
const newsList = []
Array.from(newsElements).map(element => {
const sjElement = element.querySelector('.sj')
const [year, month] = sjElement.querySelector('p').textContent.split('.')
const day = sjElement.querySelector('h2').textContent
const date = year + '-' + month + '-' + day
const dateTime = new Date(date)
const contentElement = element.querySelector('.wz')
const title = contentElement.querySelector('h2').textContent
const link = new URL(contentElement.querySelector('a').href, pageUrl).href
const detail = contentElement.querySelector('p').textContent
let newNews = {
title: title,
detail: detail || '',
link: link,
isImportant: false,
dateTime: dateTime,
};
newsList.push(newNews);
})
res.json(newsList);
} catch (error) {
res.status(500).json({error});
}
});
app.post('/insert-note', async (req, res) => {
const note = new Note(req.body)
note.save()
.then(() => res.json({msg: "success"}))
.catch(error => res.status(500).json({error}))
})
app.post('/update-note', async (req, res) => {
const note = req.body
Note.updateOne({_id : req.body._id}, note)
.then(() => res.redirect(web + "note"))
.catch(error => res.status(500).json({error}))
})
app.post('/update-important-note', async (req, res) => {
Note.updateOne({_id : req.body._id}, { $set: { isImportant: req.body.isImportant } })
.then(() => res.json({msg: "success"}))
.catch(error => res.status(500).json({error}))
})
app.post('/update-detail', async (req, res) => {
try {
const pageUrl = req.body.link
// const pageUrl = "https://jwc.sjtu.edu.cn/info/1222/113131.htm"
const response = await fetch(pageUrl)
const data = await response.text()
const dom = new JSDOM(data)
const newDetail = dom.window.document.querySelector('.v_news_content').innerHTML
const convertedString = newDetail.replace(/<p[^>]*>/g, '').replace(/<\/p>/g, '\n').replace(/<[^>]+>/g, '')
// res.json(convertedString)
Note.updateOne({_id : req.body._id}, { $set: { detail : convertedString } })
.then(() => res.redirect(web + "note"))
.catch(error => res.status(500).json({error}))
} catch (error) {
res.status(500).json({error});
}
});
app.post('/delete-note', async (req, res) => {
const id = req.body._id
await Note.deleteOne({_id : id})
.then(() => res.redirect(web + "note"))
.catch(error => res.status(500).json({error}))
})
//----------------------------------------------User
app.get('/api/users', async (req, res) => {
try {
const userDocuments = await User.find({})
res.json(userDocuments)
} catch (error){
res.status(500).json({error})
}
})
app.post('/insert-user', async (req, res) => {
const user = new User(req.body)
const email = user.email
const name = user.userName
const existingUser = await User.findOne({
$or: [
{email: email },
{userName: name}
]
})
if (existingUser) {
return res.status(400).json({ error: '该邮箱或用户名已被注册' });
} else {
user.save()
.then(() => res.redirect(web))
.catch(error => res.status(500).json({error}))
}
})
app.post('/update-user', async (req, res) => {
const user = req.body
User.updateOne({_id : req.body._id}, user)
.then(() => res.redirect(web))
.catch(error => res.status(500).json({error}))
})
app.post('/delete-user', async (req, res) => {
const id = req.body._id
await User.deleteOne({_id : id})
.then(() => res.redirect(web))
.catch(error => res.status(500).json({error}))
})
app.post('/api/login', (req, res) => {
const { userName, passWord } = req.body;
User.findOne({ userName })
.then((user) => {
if (!user || passWord !== user.passWord) {
res.status(401).json({ error: 'Invalid credentials' });
return;
}
const token = jwt.sign({ userId: user._id }, SECRET_KEY, {
expiresIn: '168h',
});
res.json({ token });
})
.catch((error) => {
res.status(500).json({ error: 'An error occurred' });
});
});
function authenticateToken(req, res, next) {
const token = req.headers.authorization;
if (!token) {
res.status(401).json({ error: 'Access denied' });
return;
}
jwt.verify(token, SECRET_KEY, (err, decoded) => {
if (err) {
res.status(403).json({ error: 'Invalid token' });
return;
}
req.userId = decoded.userId;
next();
});
}
app.post('/api/protected', authenticateToken, async (req, res) => {
try {
const userId = req.userId;
res.json({ user_id: userId });
} catch (error) {
res.status(500).json({ error });
}
});
app.post('/api/email', async (req, res) => {
const email = req.body.email
const code = req.body.code
// String(Math.floor(Math.random() * 1000000)).padEnd(6, '0')
const mail = {
from: `"wdl"<2720609228@qq.com>`,
subject: '验证码',
to: email,
html: `
<p>同学你好!</p>
<p>你的验证码是:<strong style="color:orangered;">${code}</strong></p>
<p>打死也不要告诉别人哦!</p>
<p>如果不是本人操作,请无视此邮件</p>
`
};
await nodeMail.sendMail(mail, (err, info) => {
if (!err) {
res.json({msg: "验证码发送成功"})
} else {
res.json({msg: "验证码发送失败,请稍后重试"})
}
})
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})