-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
463 lines (413 loc) · 15.7 KB
/
index.js
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
require('tls').DEFAULT_MIN_VERSION = 'TLSv1'
require('dotenv').config();
const config = require('./config.json')
const fetch = require('node-fetch')
const Sentry = require('@sentry/node')
Sentry.init({
dsn: config.sentryDSN,
tracesSampleRate: 1.0
})
// Start express server
const morgan = require('morgan')
const express = require('express')
const app = express()
app.use(express.json())
app.use(morgan('dev'))
app.listen(config.port, () => console.log(`Pronote Notifications API server listening on port ::${config.port}::`))
const DatabaseService = require('./services/database')
const PronoteService = require('./services/pronote')
const FirebaseService = require('./services/firebase')
const jwt = require('./services/jwt')
const database = new DatabaseService()
const pronote = new PronoteService()
const firebase = new FirebaseService()
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const synchronize = async (studentName) => {
const users = await database.fetchUsers()
const usersCaches = await database.fetchUsersCache()
const usersTokens = await database.fetchFCMTokens()
const usersSync = users.filter((user) => !user.passwordInvalidated && (studentName ? user.pronoteUsername === studentName : true))
for (const [index, userAuth] of usersSync.entries()) {
await sleep(500)
const oldCache = usersCaches.find((cache) => {
return cache.pronoteUsername === userAuth.pronoteUsername && cache.pronoteURL === userAuth.pronoteURL
})
pronote.checkSession(userAuth, oldCache, index).then(([notifications, newCache]) => {
if (notifications.length > 0) {
const tokens = usersTokens.filter((token) => {
return token.pronoteUsername === userAuth.pronoteUsername && token.pronoteURL === userAuth.pronoteURL && token.isActive
})
const homeworksTokens = tokens.filter((token) => token.notificationsHomeworks).map((token) => token.fcmToken)
const marksTokens = tokens.filter((token) => token.notificationsMarks).map((token) => token.fcmToken)
notifications.forEach((notificationData) => {
database.createNotification(userAuth, notificationData).then((notificationDBID) => {
const notification = {
title: notificationData.title,
body: notificationData.body
}
const sentAt = new Date()
if (notificationData.type === 'homework' && homeworksTokens.length > 0) {
firebase.sendNotification(notification, 'homework', homeworksTokens).then((responses) => {
database.markNotificationSent(notificationDBID, new Date())
responses.forEach((res, i) => {
const token = marksTokens[i]
database.markLastActiveAt(token, sentAt)
if (res.success) database.markLastSuccessAt(token, sentAt)
})
})
} else if (notificationData.type === 'mark' && marksTokens.length > 0) {
firebase.sendNotification(notification, 'mark', marksTokens).then((responses) => {
database.markNotificationSent(notificationDBID, new Date())
responses.forEach((res, i) => {
const token = marksTokens[i]
database.markLastActiveAt(token, sentAt)
if (res.success) database.markLastSuccessAt(token, sentAt)
})
})
}
})
})
}
database.updateUserCache(userAuth, newCache)
}).catch((e) => {
if (e.message === 'Wrong user credentials') {
database.invalidateUserPassword(userAuth)
}
})
}
}
const checkInvalidated = async () => {
const users = await database.fetchUsers()
const usersInvalidated = users.filter((u) => u.passwordInvalidated)
const failed = []
usersInvalidated.forEach((user) => {
if (failed.filter((e) => e === user.pronoteURL).length < 1) {
pronote.createSession(user).then(() => {
database.invalidateUserPassword(user, false)
}).catch(() => {
failed.push(user.pronoteURL)
})
}
})
}
const userToSynchronize = process.argv[process.argv.indexOf('--sync') + 1] === 'all' ? null : process.argv[process.argv.indexOf('--sync') + 1]
if (process.argv.includes('--sync')) synchronize(userToSynchronize)
if (process.argv.includes('--checkinv')) checkInvalidated()
synchronize()
setInterval(function () {
synchronize()
}, 30 * 60 * 1000)
setInterval(() => {
checkInvalidated()
}, 24 * 60 * 60 * 1000)
app.post('/logout', async (req, res) => {
const token = req.headers.authorization
const payload = jwt.verifyToken(token)
if (!token || !payload) {
return res.status(403).send({
success: false,
code: 2,
message: 'Unauthorized'
})
}
database.createUserLog(payload, {
route: '/logout',
appVersion: req.headers['app-version'] || 'unknown',
date: new Date(),
jwt: token
})
if (payload.pronoteURL === 'demo') {
return res.status(200).send({
success: true
})
}
const existingToken = await database.fetchFCMToken(payload.fcmToken)
if (!existingToken) {
return res.status(500).send({
success: false,
code: 4,
message: 'Unknown FCM token'
})
}
database.updateToken(payload.fcmToken, {
isActive: false
})
return res.status(200).send({
success: true
})
})
app.post('/settings', async (req, res) => {
const token = req.headers.authorization
const payload = jwt.verifyToken(token)
if (!token || !payload) {
return res.status(403).send({
success: false,
code: 2,
message: 'Unauthorized'
})
}
const data = req.body
database.createUserLog(payload, {
route: '/settings',
appVersion: req.headers['app-version'] || 'unknown',
date: new Date(),
body: data,
jwt: token
})
if (payload.pronoteURL === 'demo') {
return res.status(200).send({
success: true
})
}
const existingToken = await database.fetchFCMToken(payload.fcmToken)
if (!existingToken) {
return res.status(500).send({
success: false,
code: 4,
message: 'Unknown FCM token'
})
}
database.updateToken(payload.fcmToken, {
notificationsHomeworks: data.notifications_homeworks === 'true',
notificationsMarks: data.notifications_marks === 'true'
})
return res.status(200).send({
success: true
})
})
app.get('/notifications', async (req, res) => {
const token = req.headers.authorization
const payload = jwt.verifyToken(token)
if (!token || !payload) {
return res.status(403).send({
success: false,
code: 2,
message: 'Unauthorized'
})
}
database.createUserLog(payload, {
route: '/notifications',
appVersion: req.headers['app-version'] || 'unknown',
date: new Date(),
jwt: token
})
if (payload.pronoteURL === 'demo') {
const minDate = new Date(2012, 0, 1)
const randomDate = () => new Date(minDate.getTime() + Math.random() * (Date.now() - minDate.getTime()))
return res.status(200).send({
success: true,
notifications: [
{
created_at: randomDate(),
read_at: randomDate(),
sent_at: randomDate(),
title: 'Nouvelle note en HISTOIRE-GEOGRAPHIE',
body: 'Note: 19/20\nMoyenne de la classe: 11.91/20',
type: 'mark'
}
]
})
}
const user = await database.fetchUser(payload.pronoteUsername, payload.pronoteURL)
if (!user) {
return res.status(403).send({
success: false,
code: 3,
message: 'Votre compte est introuvable.'
})
}
const notifications = (await database.fetchUserNotifications(payload.pronoteUsername, payload.pronoteURL))
.sort((a, b) => {
const createdOrder = b.createdAt.getTime() - a.createdAt.getTime()
if (createdOrder !== 0) return createdOrder
else return b.body.length - a.body.length
})
.map((notif) => ({
created_at: notif.createdAt,
read_at: notif.readAt,
sent_at: notif.sentAt,
title: notif.title,
body: notif.body,
type: notif.type
}))
return res.status(200).send({
success: true,
notifications
})
})
app.get('/login', async (req, res) => {
const token = req.headers.authorization
const payload = jwt.verifyToken(token)
if (!token || !payload) {
return res.status(403).send({
success: false,
code: 2,
message: 'Unauthorized'
})
}
database.createUserLog(payload, {
route: '/login',
appVersion: req.headers['app-version'] || 'unknown',
date: new Date(),
jwt: token
})
if (payload.pronoteURL === 'demo') {
return res.status(200).send({
success: true,
full_name: 'Sarah Kelly',
student_class: '204',
establishment: 'Lycée Gustave Eiffel',
notifications_homeworks: true,
notifications_marks: true
})
}
const user = await database.fetchUser(payload.pronoteUsername, payload.pronoteURL)
if (!user) {
return res.status(403).send({
success: false,
code: 3,
message: 'Votre compte est introuvable.'
})
} else {
const existingToken = await database.fetchFCMToken(payload.fcmToken)
if (!existingToken) {
return res.status(500).send({
success: false,
code: 4,
message: 'Unknown FCM token'
})
}
return res.status(200).send({
success: true,
full_name: user.fullName,
student_class: user.studentClass,
establishment: user.establishment,
password_invalidated: user.passwordInvalidated,
notifications_homeworks: existingToken.notificationsHomeworks,
notifications_marks: existingToken.notificationsMarks
})
}
})
app.get('/establishments', async (req, res) => {
if (!req.query.latitude || !req.query.longitude) return
database.createUserLog({
pronoteUsername: 'unknown',
pronoteURL: 'unknown',
fcmToken: 'unknown'
}, {
route: '/establishments',
appVersion: req.headers['app-version'] || 'unknown',
date: new Date(),
body: { latitude: req.query.latitude, longitude: req.query.longitude }
})
const establishments = (await pronote.getEstablishments(req.query.latitude, req.query.longitude)) || []
return res.status(200).send({
success: true,
establishments
})
})
app.post('/register', async (req, res) => {
const body = req.body
if (!body.pronote_url) {
return void console.log(body);
}
const userAuth = {
pronoteUsername: body.pronote_username,
pronotePassword: body.pronote_password,
pronoteURL: pronote.parsePronoteURL(body.pronote_url),
fcmToken: body.fcm_token
}
if (Object.values(userAuth).some((v) => v === undefined)) {
return res.status(400).send({
success: false,
message: 'BAD REQUEST. Essayez de mettre à jour l\'application et réessayez !'
})
}
if (body.device_id) userAuth.deviceID = body.device_id
database.createUserLog(userAuth, {
route: '/register',
appVersion: req.headers['app-version'] || 'unknown',
date: new Date(),
body: userAuth
})
const token = jwt.createToken(userAuth)
const isValidToken = await firebase.verifyToken(userAuth.fcmToken)
if (!isValidToken) {
return res.status(403).send({
success: false,
message: 'Impossible de valider le token FCM.'
})
}
if (userAuth.pronoteURL === 'demo') {
return res.status(200).send({
success: true,
full_name: 'Sarah Kelly',
student_class: '204',
establishment: 'Lycée Gustave Eiffel',
notifications_homeworks: true,
notifications_marks: true,
jwt: token
})
}
let { cas, session } = await pronote.resolveCas(userAuth)
userAuth.pronoteCAS = cas
if (!session) {
session = await pronote.createSession(userAuth).catch((error) => {
let message = 'Connexion à Pronote impossible car l\'URL Pronote entrée est invalide. Fermez la pop-up et cliquez sur "Q\'est-ce que "URL Pronote" ou rejoignez notre serveur Discord : https://androz2091.fr/discord pour plus d\'informations. Tous les lycées et collèges étant supportés, nous vous aiderons à trouver la bonne URL.'
if (error.code === 3) message = 'Connexion à Pronote réussie mais vos identifiants sont incorrects. Vérifiez et réessayez !'
if (error.code === 2) message = 'Le serveur de Notifications pour Pronote est actuellement indisponible. Réessayez dans quelques minutes !'
res.status(403).send({
success: false,
message
})
return null
})
}
if (!session) return
const user = await database.fetchUser(userAuth.pronoteUsername, userAuth.pronoteURL)
if (user) {
if (user.pronotePassword !== userAuth.pronotePassword) {
database.updateUserPassword({
pronoteUsername: userAuth.pronoteUsername,
pronoteURL: userAuth.pronoteURL,
newPassword: userAuth.pronotePassword
})
}
database.invalidateUserPassword(userAuth, false)
res.status(200).send({
success: true,
full_name: user.fullName,
student_class: user.studentClass,
establishment: user.establishment,
password_invalidated: user.passwordInvalidated,
notifications_homeworks: true,
notifications_marks: true,
jwt: token
})
} else {
res.status(200).send({
success: true,
full_name: session.user.name,
student_class: session.user.studentClass.name,
establishment: session.user.establishment.name,
notifications_homeworks: true,
notifications_marks: true,
jwt: token
})
database.createUser({
...userAuth,
...{
fullName: session.user.name,
studentClass: session.user.studentClass.name,
establishment: session.user.establishment.name
}
})
pronote.checkSession(userAuth, {}).then(([notifications, cache]) => {
database.updateUserCache(userAuth, cache)
})
}
database.createOrUpdateToken(userAuth, userAuth.fcmToken, userAuth.deviceID)
})
app.get('*', (req, res) => res.send({
success: true, message: 'Welcome to Notifications pour Pronote API'
}))