]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/peertube-socket.ts
Fix socket notification with multiple user tabs
[github/Chocobozzz/PeerTube.git] / server / lib / peertube-socket.ts
CommitLineData
cef534ed
C
1import * as SocketIO from 'socket.io'
2import { authenticateSocket } from '../middlewares'
3import { UserNotificationModel } from '../models/account/user-notification'
4import { logger } from '../helpers/logger'
5import { Server } from 'http'
6
7class PeerTubeSocket {
8
9 private static instance: PeerTubeSocket
10
015d9dec 11 private userNotificationSockets: { [ userId: number ]: SocketIO.Socket[] } = {}
cef534ed
C
12
13 private constructor () {}
14
15 init (server: Server) {
16 const io = SocketIO(server)
17
18 io.of('/user-notifications')
19 .use(authenticateSocket)
20 .on('connection', socket => {
21 const userId = socket.handshake.query.user.id
22
23 logger.debug('User %d connected on the notification system.', userId)
24
015d9dec
C
25 if (!this.userNotificationSockets[userId]) this.userNotificationSockets[userId] = []
26
27 this.userNotificationSockets[userId].push(socket)
cef534ed
C
28
29 socket.on('disconnect', () => {
30 logger.debug('User %d disconnected from SocketIO notifications.', userId)
31
015d9dec 32 this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket)
cef534ed
C
33 })
34 })
35 }
36
37 sendNotification (userId: number, notification: UserNotificationModel) {
015d9dec 38 const sockets = this.userNotificationSockets[userId]
cef534ed 39
015d9dec 40 if (!sockets) return
cef534ed 41
015d9dec
C
42 for (const socket of sockets) {
43 socket.emit('new-notification', notification.toFormattedJSON())
44 }
cef534ed
C
45 }
46
47 static get Instance () {
48 return this.instance || (this.instance = new this())
49 }
50}
51
52// ---------------------------------------------------------------------------
53
54export {
55 PeerTubeSocket
56}