]>
Commit | Line | Data |
---|---|---|
cef534ed C |
1 | import * as SocketIO from 'socket.io' |
2 | import { authenticateSocket } from '../middlewares' | |
cef534ed C |
3 | import { logger } from '../helpers/logger' |
4 | import { Server } from 'http' | |
453e83ea | 5 | import { UserNotificationModelForApi } from '@server/typings/models/user' |
cef534ed C |
6 | |
7 | class PeerTubeSocket { | |
8 | ||
9 | private static instance: PeerTubeSocket | |
10 | ||
1b42d73f | 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 | ||
1b42d73f 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 | ||
1b42d73f | 32 | this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket) |
cef534ed C |
33 | }) |
34 | }) | |
35 | } | |
36 | ||
453e83ea | 37 | sendNotification (userId: number, notification: UserNotificationModelForApi) { |
1b42d73f | 38 | const sockets = this.userNotificationSockets[userId] |
cef534ed | 39 | |
1b42d73f | 40 | if (!sockets) return |
cef534ed | 41 | |
20ec0384 | 42 | const notificationMessage = notification.toFormattedJSON() |
1b42d73f | 43 | for (const socket of sockets) { |
20ec0384 | 44 | socket.emit('new-notification', notificationMessage) |
1b42d73f | 45 | } |
cef534ed C |
46 | } |
47 | ||
48 | static get Instance () { | |
49 | return this.instance || (this.instance = new this()) | |
50 | } | |
51 | } | |
52 | ||
53 | // --------------------------------------------------------------------------- | |
54 | ||
55 | export { | |
56 | PeerTubeSocket | |
57 | } |