]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/peertube-socket.ts
c4df399caa3c4977e2d9290101e80972159b578b
[github/Chocobozzz/PeerTube.git] / server / lib / peertube-socket.ts
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'
10
11 class PeerTubeSocket {
12
13 private static instance: PeerTubeSocket
14
15 private userNotificationSockets: { [ userId: number ]: SocketIO.Socket[] } = {}
16 private liveVideosNamespace: SocketIO.Namespace
17
18 private constructor () {}
19
20 init (server: Server) {
21 const io = SocketIO(server)
22
23 io.of('/user-notifications')
24 .use(authenticateSocket)
25 .on('connection', socket => {
26 const userId = socket.handshake.query.user.id
27
28 logger.debug('User %d connected on the notification system.', userId)
29
30 if (!this.userNotificationSockets[userId]) this.userNotificationSockets[userId] = []
31
32 this.userNotificationSockets[userId].push(socket)
33
34 socket.on('disconnect', () => {
35 logger.debug('User %d disconnected from SocketIO notifications.', userId)
36
37 this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket)
38 })
39 })
40
41 this.liveVideosNamespace = io.of('/live-videos')
42 .on('connection', socket => {
43 socket.on('subscribe', ({ videoId }) => {
44 if (!isIdValid(videoId)) return
45
46 socket.join(videoId)
47 })
48
49 socket.on('unsubscribe', ({ videoId }) => {
50 if (!isIdValid(videoId)) return
51
52 socket.leave(videoId)
53 })
54 })
55 }
56
57 sendNotification (userId: number, notification: UserNotificationModelForApi) {
58 const sockets = this.userNotificationSockets[userId]
59 if (!sockets) return
60
61 logger.debug('Sending user notification to user %d.', userId)
62
63 const notificationMessage = notification.toFormattedJSON()
64 for (const socket of sockets) {
65 socket.emit('new-notification', notificationMessage)
66 }
67 }
68
69 sendVideoLiveNewState (video: MVideo) {
70 const data: LiveVideoEventPayload = { state: video.state }
71 const type: LiveVideoEventType = 'state-change'
72
73 logger.debug('Sending video live new state notification of %s.', video.url)
74
75 this.liveVideosNamespace
76 .in(video.id)
77 .emit(type, data)
78 }
79
80 static get Instance () {
81 return this.instance || (this.instance = new this())
82 }
83 }
84
85 // ---------------------------------------------------------------------------
86
87 export {
88 PeerTubeSocket
89 }