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
64 theaterEnabled = false
66 userRating: UserVideoRateType = null
68 playerPlaceholderImgSrc: string
70 video: VideoDetails = null
71 videoCaptions: VideoCaption[] = []
73 playlistPosition: number
74 playlist: VideoPlaylist = null
76 descriptionLoading = false
77 completeDescriptionShown = false
78 completeVideoDescription: string
79 shortVideoDescription: string
80 videoHTMLDescription = ''
82 likesBarTooltipText = ''
84 hasAlreadyAcceptedPrivacyConcern = false
85 remoteServerDown = false
87 hotkeys: Hotkey[] = []
92 tooltipSaveToPlaylist = ''
94 videoActionsOptions: VideoActionsDisplayType = {
106 private nextVideoUuid = ''
107 private nextVideoTitle = ''
108 private currentTime: number
109 private paramsSub: Subscription
110 private queryParamsSub: Subscription
111 private configSub: Subscription
112 private liveVideosSub: Subscription
114 private serverConfig: ServerConfig
117 private elementRef: ElementRef,
118 private changeDetector: ChangeDetectorRef,
119 private route: ActivatedRoute,
120 private router: Router,
121 private videoService: VideoService,
122 private playlistService: VideoPlaylistService,
123 private confirmService: ConfirmService,
124 private metaService: MetaService,
125 private authService: AuthService,
126 private userService: UserService,
127 private serverService: ServerService,
128 private restExtractor: RestExtractor,
129 private notifier: Notifier,
130 private markdownService: MarkdownService,
131 private zone: NgZone,
132 private redirectService: RedirectService,
133 private videoCaptionService: VideoCaptionService,
134 private hotkeysService: HotkeysService,
135 private hooks: HooksService,
136 private peertubeSocket: PeerTubeSocket,
137 private screenService: ScreenService,
138 private location: PlatformLocation,
139 @Inject(LOCALE_ID) private localeId: string
143 return this.authService.getUser()
146 get anonymousUser () {
147 return this.userService.getAnonymousUser()
151 // Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
152 if (this.user || !this.screenService.isInMobileView()) {
153 this.tooltipLike = $localize`Like this video`
154 this.tooltipDislike = $localize`Dislike this video`
155 this.tooltipSupport = $localize`Support options for this video`
156 this.tooltipSaveToPlaylist = $localize`Save to playlist`
159 PeertubePlayerManager.initState()
161 this.serverConfig = this.serverService.getTmpConfig()
163 this.configSub = this.serverService.getConfig()
164 .subscribe(config => {
165 this.serverConfig = config
168 isWebRTCDisabled() ||
169 this.serverConfig.tracker.enabled === false ||
170 getStoredP2PEnabled() === false ||
171 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
173 this.hasAlreadyAcceptedPrivacyConcern = true
177 this.paramsSub = this.route.params.subscribe(routeParams => {
178 const videoId = routeParams[ 'videoId' ]
179 if (videoId) this.loadVideo(videoId)
181 const playlistId = routeParams[ 'playlistId' ]
182 if (playlistId) this.loadPlaylist(playlistId)
185 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
186 this.playlistPosition = queryParams[ 'playlistPosition' ]
187 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
189 const start = queryParams[ 'start' ]
190 if (this.player && start) this.player.currentTime(parseInt(start, 10))
195 this.theaterEnabled = getStoredTheater()
197 this.hooks.runAction('action:video-watch.init', 'video-watch')
203 // Unsubscribe subscriptions
204 if (this.paramsSub) this.paramsSub.unsubscribe()
205 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
206 if (this.configSub) this.configSub.unsubscribe()
207 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
210 this.hotkeysService.remove(this.hotkeys)
214 if (this.isUserLoggedIn() === false) return
216 // Already liked this video
217 if (this.userRating === 'like') this.setRating('none')
218 else this.setRating('like')
222 if (this.isUserLoggedIn() === false) return
224 // Already disliked this video
225 if (this.userRating === 'dislike') this.setRating('none')
226 else this.setRating('dislike')
229 getRatePopoverText () {
230 if (this.isUserLoggedIn()) return undefined
232 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
235 showMoreDescription () {
236 if (this.completeVideoDescription === undefined) {
237 return this.loadCompleteDescription()
240 this.updateVideoDescription(this.completeVideoDescription)
241 this.completeDescriptionShown = true
244 showLessDescription () {
245 this.updateVideoDescription(this.shortVideoDescription)
246 this.completeDescriptionShown = false
249 showDownloadModal () {
250 this.videoDownloadModal.show(this.video, this.videoCaptions)
253 isVideoDownloadable () {
254 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
257 loadCompleteDescription () {
258 this.descriptionLoading = true
260 this.videoService.loadCompleteDescription(this.video.descriptionPath)
263 this.completeDescriptionShown = true
264 this.descriptionLoading = false
266 this.shortVideoDescription = this.video.description
267 this.completeVideoDescription = description
269 this.updateVideoDescription(this.completeVideoDescription)
273 this.descriptionLoading = false
274 this.notifier.error(error.message)
279 showSupportModal () {
280 // Check video was playing before opening support modal
281 const isVideoPlaying = this.isPlaying()
285 const modalRef = this.videoSupportModal.show()
287 modalRef.result.then(() => {
288 if (isVideoPlaying) {
297 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
301 return this.authService.isLoggedIn()
305 if (!this.video || Array.isArray(this.video.tags) === false) return []
307 return this.video.tags
310 onRecommendations (videos: Video[]) {
311 if (videos.length > 0) {
312 // The recommended videos's first element should be the next video
313 const video = videos[0]
314 this.nextVideoUuid = video.uuid
315 this.nextVideoTitle = video.name
324 this.redirectService.redirectToHomepage()
327 declinedPrivacyConcern () {
328 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
329 this.hasAlreadyAcceptedPrivacyConcern = false
332 acceptedPrivacyConcern () {
333 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
334 this.hasAlreadyAcceptedPrivacyConcern = true
337 isVideoToTranscode () {
338 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
342 return this.video && this.video.state.id === VideoState.TO_IMPORT
345 hasVideoScheduledPublication () {
346 return this.video && this.video.scheduledUpdate !== undefined
350 return !!(this.video?.isLive)
353 isWaitingForLive () {
354 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
358 return this.video?.state.id === VideoState.LIVE_ENDED
361 isVideoBlur (video: Video) {
362 return video.isVideoNSFWForUser(this.user, this.serverConfig)
365 isAutoPlayEnabled () {
367 (this.user && this.user.autoPlayNextVideo) ||
368 this.anonymousUser.autoPlayNextVideo
372 handleTimestampClicked (timestamp: number) {
373 if (!this.player || this.video.isLive) return
375 this.player.currentTime(timestamp)
379 isPlaylistAutoPlayEnabled () {
381 (this.user && this.user.autoPlayNextVideoPlaylist) ||
382 this.anonymousUser.autoPlayNextVideoPlaylist
386 isChannelDisplayNameGeneric () {
387 const genericChannelDisplayName = [
388 `Main ${this.video.channel.ownerAccount.name} channel`,
389 `Default ${this.video.channel.ownerAccount.name} channel`
392 return genericChannelDisplayName.includes(this.video.channel.displayName)
395 onPlaylistVideoFound (videoId: string) {
396 this.loadVideo(videoId)
399 private loadVideo (videoId: string) {
400 // Video did not change
401 if (this.video && this.video.uuid === videoId) return
403 if (this.player) this.player.pause()
405 const videoObs = this.hooks.wrapObsFun(
406 this.videoService.getVideo.bind(this.videoService),
409 'filter:api.video-watch.video.get.params',
410 'filter:api.video-watch.video.get.result'
416 this.videoCaptionService.listCaptions(videoId)
419 // If 400, 403 or 404, the video is private or blocked so redirect to 404
421 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
422 const search = window.location.search
423 let originUrl = err.body.originUrl
424 if (search) originUrl += search
426 this.confirmService.confirm(
427 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
428 $localize`Redirection`
431 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
432 HttpStatusCode.BAD_REQUEST_400,
433 HttpStatusCode.FORBIDDEN_403,
434 HttpStatusCode.NOT_FOUND_404
438 return window.location.href = originUrl
442 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
443 HttpStatusCode.BAD_REQUEST_400,
444 HttpStatusCode.FORBIDDEN_403,
445 HttpStatusCode.NOT_FOUND_404
449 .subscribe(([ video, captionsResult ]) => {
450 const queryParams = this.route.snapshot.queryParams
453 resume: queryParams.resume,
455 startTime: queryParams.start,
456 stopTime: queryParams.stop,
458 muted: queryParams.muted,
459 loop: queryParams.loop,
460 subtitle: queryParams.subtitle,
462 playerMode: queryParams.mode,
466 this.onVideoFetched(video, captionsResult.data, urlOptions)
467 .catch(err => this.handleError(err))
471 private loadPlaylist (playlistId: string) {
472 // Playlist did not change
473 if (this.playlist && this.playlist.uuid === playlistId) return
475 this.playlistService.getVideoPlaylist(playlistId)
477 // If 400 or 403, the video is private or blocked so redirect to 404
478 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
479 HttpStatusCode.BAD_REQUEST_400,
480 HttpStatusCode.FORBIDDEN_403,
481 HttpStatusCode.NOT_FOUND_404
484 .subscribe(playlist => {
485 this.playlist = playlist
487 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
491 private updateVideoDescription (description: string) {
492 this.video.description = description
493 this.setVideoDescriptionHTML()
494 .catch(err => console.error(err))
497 private async setVideoDescriptionHTML () {
498 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
499 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
502 private setVideoLikesBarTooltipText () {
503 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
506 private handleError (err: any) {
507 const errorMessage: string = typeof err === 'string' ? err : err.message
508 if (!errorMessage) return
510 // Display a message in the video player instead of a notification
511 if (errorMessage.indexOf('from xs param') !== -1) {
513 this.remoteServerDown = true
514 this.changeDetector.detectChanges()
519 this.notifier.error(errorMessage)
522 private checkUserRating () {
523 // Unlogged users do not have ratings
524 if (this.isUserLoggedIn() === false) return
526 this.videoService.getUserVideoRating(this.video.id)
530 this.userRating = ratingObject.rating
534 err => this.notifier.error(err.message)
538 private async onVideoFetched (
540 videoCaptions: VideoCaption[],
541 urlOptions: URLOptions
543 this.subscribeToLiveEventsIfNeeded(this.video, video)
546 this.videoCaptions = videoCaptions
548 // Re init attributes
549 this.playerPlaceholderImgSrc = undefined
550 this.descriptionLoading = false
551 this.completeDescriptionShown = false
552 this.completeVideoDescription = undefined
553 this.remoteServerDown = false
554 this.currentTime = undefined
556 if (this.isVideoBlur(this.video)) {
557 const res = await this.confirmService.confirm(
558 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
559 $localize`Mature or explicit content`
561 if (res === false) return this.location.back()
564 this.buildPlayer(urlOptions)
565 .catch(err => console.error('Cannot build the player', err))
567 this.setVideoDescriptionHTML()
568 this.setVideoLikesBarTooltipText()
570 this.setOpenGraphTags()
571 this.checkUserRating()
573 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
576 private async buildPlayer (urlOptions: URLOptions) {
577 // Flush old player if needed
580 const videoState = this.video.state.id
581 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
582 this.playerPlaceholderImgSrc = this.video.previewPath
586 // Build video element, because videojs removes it on dispose
587 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
588 this.playerElement = document.createElement('video')
589 this.playerElement.className = 'video-js vjs-peertube-skin'
590 this.playerElement.setAttribute('playsinline', 'true')
591 playerElementWrapper.appendChild(this.playerElement)
595 videoCaptions: this.videoCaptions,
599 const { playerMode, playerOptions } = await this.hooks.wrapFun(
600 this.buildPlayerManagerOptions.bind(this),
603 'filter:internal.video-watch.player.build-options.params',
604 'filter:internal.video-watch.player.build-options.result'
607 this.zone.runOutsideAngular(async () => {
608 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
610 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
612 this.player.on('timeupdate', () => {
613 this.currentTime = Math.floor(this.player.currentTime())
617 * replaces this.player.one('ended')
618 * 'condition()': true to make the upnext functionality trigger,
619 * false to disable the upnext functionality
620 * go to the next video in 'condition()' if you don't want of the timer.
621 * 'next': function triggered at the end of the timer.
622 * 'suspended': function used at each clic of the timer checking if we need
623 * to reset progress and wait until 'suspended' becomes truthy again.
626 timeout: 10000, // 10s
627 headText: $localize`Up Next`,
628 cancelText: $localize`Cancel`,
629 suspendedText: $localize`Autoplay is suspended`,
630 getTitle: () => this.nextVideoTitle,
631 next: () => this.zone.run(() => this.autoplayNext()),
634 if (this.isPlaylistAutoPlayEnabled()) {
635 // upnext will not trigger, and instead the next video will play immediately
636 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
638 } else if (this.isAutoPlayEnabled()) {
639 return true // upnext will trigger
641 return false // upnext will not trigger, and instead leave the video stopping
645 !isXPercentInViewport(this.player.el(), 80) ||
646 !document.getElementById('content').contains(document.activeElement)
651 this.player.one('stopped', () => {
653 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
657 this.player.one('ended', () => {
658 if (this.video.isLive) {
659 this.video.state.id = VideoState.LIVE_ENDED
663 this.player.on('theaterChange', (_: any, enabled: boolean) => {
664 this.zone.run(() => this.theaterEnabled = enabled)
667 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
671 private autoplayNext () {
673 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
674 } else if (this.nextVideoUuid) {
675 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
679 private setRating (nextRating: UserVideoRateType) {
680 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
681 like: this.videoService.setVideoLike,
682 dislike: this.videoService.setVideoDislike,
683 none: this.videoService.unsetVideoLike
686 ratingMethods[nextRating].call(this.videoService, this.video.id)
689 // Update the video like attribute
690 this.updateVideoRating(this.userRating, nextRating)
691 this.userRating = nextRating
694 (err: { message: string }) => this.notifier.error(err.message)
698 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
699 let likesToIncrement = 0
700 let dislikesToIncrement = 0
703 if (oldRating === 'like') likesToIncrement--
704 if (oldRating === 'dislike') dislikesToIncrement--
707 if (newRating === 'like') likesToIncrement++
708 if (newRating === 'dislike') dislikesToIncrement++
710 this.video.likes += likesToIncrement
711 this.video.dislikes += dislikesToIncrement
713 this.video.buildLikeAndDislikePercents()
714 this.setVideoLikesBarTooltipText()
717 private setOpenGraphTags () {
718 this.metaService.setTitle(this.video.name)
720 this.metaService.setTag('og:type', 'video')
722 this.metaService.setTag('og:title', this.video.name)
723 this.metaService.setTag('name', this.video.name)
725 this.metaService.setTag('og:description', this.video.description)
726 this.metaService.setTag('description', this.video.description)
728 this.metaService.setTag('og:image', this.video.previewPath)
730 this.metaService.setTag('og:duration', this.video.duration.toString())
732 this.metaService.setTag('og:site_name', 'PeerTube')
734 this.metaService.setTag('og:url', window.location.href)
735 this.metaService.setTag('url', window.location.href)
738 private isAutoplay () {
739 // We'll jump to the thread id, so do not play the video
740 if (this.route.snapshot.params['threadId']) return false
742 // Otherwise true by default
743 if (!this.user) return true
745 // Be sure the autoPlay is set to false
746 return this.user.autoPlayVideo !== false
749 private flushPlayer () {
750 // Remove player if it exists
753 this.player.dispose()
754 this.player = undefined
756 console.error('Cannot dispose player.', err)
761 private buildPlayerManagerOptions (params: {
763 videoCaptions: VideoCaption[],
764 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
767 const { video, videoCaptions, urlOptions, user } = params
768 const getStartTime = () => {
769 const byUrl = urlOptions.startTime !== undefined
770 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
772 if (byUrl) return timeToInt(urlOptions.startTime)
773 if (byHistory) return video.userHistory.currentTime
778 let startTime = getStartTime()
780 // If we are at the end of the video, reset the timer
781 if (video.duration - startTime <= 1) startTime = 0
783 const playerCaptions = videoCaptions.map(c => ({
784 label: c.language.label,
785 language: c.language.id,
786 src: environment.apiUrl + c.captionPath
789 const options: PeertubePlayerManagerOptions = {
791 autoplay: this.isAutoplay(),
792 nextVideo: () => this.zone.run(() => this.autoplayNext()),
794 playerElement: this.playerElement,
795 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
797 videoDuration: video.duration,
799 inactivityTimeout: 2500,
800 poster: video.previewUrl,
803 stopTime: urlOptions.stopTime,
804 controls: urlOptions.controls,
805 muted: urlOptions.muted,
806 loop: urlOptions.loop,
807 subtitle: urlOptions.subtitle,
809 peertubeLink: urlOptions.peertubeLink,
812 captions: videoCaptions.length !== 0,
814 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
815 ? this.videoService.getVideoViewUrl(video.uuid)
817 embedUrl: video.embedUrl,
818 embedTitle: video.name,
820 isLive: video.isLive,
822 language: this.localeId,
824 userWatching: user && user.videosHistoryEnabled === true ? {
825 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
826 authorizationHeader: this.authService.getRequestHeaderValue()
829 serverUrl: environment.apiUrl,
831 videoCaptions: playerCaptions
835 videoFiles: video.files
841 if (urlOptions.playerMode) {
842 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
843 else mode = 'webtorrent'
845 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
846 else mode = 'webtorrent'
849 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
850 if (typeof TextEncoder === 'undefined') {
854 if (mode === 'p2p-media-loader') {
855 const hlsPlaylist = video.getHlsPlaylist()
857 const p2pMediaLoader = {
858 playlistUrl: hlsPlaylist.playlistUrl,
859 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
860 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
861 trackerAnnounce: video.trackerUrls,
862 videoFiles: hlsPlaylist.files
863 } as P2PMediaLoaderOptions
865 Object.assign(options, { p2pMediaLoader })
868 return { playerMode: mode, playerOptions: options }
871 private pausePlayer () {
872 if (!this.player) return
877 private resumePlayer () {
878 if (!this.player) return
883 private isPlaying () {
884 if (!this.player) return
886 return !this.player.paused()
889 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
890 if (!this.liveVideosSub) {
891 this.liveVideosSub = this.buildLiveEventsSubscription()
894 if (oldVideo && oldVideo.id !== newVideo.id) {
895 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
898 if (!newVideo.isLive) return
900 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
903 private buildLiveEventsSubscription () {
904 return this.peertubeSocket.getLiveVideosObservable()
905 .subscribe(({ type, payload }) => {
906 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
907 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
911 private handleLiveStateChange (newState: VideoState) {
912 if (newState !== VideoState.PUBLISHED) return
914 const videoState = this.video.state.id
915 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
917 console.log('Loading video after live update.')
919 const videoUUID = this.video.uuid
921 // Reset to refetch the video
922 this.video = undefined
923 this.loadVideo(videoUUID)
926 private handleLiveViewsChange (newViews: number) {
928 console.error('Cannot update video live views because video is no defined.')
932 console.log('Updating live views.')
934 this.video.views = newViews
937 private initHotkeys () {
939 // These hotkeys are managed by the player
940 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
941 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
942 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
944 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)`),
946 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
947 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
949 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
950 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
952 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
953 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
955 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
958 if (this.isUserLoggedIn()) {
959 this.hotkeys = this.hotkeys.concat([
960 new Hotkey('shift+l', () => {
963 }, undefined, $localize`Like the video`),
965 new Hotkey('shift+d', () => {
968 }, undefined, $localize`Dislike the video`),
970 new Hotkey('shift+s', () => {
971 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
973 }, undefined, $localize`Subscribe to the account`)
977 this.hotkeysService.add(this.hotkeys)