aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/peertube-socket.ts
blob: eb84ecd4bbb134a3216f2ca62576b9459f0a7274 (plain) (blame)
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
import * as SocketIO from 'socket.io'
import { authenticateSocket } from '../middlewares'
import { UserNotificationModel } from '../models/account/user-notification'
import { logger } from '../helpers/logger'
import { Server } from 'http'

class PeerTubeSocket {

  private static instance: PeerTubeSocket

  private userNotificationSockets: { [ userId: number ]: SocketIO.Socket } = {}

  private constructor () {}

  init (server: Server) {
    const io = SocketIO(server)

    io.of('/user-notifications')
      .use(authenticateSocket)
      .on('connection', socket => {
        const userId = socket.handshake.query.user.id

        logger.debug('User %d connected on the notification system.', userId)

        this.userNotificationSockets[userId] = socket

        socket.on('disconnect', () => {
          logger.debug('User %d disconnected from SocketIO notifications.', userId)

          delete this.userNotificationSockets[userId]
        })
      })
  }

  sendNotification (userId: number, notification: UserNotificationModel) {
    const socket = this.userNotificationSockets[userId]

    if (!socket) return

    socket.emit('new-notification', notification.toFormattedJSON())
  }

  static get Instance () {
    return this.instance || (this.instance = new this())
  }
}

// ---------------------------------------------------------------------------

export {
  PeerTubeSocket
}