1 import { Subject } from 'rxjs'
2 import { Injectable, NgZone } from '@angular/core'
3 import { LiveVideoEventPayload, LiveVideoEventType, UserNotification as UserNotificationServer } from '@shared/models'
4 import { environment } from '../../../environments/environment'
5 import { AuthService } from '../auth'
6 import { io, Socket } from 'socket.io-client'
8 export type NotificationEvent = 'new' | 'read' | 'read-all'
11 export class PeerTubeSocket {
14 private notificationSubject = new Subject<{ type: NotificationEvent, notification?: UserNotificationServer }>()
15 private liveVideosSubject = new Subject<{ type: LiveVideoEventType, payload: LiveVideoEventPayload }>()
17 private notificationSocket: Socket
18 private liveVideosSocket: Socket
21 private auth: AuthService,
22 private ngZone: NgZone
25 async getMyNotificationsSocket () {
26 await this.initNotificationSocket()
28 return this.notificationSubject.asObservable()
31 getLiveVideosObservable () {
32 return this.liveVideosSubject.asObservable()
35 async subscribeToLiveVideosSocket (videoId: number) {
36 await this.initLiveVideosSocket()
38 this.liveVideosSocket.emit('subscribe', { videoId })
41 unsubscribeLiveVideos (videoId: number) {
42 if (!this.liveVideosSocket) return
44 this.liveVideosSocket.emit('unsubscribe', { videoId })
47 dispatchNotificationEvent (type: NotificationEvent, notification?: UserNotificationServer) {
48 this.notificationSubject.next({ type, notification })
51 private async initNotificationSocket () {
52 if (this.notificationSocket) return
54 await this.importIOIfNeeded()
56 // Prevent protractor issues https://github.com/angular/angular/issues/11853
57 this.ngZone.runOutsideAngular(() => {
58 this.notificationSocket = this.io(environment.apiUrl + '/user-notifications', {
59 query: { accessToken: this.auth.getAccessToken() }
63 this.notificationSocket.on('new-notification', (n: UserNotificationServer) => {
64 this.ngZone.run(() => this.dispatchNotificationEvent('new', n))
68 private async initLiveVideosSocket () {
69 if (this.liveVideosSocket) return
71 await this.importIOIfNeeded()
73 // Prevent protractor issues https://github.com/angular/angular/issues/11853
74 this.ngZone.runOutsideAngular(() => {
75 this.liveVideosSocket = this.io(environment.apiUrl + '/live-videos')
78 const types: LiveVideoEventType[] = [ 'views-change', 'state-change' ]
80 for (const type of types) {
81 this.liveVideosSocket.on(type, (payload: LiveVideoEventPayload) => {
82 this.ngZone.run(() => this.dispatchLiveVideoEvent(type, payload))
87 private async importIOIfNeeded () {
90 this.io = (await import('socket.io-client')).io
93 private dispatchLiveVideoEvent (type: LiveVideoEventType, payload: LiveVideoEventPayload) {
94 this.liveVideosSubject.next({ type, payload })