1 import * as SocketIO from 'socket.io'
2 import { authenticateSocket } from '../middlewares'
3 import { UserNotificationModel } from '../models/account/user-notification'
4 import { logger } from '../helpers/logger'
5 import { Server } from 'http'
9 private static instance: PeerTubeSocket
11 private userNotificationSockets: { [ userId: number ]: SocketIO.Socket } = {}
13 private constructor () {}
15 init (server: Server) {
16 const io = SocketIO(server)
18 io.of('/user-notifications')
19 .use(authenticateSocket)
20 .on('connection', socket => {
21 const userId = socket.handshake.query.user.id
23 logger.debug('User %d connected on the notification system.', userId)
25 this.userNotificationSockets[userId] = socket
27 socket.on('disconnect', () => {
28 logger.debug('User %d disconnected from SocketIO notifications.', userId)
30 delete this.userNotificationSockets[userId]
35 sendNotification (userId: number, notification: UserNotificationModel) {
36 const socket = this.userNotificationSockets[userId]
40 socket.emit('new-notification', notification.toFormattedJSON())
43 static get Instance () {
44 return this.instance || (this.instance = new this())
48 // ---------------------------------------------------------------------------