1 import { Socket } from 'dgram'
2 import { Server } from 'http'
3 import * as SocketIO from 'socket.io'
4 import { MVideo } from '@server/types/models'
5 import { UserNotificationModelForApi } from '@server/types/models/user'
6 import { LiveVideoEventPayload, LiveVideoEventType } from '@shared/models'
7 import { logger } from '../helpers/logger'
8 import { authenticateSocket } from '../middlewares'
9 import { isIdValid } from '@server/helpers/custom-validators/misc'
11 class PeerTubeSocket {
13 private static instance: PeerTubeSocket
15 private userNotificationSockets: { [ userId: number ]: SocketIO.Socket[] } = {}
16 private liveVideosNamespace: SocketIO.Namespace
18 private constructor () {}
20 init (server: Server) {
21 const io = SocketIO(server)
23 io.of('/user-notifications')
24 .use(authenticateSocket)
25 .on('connection', socket => {
26 const userId = socket.handshake.query.user.id
28 logger.debug('User %d connected on the notification system.', userId)
30 if (!this.userNotificationSockets[userId]) this.userNotificationSockets[userId] = []
32 this.userNotificationSockets[userId].push(socket)
34 socket.on('disconnect', () => {
35 logger.debug('User %d disconnected from SocketIO notifications.', userId)
37 this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket)
41 this.liveVideosNamespace = io.of('/live-videos')
42 .on('connection', socket => {
43 socket.on('subscribe', ({ videoId }) => {
44 if (!isIdValid(videoId)) return
49 socket.on('unsubscribe', ({ videoId }) => {
50 if (!isIdValid(videoId)) return
57 sendNotification (userId: number, notification: UserNotificationModelForApi) {
58 const sockets = this.userNotificationSockets[userId]
61 logger.debug('Sending user notification to user %d.', userId)
63 const notificationMessage = notification.toFormattedJSON()
64 for (const socket of sockets) {
65 socket.emit('new-notification', notificationMessage)
69 sendVideoLiveNewState (video: MVideo) {
70 const data: LiveVideoEventPayload = { state: video.state }
71 const type: LiveVideoEventType = 'state-change'
73 logger.debug('Sending video live new state notification of %s.', video.url)
75 this.liveVideosNamespace
80 static get Instance () {
81 return this.instance || (this.instance = new this())
85 // ---------------------------------------------------------------------------