Repository navigation
Expand file tree
/
Copy pathnoteshandler.js
More file actions
494 lines (447 loc) · 15.2 KB
/
Copy pathnoteshandler.js
File metadata and controls
494 lines (447 loc) · 15.2 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
/* eslint-disable node/no-callback-literal */
/*
Fails Components (Fancy Automated Internet Lecture System - Components)
Copyright (C) 2015-2017 (original FAILS),
2021- (FAILS Components) Marten Richter <marten.richter@freenet.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { createHash } from 'crypto'
import { CommonConnection } from './commonhandler.js'
export class NotesConnection extends CommonConnection {
constructor(args) {
super(args)
this.redis = args.redis
this.mongo = args.mongo
this.notesio = args.notesio
this.notepadio = args.notepadio
this.screenio = args.screenio
this.getFileURL = args.getFileURL
this.noteshandlerURL = args.noteshandlerURL
this.signNotesJwt = args.signNotesJwt
this.signAvsJwt = args.signAvsJwt
this.SocketHandlerNotes = this.SocketHandlerNotes.bind(this)
}
async SocketHandlerNotes(socket) {
const address = socket.handshake.headers['x-forwarded-for']
.split(',')
.map((el) => el.trim()) || [socket.client.conn.remoteAddress]
console.log('Notes %s with ip %s connected', socket.id, address)
console.log('Notes name', socket.decoded_token.name)
console.log('Notes lecture uuid', socket.decoded_token.lectureuuid)
const purenotes = {
socketid: socket.id,
lectureuuid: socket.decoded_token.lectureuuid,
name: socket.decoded_token.name,
displayname: socket.decoded_token.user.displayname,
appversion: socket.decoded_token.appversion,
features: socket.decoded_token.features,
purpose: 'notes'
}
let curtoken = socket.decoded_token
let routerres
let routerurl = new Promise((resolve) => {
routerres = resolve
})
// console.log('notes connected')
this.getLectDetail(purenotes, socket)
// console.log('notes send board data')
this.sendBoardsToSocket(purenotes.lectureuuid, socket)
purenotes.roomname = this.getRoomName(purenotes.lectureuuid)
{
const messagehash = createHash('sha256')
const useruuid = socket.decoded_token.user.useruuid
// now we create a hash that can be used to identify a user, if and only if,
// access to this database is available and not between lectures!
messagehash.update(useruuid + purenotes.lectureuuid)
purenotes.userhash = messagehash.digest('hex')
}
// console.log('notes is connected to notepad, join room', purenotes.roomname)
socket.join(purenotes.roomname)
{
const token = await this.getNotesToken(curtoken)
curtoken = token.decoded
socket.emit('authtoken', { token: token.token })
}
socket.emit('userhash', purenotes.userhash)
{
const presinfo = this.getPresentationinfo(purenotes)
const readypresinfo = await presinfo
socket.emit('presinfo', readypresinfo)
}
this.emitAVOffers(socket, purenotes)
this.emitVideoquestions(socket, purenotes)
socket.on(
'reauthor',
async function () {
// we use the information from the already present authtoken
this.addUpdateCryptoIdent(purenotes)
const token = await this.getNotesToken(curtoken)
curtoken = token.decoded
socket.emit('authtoken', { token: token.token })
}.bind(this)
)
socket.on('chatquestion', (cmd) => {
if (cmd.text) {
const displayname = socket.decoded_token.user.displayname
const userhash = purenotes.userhash
this.notepadio.to(purenotes.roomname).emit('chatquestion', {
displayname,
text: cmd.text,
encData: cmd.encData,
keyindex: cmd.keyindex,
iv: cmd.iv,
videoquestion: cmd.videoquestion
? { id: purenotes.socketid }
: undefined,
userhash
})
// console.log("chat send", cmd.text,socket.decoded_token);
}
// console.log("chatquestion",cmd);
})
socket.on('closevideoquestion', (cmd) => {
this.closeVideoQuestion(purenotes, { id: purenotes.socketid }).catch(
(error) => {
console.log('Problem in closeVideoQuestion', error)
}
)
})
socket.on('avoffer', (cmd) => {
this.handleVQoffer(purenotes, cmd).catch((error) => {
console.log('Problem in handleVQoffer', error)
})
})
socket.on('castvote', async (data, callback) => {
if (
data.pollid &&
/^[0-9a-zA-Z]{9}$/.test(data.pollid) &&
data.selection &&
((typeof data.selection === 'string' &&
/^[0-9a-zA-Z]{9}$/.test(data.selection)) ||
(Array.isArray(data.selection) &&
data.selection.filter((el) => /^[0-9a-zA-Z]{9}$/.test(el)).length >
0))
) {
const pollstate = await this.getPollinfo(purenotes)
if (
pollstate.limited &&
!pollstate.participants.includes(purenotes.userhash)
) {
console.log('not eglible to vote!')
callback({ error: 'not eglible to vote!' })
return
}
if (pollstate.data.id !== data.pollid) {
callback({ error: 'pollid does not match current running poll!' })
return
}
const useruuid = socket.decoded_token.user.useruuid
try {
const ballothash = createHash('sha256')
ballothash.update(useruuid + data.pollid)
const salt = await this.redis.get(
'pollsalt:lecture:' + purenotes.lectureuuid + ':poll:' + data.pollid
)
ballothash.update(salt)
const ballotid = ballothash.digest('hex')
this.notepadio.to(purenotes.roomname).emit('castvote', {
ballotid: ballotid,
vote: data.selection,
pollid: data.pollid
})
callback({ ballot: ballotid })
} catch (err) {
console.log('failed to get salt', err)
callback({ error: 'failure' })
}
} else callback({ error: 'failure' })
})
socket.on('getrouting', async (cmd, callback) => {
let tempOut
if (cmd.dir === 'out' && cmd.id === purenotes.socketid) {
let toid
try {
await Promise.any([
routerurl,
new Promise((resolve, reject) => {
toid = setTimeout(reject, 20 * 1000)
})
])
if (toid) clearTimeout(toid)
toid = undefined
tempOut = await this.getTempOutTransport(purenotes, await routerurl)
} catch (error) {
callback({ error: 'getrouting: timeout or error tempout: ' + error })
}
}
if (
cmd &&
cmd.id &&
cmd.dir &&
(cmd.dir === 'in' || tempOut) /* || cmd.dir === 'out' */ // a notes can only receive, later with special permission
) {
try {
let toid
await Promise.any([
routerurl,
new Promise((resolve, reject) => {
toid = setTimeout(reject, 20 * 1000)
})
])
if (toid) clearTimeout(toid)
toid = undefined
this.getRouting(
purenotes,
{ ...cmd, tempOut },
await routerurl,
callback
)
} catch (error) {
callback({ error: 'getrouting: timeout or error: ' + error })
}
} else callback({ error: 'getrouting: malformed request' })
})
socket.on('gettransportinfo', (cmd, callback) => {
let geopos
if (cmd && cmd.geopos && cmd.geopos.longitude && cmd.geopos.latitude)
geopos = {
longitude: cmd.geopos.longitude,
latitude: cmd.geopos.latitude
}
this.getTransportInfo(
{
ipaddress: address,
geopos,
lectureuuid: purenotes.lectureuuid,
clientid: socket.id,
canWrite: false
},
(ret) => {
if (ret.url) {
if (routerres) {
const res = routerres
routerres = undefined
res(ret.url)
}
routerurl = ret.url
} else routerurl = undefined
callback(ret)
}
).catch((error) => {
console.log('Problem in getTransportInfo', error)
})
})
socket.on('keyInfo', (cmd) => {
if (cmd.cryptKey && cmd.signKey) {
purenotes.cryptKey = cmd.cryptKey
purenotes.signKey = cmd.signKey
this.addUpdateCryptoIdent(purenotes)
}
})
socket.on('keymasterQuery', () => {
this.handleKeymasterQuery(purenotes)
})
socket.on('disconnect', async () => {
console.log(
'Notes Client %s with ip %s disconnected',
socket.id,
address
)
if (purenotes) {
if (purenotes.roomname) {
socket.leave(purenotes.roomname)
try {
const proms = []
proms.push(
this.redis.hDel(
'lecture:' + purenotes.lectureuuid + ':idents',
purenotes.socketid
)
)
proms.push(
this.redis.hDel(
'lecture:' + purenotes.lectureuuid + ':videoquestion',
'permitted:' + purenotes.socketid
)
)
this.notepadio
.to(purenotes.roomname)
.emit('identDelete', { id: purenotes.socketid })
const promres = await Promise.all(proms)
if (promres[1] > 0) {
this.notepadio
.to(purenotes.roomname)
.emit('closevideoquestion', { id: purenotes.socketid })
this.screenio
.to(purenotes.roomname)
.emit('closevideoquestion', { id: purenotes.socketid })
this.notesio
.to(purenotes.roomname)
.emit('closevideoquestion', { id: purenotes.socketid })
}
} catch (error) {
console.log('Problem disconnect:', error)
}
// console.log('notes disconnected leave room', purenotes.roomname)
purenotes.roomname = null
}
}
})
{
const pollstate = await this.getPollinfo(purenotes)
if (pollstate) {
let canVote = true
if (pollstate.limited) {
if (!pollstate.participants.includes(purenotes.userhash)) {
canVote = false
}
}
socket.emit(pollstate.command, { ...pollstate.data, canVote })
}
}
}
async getNotesToken(oldtoken) {
const newtoken = {
lectureuuid: oldtoken.lectureuuid,
purpose: 'notes', // in case a bug is there, no one should escape the realm
name: oldtoken.name,
user: oldtoken.user,
appversion: oldtoken.appversion,
features: oldtoken.features,
noteshandler: this.noteshandlerURL,
maxrenew: oldtoken.maxrenew - 1
}
if (!oldtoken.maxrenew || !(oldtoken.maxrenew > 0))
return { error: 'maxrenew token failed', oldtoken: oldtoken }
return { token: await this.signNotesJwt(newtoken), decoded: newtoken }
}
async getTempOutTransport(args, routerurl) {
try {
// first check permissions
const exists = await this.redis.hExists(
'lecture:' + args.lectureuuid + ':videoquestion',
'permitted:' + args.socketid
)
if (!exists) return
// very well we have the permission, so generate a token for temperory perms
const routercol = this.mongo.collection('avsrouters')
const majorid = args.lectureuuid
const clientid = args.lectureuuid + ':' + args.socketid
const router = await routercol.findOne(
{
url: routerurl
},
{
projection: {
_id: 0,
url: 1,
region: 1,
key: 1,
spki: 1,
primaryRealms: { $elemMatch: { $eq: majorid } },
hashSalt: 1,
localClients: { $elemMatch: { $eq: clientid } },
remoteClients: { $elemMatch: { $eq: clientid } }
}
}
)
const calcHash = async (input) => {
const hash = createHash('sha256')
hash.update(input)
// console.log('debug router info', router)
hash.update(router.hashSalt)
return hash.digest('base64')
}
const realmhash = calcHash(args.lectureuuid)
const clienthash = calcHash(args.socketid)
let token = {}
// todo hash table
token.accessWrite = [
(await realmhash).replace(/[+/]/g, '\\$&') +
':' +
(await clienthash).replace(/[+/]/g, '\\$&')
]
token.realm = await realmhash
token.client = await clienthash
token = this.signAvsJwt(token)
return await token
} catch (error) {
console.log('Problem getTempOutTransport', error)
throw new Error()
}
}
async handleVQoffer(args, cmd) {
// ok to things to do, inform the others about the offer
// and store the information in redis
if (
cmd.type !== 'video' &&
cmd.type !== 'audio' /* && cmd.type !== 'screen' */
) {
return
}
const roomname = this.getRoomName(args.lectureuuid)
const message = {
id: args.socketid,
type: cmd.type,
db: cmd.db // loundness in case of audio
}
this.notepadio.to(roomname).emit('vqoffer', message)
this.screenio.to(roomname).emit('vqoffer', message)
this.notesio.to(roomname).emit('vqoffer', message)
// VQ offers are not saved
}
async getPresentationinfo(args) {
try {
let lectprop = this.redis.hmGet('lecture:' + args.lectureuuid, [
'casttoscreens',
'backgroundbw',
'showscreennumber'
])
lectprop = await lectprop
return {
casttoscreens: lectprop[0] !== null ? lectprop[0] : 'false',
backgroundbw: lectprop[1] !== null ? lectprop[1] : 'true',
showscreennumber: lectprop[2] !== null ? lectprop[2] : 'false'
}
} catch (error) {
console.log('getPresentationinfo', error)
return null
}
}
async getPollinfo(args) {
try {
const pollinfo = await this.redis.hGetAll(
'lecture:' + args.lectureuuid + ':pollstate'
)
if (pollinfo.command && pollinfo.data) {
const limited = !!(pollinfo.limited === 'true')
let participants
if (limited) {
if (!pollinfo.participants) {
console.log('getPollinfo no participants for limited poll')
return null
}
participants = JSON.parse(pollinfo.participants)
}
return {
command: pollinfo.command,
data: JSON.parse(pollinfo.data),
limited,
participants
}
} else return null
} catch (error) {
console.log('getPollInfo failed', error)
return null
}
}
}