+ private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
+ if (!this.liveVideosSub) {
+ this.liveVideosSub = this.buildLiveEventsSubscription()
+ }
+
+ if (oldVideo && oldVideo.id !== newVideo.id) {
+ await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
+ }
+
+ if (!newVideo.isLive) return
+
+ await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
+ }
+
+ private buildLiveEventsSubscription () {
+ return this.peertubeSocket.getLiveVideosObservable()
+ .subscribe(({ type, payload }) => {
+ if (type === 'state-change') return this.handleLiveStateChange(payload.state)
+ if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
+ })
+ }
+
+ private handleLiveStateChange (newState: VideoState) {
+ if (newState !== VideoState.PUBLISHED) return
+
+ const videoState = this.video.state.id
+ if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
+
+ console.log('Loading video after live update.')
+
+ const videoUUID = this.video.uuid
+
+ // Reset to refetch the video
+ this.video = undefined
+ this.loadVideo(videoUUID)
+ }
+
+ private handleLiveViewsChange (newViews: number) {
+ if (!this.video) {
+ console.error('Cannot update video live views because video is no defined.')
+ return
+ }
+
+ console.log('Updating live views.')
+
+ this.video.views = newViews
+ }
+