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'
19 import { HooksService } from '@app/core/plugins/hooks.service'
20 import { RedirectService } from '@app/core/routing/redirect.service'
21 import { isXPercentInViewport, scrollToTop } from '@app/helpers'
22 import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
23 import { VideoShareComponent } from '@app/shared/shared-share-modal'
24 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
25 import { VideoActionsDisplayType, VideoDownloadComponent } from '@app/shared/shared-video-miniature'
26 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
27 import { MetaService } from '@ngx-meta/core'
28 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
29 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
30 import { ServerConfig, ServerErrorCode, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
31 import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
34 P2PMediaLoaderOptions,
35 PeertubePlayerManager,
36 PeertubePlayerManagerOptions,
39 } from '../../../assets/player/peertube-player-manager'
40 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
41 import { environment } from '../../../environments/environment'
42 import { VideoSupportComponent } from './modal/video-support.component'
43 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
45 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
48 selector: 'my-video-watch',
49 templateUrl: './video-watch.component.html',
50 styleUrls: [ './video-watch.component.scss' ]
52 export class VideoWatchComponent implements OnInit, OnDestroy {
53 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
55 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
56 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
57 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
58 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
59 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
62 playerElement: HTMLVideoElement
63 theaterEnabled = false
64 userRating: UserVideoRateType = null
65 descriptionLoading = false
67 video: VideoDetails = null
68 videoCaptions: VideoCaption[] = []
70 playlistPosition: number
71 playlist: VideoPlaylist = null
73 completeDescriptionShown = false
74 completeVideoDescription: string
75 shortVideoDescription: string
76 videoHTMLDescription = ''
77 likesBarTooltipText = ''
78 hasAlreadyAcceptedPrivacyConcern = false
79 remoteServerDown = false
80 hotkeys: Hotkey[] = []
85 tooltipSaveToPlaylist = ''
87 videoActionsOptions: VideoActionsDisplayType = {
99 private nextVideoUuid = ''
100 private nextVideoTitle = ''
101 private currentTime: number
102 private paramsSub: Subscription
103 private queryParamsSub: Subscription
104 private configSub: Subscription
105 private liveVideosSub: Subscription
107 private serverConfig: ServerConfig
110 private elementRef: ElementRef,
111 private changeDetector: ChangeDetectorRef,
112 private route: ActivatedRoute,
113 private router: Router,
114 private videoService: VideoService,
115 private playlistService: VideoPlaylistService,
116 private confirmService: ConfirmService,
117 private metaService: MetaService,
118 private authService: AuthService,
119 private userService: UserService,
120 private serverService: ServerService,
121 private restExtractor: RestExtractor,
122 private notifier: Notifier,
123 private markdownService: MarkdownService,
124 private zone: NgZone,
125 private redirectService: RedirectService,
126 private videoCaptionService: VideoCaptionService,
127 private hotkeysService: HotkeysService,
128 private hooks: HooksService,
129 private peertubeSocket: PeerTubeSocket,
130 private screenService: ScreenService,
131 private location: PlatformLocation,
132 @Inject(LOCALE_ID) private localeId: string
136 return this.authService.getUser()
139 get anonymousUser () {
140 return this.userService.getAnonymousUser()
144 // Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
145 if (this.user || !this.screenService.isInMobileView()) {
146 this.tooltipLike = $localize`Like this video`
147 this.tooltipDislike = $localize`Dislike this video`
148 this.tooltipSupport = $localize`Support options for this video`
149 this.tooltipSaveToPlaylist = $localize`Save to playlist`
152 PeertubePlayerManager.initState()
154 this.serverConfig = this.serverService.getTmpConfig()
156 this.configSub = this.serverService.getConfig()
157 .subscribe(config => {
158 this.serverConfig = config
161 isWebRTCDisabled() ||
162 this.serverConfig.tracker.enabled === false ||
163 getStoredP2PEnabled() === false ||
164 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
166 this.hasAlreadyAcceptedPrivacyConcern = true
170 this.paramsSub = this.route.params.subscribe(routeParams => {
171 const videoId = routeParams[ 'videoId' ]
172 if (videoId) this.loadVideo(videoId)
174 const playlistId = routeParams[ 'playlistId' ]
175 if (playlistId) this.loadPlaylist(playlistId)
178 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
179 this.playlistPosition = queryParams[ 'playlistPosition' ]
180 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
182 const start = queryParams[ 'start' ]
183 if (this.player && start) this.player.currentTime(parseInt(start, 10))
188 this.theaterEnabled = getStoredTheater()
190 this.hooks.runAction('action:video-watch.init', 'video-watch')
196 // Unsubscribe subscriptions
197 if (this.paramsSub) this.paramsSub.unsubscribe()
198 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
199 if (this.configSub) this.configSub.unsubscribe()
200 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
203 this.hotkeysService.remove(this.hotkeys)
207 if (this.isUserLoggedIn() === false) return
209 // Already liked this video
210 if (this.userRating === 'like') this.setRating('none')
211 else this.setRating('like')
215 if (this.isUserLoggedIn() === false) return
217 // Already disliked this video
218 if (this.userRating === 'dislike') this.setRating('none')
219 else this.setRating('dislike')
222 getRatePopoverText () {
223 if (this.isUserLoggedIn()) return undefined
225 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
228 showMoreDescription () {
229 if (this.completeVideoDescription === undefined) {
230 return this.loadCompleteDescription()
233 this.updateVideoDescription(this.completeVideoDescription)
234 this.completeDescriptionShown = true
237 showLessDescription () {
238 this.updateVideoDescription(this.shortVideoDescription)
239 this.completeDescriptionShown = false
242 showDownloadModal () {
243 this.videoDownloadModal.show(this.video, this.videoCaptions)
246 isVideoDownloadable () {
247 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
250 loadCompleteDescription () {
251 this.descriptionLoading = true
253 this.videoService.loadCompleteDescription(this.video.descriptionPath)
256 this.completeDescriptionShown = true
257 this.descriptionLoading = false
259 this.shortVideoDescription = this.video.description
260 this.completeVideoDescription = description
262 this.updateVideoDescription(this.completeVideoDescription)
266 this.descriptionLoading = false
267 this.notifier.error(error.message)
272 showSupportModal () {
273 // Check video was playing before opening support modal
274 const isVideoPlaying = this.isPlaying()
278 const modalRef = this.videoSupportModal.show()
280 modalRef.result.then(() => {
281 if (isVideoPlaying) {
290 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
294 return this.authService.isLoggedIn()
298 if (!this.video || Array.isArray(this.video.tags) === false) return []
300 return this.video.tags
303 onRecommendations (videos: Video[]) {
304 if (videos.length > 0) {
305 // The recommended videos's first element should be the next video
306 const video = videos[0]
307 this.nextVideoUuid = video.uuid
308 this.nextVideoTitle = video.name
317 this.redirectService.redirectToHomepage()
320 declinedPrivacyConcern () {
321 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
322 this.hasAlreadyAcceptedPrivacyConcern = false
325 acceptedPrivacyConcern () {
326 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
327 this.hasAlreadyAcceptedPrivacyConcern = true
330 isVideoToTranscode () {
331 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
335 return this.video && this.video.state.id === VideoState.TO_IMPORT
338 hasVideoScheduledPublication () {
339 return this.video && this.video.scheduledUpdate !== undefined
343 return !!(this.video?.isLive)
346 isWaitingForLive () {
347 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
351 return this.video?.state.id === VideoState.LIVE_ENDED
354 isVideoBlur (video: Video) {
355 return video.isVideoNSFWForUser(this.user, this.serverConfig)
358 isAutoPlayEnabled () {
360 (this.user && this.user.autoPlayNextVideo) ||
361 this.anonymousUser.autoPlayNextVideo
365 handleTimestampClicked (timestamp: number) {
366 if (!this.player || this.video.isLive) return
368 this.player.currentTime(timestamp)
372 isPlaylistAutoPlayEnabled () {
374 (this.user && this.user.autoPlayNextVideoPlaylist) ||
375 this.anonymousUser.autoPlayNextVideoPlaylist
379 isChannelDisplayNameGeneric () {
380 const genericChannelDisplayName = [
381 `Main ${this.video.channel.ownerAccount.name} channel`,
382 `Default ${this.video.channel.ownerAccount.name} channel`
385 return genericChannelDisplayName.includes(this.video.channel.displayName)
388 onPlaylistVideoFound (videoId: string) {
389 this.loadVideo(videoId)
392 private loadVideo (videoId: string) {
393 // Video did not change
394 if (this.video && this.video.uuid === videoId) return
396 if (this.player) this.player.pause()
398 const videoObs = this.hooks.wrapObsFun(
399 this.videoService.getVideo.bind(this.videoService),
402 'filter:api.video-watch.video.get.params',
403 'filter:api.video-watch.video.get.result'
409 this.videoCaptionService.listCaptions(videoId)
412 // If 400, 403 or 404, the video is private or blocked so redirect to 404
414 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
415 const search = window.location.search
416 let originUrl = err.body.originUrl
417 if (search) originUrl += search
419 this.confirmService.confirm(
420 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
421 $localize`Redirection`
424 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
425 HttpStatusCode.BAD_REQUEST_400,
426 HttpStatusCode.FORBIDDEN_403,
427 HttpStatusCode.NOT_FOUND_404
431 return window.location.href = originUrl
435 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
436 HttpStatusCode.BAD_REQUEST_400,
437 HttpStatusCode.FORBIDDEN_403,
438 HttpStatusCode.NOT_FOUND_404
442 .subscribe(([ video, captionsResult ]) => {
443 const queryParams = this.route.snapshot.queryParams
446 resume: queryParams.resume,
448 startTime: queryParams.start,
449 stopTime: queryParams.stop,
451 muted: queryParams.muted,
452 loop: queryParams.loop,
453 subtitle: queryParams.subtitle,
455 playerMode: queryParams.mode,
459 this.onVideoFetched(video, captionsResult.data, urlOptions)
460 .catch(err => this.handleError(err))
464 private loadPlaylist (playlistId: string) {
465 // Playlist did not change
466 if (this.playlist && this.playlist.uuid === playlistId) return
468 this.playlistService.getVideoPlaylist(playlistId)
470 // If 400 or 403, the video is private or blocked so redirect to 404
471 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
472 HttpStatusCode.BAD_REQUEST_400,
473 HttpStatusCode.FORBIDDEN_403,
474 HttpStatusCode.NOT_FOUND_404
477 .subscribe(playlist => {
478 this.playlist = playlist
480 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
484 private updateVideoDescription (description: string) {
485 this.video.description = description
486 this.setVideoDescriptionHTML()
487 .catch(err => console.error(err))
490 private async setVideoDescriptionHTML () {
491 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
492 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
495 private setVideoLikesBarTooltipText () {
496 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
499 private handleError (err: any) {
500 const errorMessage: string = typeof err === 'string' ? err : err.message
501 if (!errorMessage) return
503 // Display a message in the video player instead of a notification
504 if (errorMessage.indexOf('from xs param') !== -1) {
506 this.remoteServerDown = true
507 this.changeDetector.detectChanges()
512 this.notifier.error(errorMessage)
515 private checkUserRating () {
516 // Unlogged users do not have ratings
517 if (this.isUserLoggedIn() === false) return
519 this.videoService.getUserVideoRating(this.video.id)
523 this.userRating = ratingObject.rating
527 err => this.notifier.error(err.message)
531 private async onVideoFetched (
533 videoCaptions: VideoCaption[],
534 urlOptions: URLOptions
536 this.subscribeToLiveEventsIfNeeded(this.video, video)
539 this.videoCaptions = videoCaptions
541 // Re init attributes
542 this.descriptionLoading = false
543 this.completeDescriptionShown = false
544 this.completeVideoDescription = undefined
545 this.remoteServerDown = false
546 this.currentTime = undefined
548 if (this.isVideoBlur(this.video)) {
549 const res = await this.confirmService.confirm(
550 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
551 $localize`Mature or explicit content`
553 if (res === false) return this.location.back()
556 this.buildPlayer(urlOptions)
557 .catch(err => console.error('Cannot build the player', err))
559 this.setVideoDescriptionHTML()
560 this.setVideoLikesBarTooltipText()
562 this.setOpenGraphTags()
563 this.checkUserRating()
565 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
568 private async buildPlayer (urlOptions: URLOptions) {
569 const videoState = this.video.state.id
570 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) return
572 // Flush old player if needed
575 // Build video element, because videojs removes it on dispose
576 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
577 this.playerElement = document.createElement('video')
578 this.playerElement.className = 'video-js vjs-peertube-skin'
579 this.playerElement.setAttribute('playsinline', 'true')
580 playerElementWrapper.appendChild(this.playerElement)
584 videoCaptions: this.videoCaptions,
588 const { playerMode, playerOptions } = await this.hooks.wrapFun(
589 this.buildPlayerManagerOptions.bind(this),
592 'filter:internal.video-watch.player.build-options.params',
593 'filter:internal.video-watch.player.build-options.result'
596 this.zone.runOutsideAngular(async () => {
597 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
599 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
601 this.player.on('timeupdate', () => {
602 this.currentTime = Math.floor(this.player.currentTime())
606 * replaces this.player.one('ended')
607 * 'condition()': true to make the upnext functionality trigger,
608 * false to disable the upnext functionality
609 * go to the next video in 'condition()' if you don't want of the timer.
610 * 'next': function triggered at the end of the timer.
611 * 'suspended': function used at each clic of the timer checking if we need
612 * to reset progress and wait until 'suspended' becomes truthy again.
615 timeout: 10000, // 10s
616 headText: $localize`Up Next`,
617 cancelText: $localize`Cancel`,
618 suspendedText: $localize`Autoplay is suspended`,
619 getTitle: () => this.nextVideoTitle,
620 next: () => this.zone.run(() => this.autoplayNext()),
623 if (this.isPlaylistAutoPlayEnabled()) {
624 // upnext will not trigger, and instead the next video will play immediately
625 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
627 } else if (this.isAutoPlayEnabled()) {
628 return true // upnext will trigger
630 return false // upnext will not trigger, and instead leave the video stopping
634 !isXPercentInViewport(this.player.el(), 80) ||
635 !document.getElementById('content').contains(document.activeElement)
640 this.player.one('stopped', () => {
642 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
646 this.player.one('ended', () => {
647 if (this.video.isLive) {
648 this.video.state.id = VideoState.LIVE_ENDED
652 this.player.on('theaterChange', (_: any, enabled: boolean) => {
653 this.zone.run(() => this.theaterEnabled = enabled)
656 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
660 private autoplayNext () {
662 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
663 } else if (this.nextVideoUuid) {
664 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
668 private setRating (nextRating: UserVideoRateType) {
669 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
670 like: this.videoService.setVideoLike,
671 dislike: this.videoService.setVideoDislike,
672 none: this.videoService.unsetVideoLike
675 ratingMethods[nextRating].call(this.videoService, this.video.id)
678 // Update the video like attribute
679 this.updateVideoRating(this.userRating, nextRating)
680 this.userRating = nextRating
683 (err: { message: string }) => this.notifier.error(err.message)
687 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
688 let likesToIncrement = 0
689 let dislikesToIncrement = 0
692 if (oldRating === 'like') likesToIncrement--
693 if (oldRating === 'dislike') dislikesToIncrement--
696 if (newRating === 'like') likesToIncrement++
697 if (newRating === 'dislike') dislikesToIncrement++
699 this.video.likes += likesToIncrement
700 this.video.dislikes += dislikesToIncrement
702 this.video.buildLikeAndDislikePercents()
703 this.setVideoLikesBarTooltipText()
706 private setOpenGraphTags () {
707 this.metaService.setTitle(this.video.name)
709 this.metaService.setTag('og:type', 'video')
711 this.metaService.setTag('og:title', this.video.name)
712 this.metaService.setTag('name', this.video.name)
714 this.metaService.setTag('og:description', this.video.description)
715 this.metaService.setTag('description', this.video.description)
717 this.metaService.setTag('og:image', this.video.previewPath)
719 this.metaService.setTag('og:duration', this.video.duration.toString())
721 this.metaService.setTag('og:site_name', 'PeerTube')
723 this.metaService.setTag('og:url', window.location.href)
724 this.metaService.setTag('url', window.location.href)
727 private isAutoplay () {
728 // We'll jump to the thread id, so do not play the video
729 if (this.route.snapshot.params['threadId']) return false
731 // Otherwise true by default
732 if (!this.user) return true
734 // Be sure the autoPlay is set to false
735 return this.user.autoPlayVideo !== false
738 private flushPlayer () {
739 // Remove player if it exists
742 this.player.dispose()
743 this.player = undefined
745 console.error('Cannot dispose player.', err)
750 private buildPlayerManagerOptions (params: {
752 videoCaptions: VideoCaption[],
753 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
756 const { video, videoCaptions, urlOptions, user } = params
757 const getStartTime = () => {
758 const byUrl = urlOptions.startTime !== undefined
759 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
761 if (byUrl) return timeToInt(urlOptions.startTime)
762 if (byHistory) return video.userHistory.currentTime
767 let startTime = getStartTime()
769 // If we are at the end of the video, reset the timer
770 if (video.duration - startTime <= 1) startTime = 0
772 const playerCaptions = videoCaptions.map(c => ({
773 label: c.language.label,
774 language: c.language.id,
775 src: environment.apiUrl + c.captionPath
778 const options: PeertubePlayerManagerOptions = {
780 autoplay: this.isAutoplay(),
781 nextVideo: () => this.zone.run(() => this.autoplayNext()),
783 playerElement: this.playerElement,
784 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
786 videoDuration: video.duration,
788 inactivityTimeout: 2500,
789 poster: video.previewUrl,
792 stopTime: urlOptions.stopTime,
793 controls: urlOptions.controls,
794 muted: urlOptions.muted,
795 loop: urlOptions.loop,
796 subtitle: urlOptions.subtitle,
798 peertubeLink: urlOptions.peertubeLink,
801 captions: videoCaptions.length !== 0,
803 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
804 ? this.videoService.getVideoViewUrl(video.uuid)
806 embedUrl: video.embedUrl,
808 isLive: video.isLive,
810 language: this.localeId,
812 userWatching: user && user.videosHistoryEnabled === true ? {
813 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
814 authorizationHeader: this.authService.getRequestHeaderValue()
817 serverUrl: environment.apiUrl,
819 videoCaptions: playerCaptions
823 videoFiles: video.files
829 if (urlOptions.playerMode) {
830 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
831 else mode = 'webtorrent'
833 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
834 else mode = 'webtorrent'
837 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
838 if (typeof TextEncoder === 'undefined') {
842 if (mode === 'p2p-media-loader') {
843 const hlsPlaylist = video.getHlsPlaylist()
845 const p2pMediaLoader = {
846 playlistUrl: hlsPlaylist.playlistUrl,
847 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
848 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
849 trackerAnnounce: video.trackerUrls,
850 videoFiles: hlsPlaylist.files
851 } as P2PMediaLoaderOptions
853 Object.assign(options, { p2pMediaLoader })
856 return { playerMode: mode, playerOptions: options }
859 private pausePlayer () {
860 if (!this.player) return
865 private resumePlayer () {
866 if (!this.player) return
871 private isPlaying () {
872 if (!this.player) return
874 return !this.player.paused()
877 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
878 if (!this.liveVideosSub) {
879 this.liveVideosSub = this.buildLiveEventsSubscription()
882 if (oldVideo && oldVideo.id !== newVideo.id) {
883 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
886 if (!newVideo.isLive) return
888 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
891 private buildLiveEventsSubscription () {
892 return this.peertubeSocket.getLiveVideosObservable()
893 .subscribe(({ type, payload }) => {
894 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
895 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
899 private handleLiveStateChange (newState: VideoState) {
900 if (newState !== VideoState.PUBLISHED) return
902 const videoState = this.video.state.id
903 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
905 console.log('Loading video after live update.')
907 const videoUUID = this.video.uuid
909 // Reset to refetch the video
910 this.video = undefined
911 this.loadVideo(videoUUID)
914 private handleLiveViewsChange (newViews: number) {
916 console.error('Cannot update video live views because video is no defined.')
920 console.log('Updating live views.')
922 this.video.views = newViews
925 private initHotkeys () {
927 // These hotkeys are managed by the player
928 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
929 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
930 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
932 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)`),
934 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
935 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
937 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
938 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
940 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
941 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
943 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
946 if (this.isUserLoggedIn()) {
947 this.hotkeys = this.hotkeys.concat([
948 new Hotkey('shift+l', () => {
951 }, undefined, $localize`Like the video`),
953 new Hotkey('shift+d', () => {
956 }, undefined, $localize`Dislike the video`),
958 new Hotkey('shift+s', () => {
959 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
961 }, undefined, $localize`Subscribe to the account`)
965 this.hotkeysService.add(this.hotkeys)