aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/standalone/videos/shared/live-manager.ts
blob: 5fac229ba88843897a56002e4eb6318915a7e76c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { Socket } from 'socket.io-client'
import { LiveVideoEventPayload, VideoDetails, VideoState } from '../../../../../shared/models'
import { PlayerHTML } from './player-html'
import { Translations } from './translations'

export class LiveManager {
  private liveSocket: Socket

  private listeners = new Map<string, (payload: LiveVideoEventPayload) => void>()

  constructor (
    private readonly playerHTML: PlayerHTML
  ) {

  }

  async listenForChanges (options: {
    video: VideoDetails
    onPublishedVideo: () => any
  }) {
    const { video, onPublishedVideo } = options

    if (!this.liveSocket) {
      const io = (await import('socket.io-client')).io
      this.liveSocket = io(window.location.origin + '/live-videos')
    }

    const listener = (payload: LiveVideoEventPayload) => {
      if (payload.state === VideoState.PUBLISHED) {
        this.playerHTML.removeInformation()
        onPublishedVideo()
        return
      }
    }

    this.liveSocket.on('state-change', listener)
    this.listeners.set(video.uuid, listener)

    this.liveSocket.emit('subscribe', { videoId: video.id })
  }

  stopListeningForChanges (video: VideoDetails) {
    const listener = this.listeners.get(video.uuid)
    if (listener) {
      this.liveSocket.off('state-change', listener)
    }

    this.liveSocket.emit('unsubscribe', { videoId: video.id })
  }

  displayInfo (options: {
    state: VideoState
    translations: Translations
  }) {
    const { state, translations } = options

    if (state === VideoState.WAITING_FOR_LIVE) {
      this.displayWaitingForLiveInfo(translations)
      return
    }

    if (state === VideoState.LIVE_ENDED) {
      this.displayEndedLiveInfo(translations)
      return
    }
  }

  private displayWaitingForLiveInfo (translations: Translations) {
    this.playerHTML.displayInformation('This live has not started yet.', translations)
  }

  private displayEndedLiveInfo (translations: Translations) {
    this.playerHTML.displayInformation('This live has ended.', translations)

  }
}