1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, Observable, Subscription } from 'rxjs'
3 import { catchError } from 'rxjs/operators'
4 import { PlatformLocation } from '@angular/common'
5 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
6 import { ActivatedRoute, Router } from '@angular/router'
18 import { HooksService } from '@app/core/plugins/hooks.service'
19 import { RedirectService } from '@app/core/routing/redirect.service'
20 import { isXPercentInViewport, scrollToTop } from '@app/helpers'
21 import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
22 import { VideoShareComponent } from '@app/shared/shared-share-modal'
23 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
24 import { VideoActionsDisplayType, VideoDownloadComponent } from '@app/shared/shared-video-miniature'
25 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
26 import { MetaService } from '@ngx-meta/core'
27 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
28 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
29 import { ServerConfig, ServerErrorCode, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
30 import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
33 P2PMediaLoaderOptions,
34 PeertubePlayerManager,
35 PeertubePlayerManagerOptions,
38 } from '../../../assets/player/peertube-player-manager'
39 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
40 import { environment } from '../../../environments/environment'
41 import { VideoSupportComponent } from './modal/video-support.component'
42 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
44 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
47 selector: 'my-video-watch',
48 templateUrl: './video-watch.component.html',
49 styleUrls: [ './video-watch.component.scss' ]
51 export class VideoWatchComponent implements OnInit, OnDestroy {
52 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
54 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
55 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
56 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
57 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
58 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
61 playerElement: HTMLVideoElement
62 theaterEnabled = false
63 userRating: UserVideoRateType = null
64 descriptionLoading = false
66 video: VideoDetails = null
67 videoCaptions: VideoCaption[] = []
69 playlistPosition: number
70 playlist: VideoPlaylist = null
72 completeDescriptionShown = false
73 completeVideoDescription: string
74 shortVideoDescription: string
75 videoHTMLDescription = ''
76 likesBarTooltipText = ''
77 hasAlreadyAcceptedPrivacyConcern = false
78 remoteServerDown = false
79 hotkeys: Hotkey[] = []
84 tooltipSaveToPlaylist = ''
86 videoActionsOptions: VideoActionsDisplayType = {
98 private nextVideoUuid = ''
99 private nextVideoTitle = ''
100 private currentTime: number
101 private paramsSub: Subscription
102 private queryParamsSub: Subscription
103 private configSub: Subscription
104 private liveVideosSub: Subscription
106 private serverConfig: ServerConfig
109 private elementRef: ElementRef,
110 private changeDetector: ChangeDetectorRef,
111 private route: ActivatedRoute,
112 private router: Router,
113 private videoService: VideoService,
114 private playlistService: VideoPlaylistService,
115 private confirmService: ConfirmService,
116 private metaService: MetaService,
117 private authService: AuthService,
118 private userService: UserService,
119 private serverService: ServerService,
120 private restExtractor: RestExtractor,
121 private notifier: Notifier,
122 private markdownService: MarkdownService,
123 private zone: NgZone,
124 private redirectService: RedirectService,
125 private videoCaptionService: VideoCaptionService,
126 private hotkeysService: HotkeysService,
127 private hooks: HooksService,
128 private peertubeSocket: PeerTubeSocket,
129 private location: PlatformLocation,
130 @Inject(LOCALE_ID) private localeId: string
132 this.tooltipLike = $localize`Like this video`
133 this.tooltipDislike = $localize`Dislike this video`
134 this.tooltipSupport = $localize`Support options for this video`
135 this.tooltipSaveToPlaylist = $localize`Save to playlist`
139 return this.authService.getUser()
142 get anonymousUser () {
143 return this.userService.getAnonymousUser()
147 PeertubePlayerManager.initState()
149 this.serverConfig = this.serverService.getTmpConfig()
151 this.configSub = this.serverService.getConfig()
152 .subscribe(config => {
153 this.serverConfig = config
156 isWebRTCDisabled() ||
157 this.serverConfig.tracker.enabled === false ||
158 getStoredP2PEnabled() === false ||
159 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
161 this.hasAlreadyAcceptedPrivacyConcern = true
165 this.paramsSub = this.route.params.subscribe(routeParams => {
166 const videoId = routeParams[ 'videoId' ]
167 if (videoId) this.loadVideo(videoId)
169 const playlistId = routeParams[ 'playlistId' ]
170 if (playlistId) this.loadPlaylist(playlistId)
173 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
174 this.playlistPosition = queryParams[ 'playlistPosition' ]
175 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
177 const start = queryParams[ 'start' ]
178 if (this.player && start) this.player.currentTime(parseInt(start, 10))
183 this.theaterEnabled = getStoredTheater()
185 this.hooks.runAction('action:video-watch.init', 'video-watch')
191 // Unsubscribe subscriptions
192 if (this.paramsSub) this.paramsSub.unsubscribe()
193 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
194 if (this.configSub) this.configSub.unsubscribe()
195 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
198 this.hotkeysService.remove(this.hotkeys)
202 if (this.isUserLoggedIn() === false) return
204 // Already liked this video
205 if (this.userRating === 'like') this.setRating('none')
206 else this.setRating('like')
210 if (this.isUserLoggedIn() === false) return
212 // Already disliked this video
213 if (this.userRating === 'dislike') this.setRating('none')
214 else this.setRating('dislike')
217 getRatePopoverText () {
218 if (this.isUserLoggedIn()) return undefined
220 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
223 showMoreDescription () {
224 if (this.completeVideoDescription === undefined) {
225 return this.loadCompleteDescription()
228 this.updateVideoDescription(this.completeVideoDescription)
229 this.completeDescriptionShown = true
232 showLessDescription () {
233 this.updateVideoDescription(this.shortVideoDescription)
234 this.completeDescriptionShown = false
237 showDownloadModal () {
238 this.videoDownloadModal.show(this.video, this.videoCaptions)
241 isVideoDownloadable () {
242 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
245 loadCompleteDescription () {
246 this.descriptionLoading = true
248 this.videoService.loadCompleteDescription(this.video.descriptionPath)
251 this.completeDescriptionShown = true
252 this.descriptionLoading = false
254 this.shortVideoDescription = this.video.description
255 this.completeVideoDescription = description
257 this.updateVideoDescription(this.completeVideoDescription)
261 this.descriptionLoading = false
262 this.notifier.error(error.message)
267 showSupportModal () {
268 // Check video was playing before opening support modal
269 const isVideoPlaying = this.isPlaying()
273 const modalRef = this.videoSupportModal.show()
275 modalRef.result.then(() => {
276 if (isVideoPlaying) {
285 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
289 return this.authService.isLoggedIn()
293 if (!this.video || Array.isArray(this.video.tags) === false) return []
295 return this.video.tags
298 onRecommendations (videos: Video[]) {
299 if (videos.length > 0) {
300 // The recommended videos's first element should be the next video
301 const video = videos[0]
302 this.nextVideoUuid = video.uuid
303 this.nextVideoTitle = video.name
312 this.redirectService.redirectToHomepage()
315 declinedPrivacyConcern () {
316 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
317 this.hasAlreadyAcceptedPrivacyConcern = false
320 acceptedPrivacyConcern () {
321 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
322 this.hasAlreadyAcceptedPrivacyConcern = true
325 isVideoToTranscode () {
326 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
330 return this.video && this.video.state.id === VideoState.TO_IMPORT
333 hasVideoScheduledPublication () {
334 return this.video && this.video.scheduledUpdate !== undefined
338 return !!(this.video?.isLive)
341 isWaitingForLive () {
342 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
346 return this.video?.state.id === VideoState.LIVE_ENDED
349 isVideoBlur (video: Video) {
350 return video.isVideoNSFWForUser(this.user, this.serverConfig)
353 isAutoPlayEnabled () {
355 (this.user && this.user.autoPlayNextVideo) ||
356 this.anonymousUser.autoPlayNextVideo
360 handleTimestampClicked (timestamp: number) {
361 if (!this.player || this.video.isLive) return
363 this.player.currentTime(timestamp)
367 isPlaylistAutoPlayEnabled () {
369 (this.user && this.user.autoPlayNextVideoPlaylist) ||
370 this.anonymousUser.autoPlayNextVideoPlaylist
374 isChannelDisplayNameGeneric () {
375 const genericChannelDisplayName = [
376 `Main ${this.video.channel.ownerAccount.name} channel`,
377 `Default ${this.video.channel.ownerAccount.name} channel`
380 return genericChannelDisplayName.includes(this.video.channel.displayName)
383 onPlaylistVideoFound (videoId: string) {
384 this.loadVideo(videoId)
387 private loadVideo (videoId: string) {
388 // Video did not change
389 if (this.video && this.video.uuid === videoId) return
391 if (this.player) this.player.pause()
393 const videoObs = this.hooks.wrapObsFun(
394 this.videoService.getVideo.bind(this.videoService),
397 'filter:api.video-watch.video.get.params',
398 'filter:api.video-watch.video.get.result'
404 this.videoCaptionService.listCaptions(videoId)
407 // If 400, 403 or 404, the video is private or blocked so redirect to 404
409 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
410 const search = window.location.search
411 let originUrl = err.body.originUrl
412 if (search) originUrl += search
414 this.confirmService.confirm(
415 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
416 $localize`Redirection`
419 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
420 HttpStatusCode.BAD_REQUEST_400,
421 HttpStatusCode.FORBIDDEN_403,
422 HttpStatusCode.NOT_FOUND_404
426 return window.location.href = originUrl
430 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
431 HttpStatusCode.BAD_REQUEST_400,
432 HttpStatusCode.FORBIDDEN_403,
433 HttpStatusCode.NOT_FOUND_404
437 .subscribe(([ video, captionsResult ]) => {
438 const queryParams = this.route.snapshot.queryParams
441 resume: queryParams.resume,
443 startTime: queryParams.start,
444 stopTime: queryParams.stop,
446 muted: queryParams.muted,
447 loop: queryParams.loop,
448 subtitle: queryParams.subtitle,
450 playerMode: queryParams.mode,
454 this.onVideoFetched(video, captionsResult.data, urlOptions)
455 .catch(err => this.handleError(err))
459 private loadPlaylist (playlistId: string) {
460 // Playlist did not change
461 if (this.playlist && this.playlist.uuid === playlistId) return
463 this.playlistService.getVideoPlaylist(playlistId)
465 // If 400 or 403, the video is private or blocked so redirect to 404
466 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
467 HttpStatusCode.BAD_REQUEST_400,
468 HttpStatusCode.FORBIDDEN_403,
469 HttpStatusCode.NOT_FOUND_404
472 .subscribe(playlist => {
473 this.playlist = playlist
475 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
479 private updateVideoDescription (description: string) {
480 this.video.description = description
481 this.setVideoDescriptionHTML()
482 .catch(err => console.error(err))
485 private async setVideoDescriptionHTML () {
486 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
487 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
490 private setVideoLikesBarTooltipText () {
491 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
494 private handleError (err: any) {
495 const errorMessage: string = typeof err === 'string' ? err : err.message
496 if (!errorMessage) return
498 // Display a message in the video player instead of a notification
499 if (errorMessage.indexOf('from xs param') !== -1) {
501 this.remoteServerDown = true
502 this.changeDetector.detectChanges()
507 this.notifier.error(errorMessage)
510 private checkUserRating () {
511 // Unlogged users do not have ratings
512 if (this.isUserLoggedIn() === false) return
514 this.videoService.getUserVideoRating(this.video.id)
518 this.userRating = ratingObject.rating
522 err => this.notifier.error(err.message)
526 private async onVideoFetched (
528 videoCaptions: VideoCaption[],
529 urlOptions: URLOptions
531 this.subscribeToLiveEventsIfNeeded(this.video, video)
534 this.videoCaptions = videoCaptions
536 // Re init attributes
537 this.descriptionLoading = false
538 this.completeDescriptionShown = false
539 this.remoteServerDown = false
540 this.currentTime = undefined
542 if (this.isVideoBlur(this.video)) {
543 const res = await this.confirmService.confirm(
544 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
545 $localize`Mature or explicit content`
547 if (res === false) return this.location.back()
550 const videoState = this.video.state.id
551 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) return
553 // Flush old player if needed
556 // Build video element, because videojs removes it on dispose
557 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
558 this.playerElement = document.createElement('video')
559 this.playerElement.className = 'video-js vjs-peertube-skin'
560 this.playerElement.setAttribute('playsinline', 'true')
561 playerElementWrapper.appendChild(this.playerElement)
569 const { playerMode, playerOptions } = await this.hooks.wrapFun(
570 this.buildPlayerManagerOptions.bind(this),
573 'filter:internal.video-watch.player.build-options.params',
574 'filter:internal.video-watch.player.build-options.result'
577 this.zone.runOutsideAngular(async () => {
578 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
580 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
582 this.player.on('timeupdate', () => {
583 this.currentTime = Math.floor(this.player.currentTime())
587 * replaces this.player.one('ended')
588 * 'condition()': true to make the upnext functionality trigger,
589 * false to disable the upnext functionality
590 * go to the next video in 'condition()' if you don't want of the timer.
591 * 'next': function triggered at the end of the timer.
592 * 'suspended': function used at each clic of the timer checking if we need
593 * to reset progress and wait until 'suspended' becomes truthy again.
596 timeout: 10000, // 10s
597 headText: $localize`Up Next`,
598 cancelText: $localize`Cancel`,
599 suspendedText: $localize`Autoplay is suspended`,
600 getTitle: () => this.nextVideoTitle,
601 next: () => this.zone.run(() => this.autoplayNext()),
604 if (this.isPlaylistAutoPlayEnabled()) {
605 // upnext will not trigger, and instead the next video will play immediately
606 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
608 } else if (this.isAutoPlayEnabled()) {
609 return true // upnext will trigger
611 return false // upnext will not trigger, and instead leave the video stopping
615 !isXPercentInViewport(this.player.el(), 80) ||
616 !document.getElementById('content').contains(document.activeElement)
621 this.player.one('stopped', () => {
623 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
627 this.player.one('ended', () => {
628 if (this.video.isLive) {
629 this.video.state.id = VideoState.LIVE_ENDED
633 this.player.on('theaterChange', (_: any, enabled: boolean) => {
634 this.zone.run(() => this.theaterEnabled = enabled)
637 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
640 this.setVideoDescriptionHTML()
641 this.setVideoLikesBarTooltipText()
643 this.setOpenGraphTags()
644 this.checkUserRating()
646 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
649 private autoplayNext () {
651 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
652 } else if (this.nextVideoUuid) {
653 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
657 private setRating (nextRating: UserVideoRateType) {
658 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
659 like: this.videoService.setVideoLike,
660 dislike: this.videoService.setVideoDislike,
661 none: this.videoService.unsetVideoLike
664 ratingMethods[nextRating].call(this.videoService, this.video.id)
667 // Update the video like attribute
668 this.updateVideoRating(this.userRating, nextRating)
669 this.userRating = nextRating
672 (err: { message: string }) => this.notifier.error(err.message)
676 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
677 let likesToIncrement = 0
678 let dislikesToIncrement = 0
681 if (oldRating === 'like') likesToIncrement--
682 if (oldRating === 'dislike') dislikesToIncrement--
685 if (newRating === 'like') likesToIncrement++
686 if (newRating === 'dislike') dislikesToIncrement++
688 this.video.likes += likesToIncrement
689 this.video.dislikes += dislikesToIncrement
691 this.video.buildLikeAndDislikePercents()
692 this.setVideoLikesBarTooltipText()
695 private setOpenGraphTags () {
696 this.metaService.setTitle(this.video.name)
698 this.metaService.setTag('og:type', 'video')
700 this.metaService.setTag('og:title', this.video.name)
701 this.metaService.setTag('name', this.video.name)
703 this.metaService.setTag('og:description', this.video.description)
704 this.metaService.setTag('description', this.video.description)
706 this.metaService.setTag('og:image', this.video.previewPath)
708 this.metaService.setTag('og:duration', this.video.duration.toString())
710 this.metaService.setTag('og:site_name', 'PeerTube')
712 this.metaService.setTag('og:url', window.location.href)
713 this.metaService.setTag('url', window.location.href)
716 private isAutoplay () {
717 // We'll jump to the thread id, so do not play the video
718 if (this.route.snapshot.params['threadId']) return false
720 // Otherwise true by default
721 if (!this.user) return true
723 // Be sure the autoPlay is set to false
724 return this.user.autoPlayVideo !== false
727 private flushPlayer () {
728 // Remove player if it exists
731 this.player.dispose()
732 this.player = undefined
734 console.error('Cannot dispose player.', err)
739 private buildPlayerManagerOptions (params: {
741 videoCaptions: VideoCaption[],
742 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
745 const { video, videoCaptions, urlOptions, user } = params
746 const getStartTime = () => {
747 const byUrl = urlOptions.startTime !== undefined
748 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
750 if (byUrl) return timeToInt(urlOptions.startTime)
751 if (byHistory) return video.userHistory.currentTime
756 let startTime = getStartTime()
758 // If we are at the end of the video, reset the timer
759 if (video.duration - startTime <= 1) startTime = 0
761 const playerCaptions = videoCaptions.map(c => ({
762 label: c.language.label,
763 language: c.language.id,
764 src: environment.apiUrl + c.captionPath
767 const options: PeertubePlayerManagerOptions = {
769 autoplay: this.isAutoplay(),
770 nextVideo: () => this.zone.run(() => this.autoplayNext()),
772 playerElement: this.playerElement,
773 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
775 videoDuration: video.duration,
777 inactivityTimeout: 2500,
778 poster: video.previewUrl,
781 stopTime: urlOptions.stopTime,
782 controls: urlOptions.controls,
783 muted: urlOptions.muted,
784 loop: urlOptions.loop,
785 subtitle: urlOptions.subtitle,
787 peertubeLink: urlOptions.peertubeLink,
790 captions: videoCaptions.length !== 0,
792 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
793 ? this.videoService.getVideoViewUrl(video.uuid)
795 embedUrl: video.embedUrl,
797 isLive: video.isLive,
799 language: this.localeId,
801 userWatching: user && user.videosHistoryEnabled === true ? {
802 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
803 authorizationHeader: this.authService.getRequestHeaderValue()
806 serverUrl: environment.apiUrl,
808 videoCaptions: playerCaptions
812 videoFiles: video.files
818 if (urlOptions.playerMode) {
819 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
820 else mode = 'webtorrent'
822 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
823 else mode = 'webtorrent'
826 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
827 if (typeof TextEncoder === 'undefined') {
831 if (mode === 'p2p-media-loader') {
832 const hlsPlaylist = video.getHlsPlaylist()
834 const p2pMediaLoader = {
835 playlistUrl: hlsPlaylist.playlistUrl,
836 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
837 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
838 trackerAnnounce: video.trackerUrls,
839 videoFiles: hlsPlaylist.files
840 } as P2PMediaLoaderOptions
842 Object.assign(options, { p2pMediaLoader })
845 return { playerMode: mode, playerOptions: options }
848 private pausePlayer () {
849 if (!this.player) return
854 private resumePlayer () {
855 if (!this.player) return
860 private isPlaying () {
861 if (!this.player) return
863 return !this.player.paused()
866 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
867 if (!this.liveVideosSub) {
868 this.liveVideosSub = this.buildLiveEventsSubscription()
871 if (oldVideo && oldVideo.id !== newVideo.id) {
872 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
875 if (!newVideo.isLive) return
877 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
880 private buildLiveEventsSubscription () {
881 return this.peertubeSocket.getLiveVideosObservable()
882 .subscribe(({ type, payload }) => {
883 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
884 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
888 private handleLiveStateChange (newState: VideoState) {
889 if (newState !== VideoState.PUBLISHED) return
891 const videoState = this.video.state.id
892 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
894 console.log('Loading video after live update.')
896 const videoUUID = this.video.uuid
898 // Reset to refetch the video
899 this.video = undefined
900 this.loadVideo(videoUUID)
903 private handleLiveViewsChange (newViews: number) {
905 console.error('Cannot update video live views because video is no defined.')
909 console.log('Updating live views.')
911 this.video.views = newViews
914 private initHotkeys () {
916 // These hotkeys are managed by the player
917 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
918 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
919 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
921 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90% (requires player focus)`),
923 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
924 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
926 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
927 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
929 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
930 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
932 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
935 if (this.isUserLoggedIn()) {
936 this.hotkeys = this.hotkeys.concat([
937 new Hotkey('shift+l', () => {
940 }, undefined, $localize`Like the video`),
942 new Hotkey('shift+d', () => {
945 }, undefined, $localize`Dislike the video`),
947 new Hotkey('shift+s', () => {
948 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
950 }, undefined, $localize`Subscribe to the account`)
954 this.hotkeysService.add(this.hotkeys)