peertube-socket.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import * as SocketIO from 'socket.io'
  2. import { authenticateSocket } from '../middlewares'
  3. import { logger } from '../helpers/logger'
  4. import { Server } from 'http'
  5. import { UserNotificationModelForApi } from '@server/typings/models/user'
  6. class PeerTubeSocket {
  7. private static instance: PeerTubeSocket
  8. private userNotificationSockets: { [ userId: number ]: SocketIO.Socket[] } = {}
  9. private constructor () {}
  10. init (server: Server) {
  11. const io = SocketIO(server)
  12. io.of('/user-notifications')
  13. .use(authenticateSocket)
  14. .on('connection', socket => {
  15. const userId = socket.handshake.query.user.id
  16. logger.debug('User %d connected on the notification system.', userId)
  17. if (!this.userNotificationSockets[userId]) this.userNotificationSockets[userId] = []
  18. this.userNotificationSockets[userId].push(socket)
  19. socket.on('disconnect', () => {
  20. logger.debug('User %d disconnected from SocketIO notifications.', userId)
  21. this.userNotificationSockets[userId] = this.userNotificationSockets[userId].filter(s => s !== socket)
  22. })
  23. })
  24. }
  25. sendNotification (userId: number, notification: UserNotificationModelForApi) {
  26. const sockets = this.userNotificationSockets[userId]
  27. if (!sockets) return
  28. const notificationMessage = notification.toFormattedJSON()
  29. for (const socket of sockets) {
  30. socket.emit('new-notification', notificationMessage)
  31. }
  32. }
  33. static get Instance () {
  34. return this.instance || (this.instance = new this())
  35. }
  36. }
  37. // ---------------------------------------------------------------------------
  38. export {
  39. PeerTubeSocket
  40. }