peertube-socket.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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'
  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. this.userNotificationSockets[userId] = socket
  18. socket.on('disconnect', () => {
  19. logger.debug('User %d disconnected from SocketIO notifications.', userId)
  20. delete this.userNotificationSockets[userId]
  21. })
  22. })
  23. }
  24. sendNotification (userId: number, notification: UserNotificationModel) {
  25. const socket = this.userNotificationSockets[userId]
  26. if (!socket) return
  27. socket.emit('new-notification', notification.toFormattedJSON())
  28. }
  29. static get Instance () {
  30. return this.instance || (this.instance = new this())
  31. }
  32. }
  33. // ---------------------------------------------------------------------------
  34. export {
  35. PeerTubeSocket
  36. }