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 { SupportModalComponent } from '@app/shared/shared-support-modal'
25 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
26 import { VideoActionsDisplayType, VideoDownloadComponent } from '@app/shared/shared-video-miniature'
27 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
28 import { MetaService } from '@ngx-meta/core'
29 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
30 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
31 import { ServerConfig, ServerErrorCode, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
36 getStoredVideoWatchHistory
37 } from '../../../assets/player/peertube-player-local-storage'
40 P2PMediaLoaderOptions,
41 PeertubePlayerManager,
42 PeertubePlayerManagerOptions,
45 } from '../../../assets/player/peertube-player-manager'
46 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
47 import { environment } from '../../../environments/environment'
48 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
50 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
53 selector: 'my-video-watch',
54 templateUrl: './video-watch.component.html',
55 styleUrls: [ './video-watch.component.scss' ]
57 export class VideoWatchComponent implements OnInit, OnDestroy {
58 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
60 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
61 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
62 @ViewChild('supportModal') supportModal: SupportModalComponent
63 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
64 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
67 playerElement: HTMLVideoElement
69 theaterEnabled = false
71 userRating: UserVideoRateType = null
73 playerPlaceholderImgSrc: string
75 video: VideoDetails = null
76 videoCaptions: VideoCaption[] = []
78 playlistPosition: number
79 playlist: VideoPlaylist = null
81 descriptionLoading = false
82 completeDescriptionShown = false
83 completeVideoDescription: string
84 shortVideoDescription: string
85 videoHTMLDescription = ''
87 likesBarTooltipText = ''
89 hasAlreadyAcceptedPrivacyConcern = false
90 remoteServerDown = false
92 hotkeys: Hotkey[] = []
97 tooltipSaveToPlaylist = ''
99 videoActionsOptions: VideoActionsDisplayType = {
111 private nextVideoUuid = ''
112 private nextVideoTitle = ''
113 private currentTime: number
114 private paramsSub: Subscription
115 private queryParamsSub: Subscription
116 private configSub: Subscription
117 private liveVideosSub: Subscription
119 private serverConfig: ServerConfig
122 private elementRef: ElementRef,
123 private changeDetector: ChangeDetectorRef,
124 private route: ActivatedRoute,
125 private router: Router,
126 private videoService: VideoService,
127 private playlistService: VideoPlaylistService,
128 private confirmService: ConfirmService,
129 private metaService: MetaService,
130 private authService: AuthService,
131 private userService: UserService,
132 private serverService: ServerService,
133 private restExtractor: RestExtractor,
134 private notifier: Notifier,
135 private markdownService: MarkdownService,
136 private zone: NgZone,
137 private redirectService: RedirectService,
138 private videoCaptionService: VideoCaptionService,
139 private hotkeysService: HotkeysService,
140 private hooks: HooksService,
141 private peertubeSocket: PeerTubeSocket,
142 private screenService: ScreenService,
143 private location: PlatformLocation,
144 @Inject(LOCALE_ID) private localeId: string
148 return this.authService.getUser()
151 get anonymousUser () {
152 return this.userService.getAnonymousUser()
156 // Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
157 if (this.user || !this.screenService.isInMobileView()) {
158 this.tooltipLike = $localize`Like this video`
159 this.tooltipDislike = $localize`Dislike this video`
160 this.tooltipSupport = $localize`Support options for this video`
161 this.tooltipSaveToPlaylist = $localize`Save to playlist`
164 PeertubePlayerManager.initState()
166 this.serverConfig = this.serverService.getTmpConfig()
168 this.configSub = this.serverService.getConfig()
169 .subscribe(config => {
170 this.serverConfig = config
173 isWebRTCDisabled() ||
174 this.serverConfig.tracker.enabled === false ||
175 getStoredP2PEnabled() === false ||
176 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
178 this.hasAlreadyAcceptedPrivacyConcern = true
182 this.paramsSub = this.route.params.subscribe(routeParams => {
183 const videoId = routeParams[ 'videoId' ]
184 if (videoId) this.loadVideo(videoId)
186 const playlistId = routeParams[ 'playlistId' ]
187 if (playlistId) this.loadPlaylist(playlistId)
190 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
191 // Handle the ?playlistPosition
192 const positionParam = queryParams[ 'playlistPosition' ] ?? 1
194 this.playlistPosition = positionParam === 'last'
195 ? -1 // Handle the "last" index
196 : parseInt(positionParam + '', 10)
198 if (isNaN(this.playlistPosition)) {
199 console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
200 this.playlistPosition = 1
203 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
205 const start = queryParams[ 'start' ]
206 if (this.player && start) this.player.currentTime(parseInt(start, 10))
211 this.theaterEnabled = getStoredTheater()
213 this.hooks.runAction('action:video-watch.init', 'video-watch')
215 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
221 // Unsubscribe subscriptions
222 if (this.paramsSub) this.paramsSub.unsubscribe()
223 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
224 if (this.configSub) this.configSub.unsubscribe()
225 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
228 this.hotkeysService.remove(this.hotkeys)
232 if (this.isUserLoggedIn() === false) return
234 // Already liked this video
235 if (this.userRating === 'like') this.setRating('none')
236 else this.setRating('like')
240 if (this.isUserLoggedIn() === false) return
242 // Already disliked this video
243 if (this.userRating === 'dislike') this.setRating('none')
244 else this.setRating('dislike')
247 getRatePopoverText () {
248 if (this.isUserLoggedIn()) return undefined
250 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
253 showMoreDescription () {
254 if (this.completeVideoDescription === undefined) {
255 return this.loadCompleteDescription()
258 this.updateVideoDescription(this.completeVideoDescription)
259 this.completeDescriptionShown = true
262 showLessDescription () {
263 this.updateVideoDescription(this.shortVideoDescription)
264 this.completeDescriptionShown = false
267 showDownloadModal () {
268 this.videoDownloadModal.show(this.video, this.videoCaptions)
271 isVideoDownloadable () {
272 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
275 loadCompleteDescription () {
276 this.descriptionLoading = true
278 this.videoService.loadCompleteDescription(this.video.descriptionPath)
281 this.completeDescriptionShown = true
282 this.descriptionLoading = false
284 this.shortVideoDescription = this.video.description
285 this.completeVideoDescription = description
287 this.updateVideoDescription(this.completeVideoDescription)
291 this.descriptionLoading = false
292 this.notifier.error(error.message)
297 showSupportModal () {
298 this.supportModal.show()
302 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
306 return this.authService.isLoggedIn()
310 if (!this.video.url) {
311 return this.video.originInstanceUrl + VideoDetails.buildClientUrl(this.video.uuid)
313 return this.video.url
317 if (!this.video || Array.isArray(this.video.tags) === false) return []
319 return this.video.tags
322 onRecommendations (videos: Video[]) {
323 if (videos.length > 0) {
324 // The recommended videos's first element should be the next video
325 const video = videos[0]
326 this.nextVideoUuid = video.uuid
327 this.nextVideoTitle = video.name
332 this.redirectService.redirectToHomepage()
335 declinedPrivacyConcern () {
336 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
337 this.hasAlreadyAcceptedPrivacyConcern = false
340 acceptedPrivacyConcern () {
341 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
342 this.hasAlreadyAcceptedPrivacyConcern = true
345 isVideoToTranscode () {
346 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
350 return this.video && this.video.state.id === VideoState.TO_IMPORT
353 hasVideoScheduledPublication () {
354 return this.video && this.video.scheduledUpdate !== undefined
358 return !!(this.video?.isLive)
361 isWaitingForLive () {
362 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
366 return this.video?.state.id === VideoState.LIVE_ENDED
369 isVideoBlur (video: Video) {
370 return video.isVideoNSFWForUser(this.user, this.serverConfig)
373 isAutoPlayEnabled () {
375 (this.user && this.user.autoPlayNextVideo) ||
376 this.anonymousUser.autoPlayNextVideo
380 handleTimestampClicked (timestamp: number) {
381 if (!this.player || this.video.isLive) return
383 this.player.currentTime(timestamp)
387 isPlaylistAutoPlayEnabled () {
389 (this.user && this.user.autoPlayNextVideoPlaylist) ||
390 this.anonymousUser.autoPlayNextVideoPlaylist
394 isChannelDisplayNameGeneric () {
395 const genericChannelDisplayName = [
396 `Main ${this.video.channel.ownerAccount.name} channel`,
397 `Default ${this.video.channel.ownerAccount.name} channel`
400 return genericChannelDisplayName.includes(this.video.channel.displayName)
403 onPlaylistVideoFound (videoId: string) {
404 this.loadVideo(videoId)
407 displayOtherVideosAsRow () {
408 // Use the same value as in the SASS file
409 return this.screenService.getWindowInnerWidth() <= 1100
412 private loadVideo (videoId: string) {
413 // Video did not change
414 if (this.video && this.video.uuid === videoId) return
416 if (this.player) this.player.pause()
418 const videoObs = this.hooks.wrapObsFun(
419 this.videoService.getVideo.bind(this.videoService),
422 'filter:api.video-watch.video.get.params',
423 'filter:api.video-watch.video.get.result'
429 this.videoCaptionService.listCaptions(videoId)
432 // If 400, 403 or 404, the video is private or blocked so redirect to 404
434 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
435 const search = window.location.search
436 let originUrl = err.body.originUrl
437 if (search) originUrl += search
439 this.confirmService.confirm(
440 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
441 $localize`Redirection`
444 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
445 HttpStatusCode.BAD_REQUEST_400,
446 HttpStatusCode.FORBIDDEN_403,
447 HttpStatusCode.NOT_FOUND_404
451 return window.location.href = originUrl
455 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
456 HttpStatusCode.BAD_REQUEST_400,
457 HttpStatusCode.FORBIDDEN_403,
458 HttpStatusCode.NOT_FOUND_404
462 .subscribe(([ video, captionsResult ]) => {
463 const queryParams = this.route.snapshot.queryParams
466 resume: queryParams.resume,
468 startTime: queryParams.start,
469 stopTime: queryParams.stop,
471 muted: queryParams.muted,
472 loop: queryParams.loop,
473 subtitle: queryParams.subtitle,
475 playerMode: queryParams.mode,
479 this.onVideoFetched(video, captionsResult.data, urlOptions)
480 .catch(err => this.handleError(err))
484 private loadPlaylist (playlistId: string) {
485 // Playlist did not change
486 if (this.playlist && this.playlist.uuid === playlistId) return
488 this.playlistService.getVideoPlaylist(playlistId)
490 // If 400 or 403, the video is private or blocked so redirect to 404
491 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
492 HttpStatusCode.BAD_REQUEST_400,
493 HttpStatusCode.FORBIDDEN_403,
494 HttpStatusCode.NOT_FOUND_404
497 .subscribe(playlist => {
498 this.playlist = playlist
500 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
504 private updateVideoDescription (description: string) {
505 this.video.description = description
506 this.setVideoDescriptionHTML()
507 .catch(err => console.error(err))
510 private async setVideoDescriptionHTML () {
511 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
512 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
515 private setVideoLikesBarTooltipText () {
516 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
519 private handleError (err: any) {
520 const errorMessage: string = typeof err === 'string' ? err : err.message
521 if (!errorMessage) return
523 // Display a message in the video player instead of a notification
524 if (errorMessage.indexOf('from xs param') !== -1) {
526 this.remoteServerDown = true
527 this.changeDetector.detectChanges()
532 this.notifier.error(errorMessage)
535 private checkUserRating () {
536 // Unlogged users do not have ratings
537 if (this.isUserLoggedIn() === false) return
539 this.videoService.getUserVideoRating(this.video.id)
543 this.userRating = ratingObject.rating
547 err => this.notifier.error(err.message)
551 private async onVideoFetched (
553 videoCaptions: VideoCaption[],
554 urlOptions: URLOptions
556 this.subscribeToLiveEventsIfNeeded(this.video, video)
559 this.videoCaptions = videoCaptions
561 // Re init attributes
562 this.playerPlaceholderImgSrc = undefined
563 this.descriptionLoading = false
564 this.completeDescriptionShown = false
565 this.completeVideoDescription = undefined
566 this.remoteServerDown = false
567 this.currentTime = undefined
569 if (this.isVideoBlur(this.video)) {
570 const res = await this.confirmService.confirm(
571 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
572 $localize`Mature or explicit content`
574 if (res === false) return this.location.back()
577 this.buildPlayer(urlOptions)
578 .catch(err => console.error('Cannot build the player', err))
580 this.setVideoDescriptionHTML()
581 this.setVideoLikesBarTooltipText()
583 this.setOpenGraphTags()
584 this.checkUserRating()
586 const hookOptions = {
589 playlist: this.playlist
591 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
594 private async buildPlayer (urlOptions: URLOptions) {
595 // Flush old player if needed
598 const videoState = this.video.state.id
599 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
600 this.playerPlaceholderImgSrc = this.video.previewPath
604 // Build video element, because videojs removes it on dispose
605 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
606 this.playerElement = document.createElement('video')
607 this.playerElement.className = 'video-js vjs-peertube-skin'
608 this.playerElement.setAttribute('playsinline', 'true')
609 playerElementWrapper.appendChild(this.playerElement)
613 videoCaptions: this.videoCaptions,
617 const { playerMode, playerOptions } = await this.hooks.wrapFun(
618 this.buildPlayerManagerOptions.bind(this),
621 'filter:internal.video-watch.player.build-options.params',
622 'filter:internal.video-watch.player.build-options.result'
625 this.zone.runOutsideAngular(async () => {
626 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
628 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
630 this.player.on('timeupdate', () => {
631 this.currentTime = Math.floor(this.player.currentTime())
635 * replaces this.player.one('ended')
636 * 'condition()': true to make the upnext functionality trigger,
637 * false to disable the upnext functionality
638 * go to the next video in 'condition()' if you don't want of the timer.
639 * 'next': function triggered at the end of the timer.
640 * 'suspended': function used at each clic of the timer checking if we need
641 * to reset progress and wait until 'suspended' becomes truthy again.
644 timeout: 10000, // 10s
645 headText: $localize`Up Next`,
646 cancelText: $localize`Cancel`,
647 suspendedText: $localize`Autoplay is suspended`,
648 getTitle: () => this.nextVideoTitle,
649 next: () => this.zone.run(() => this.autoplayNext()),
652 if (this.isPlaylistAutoPlayEnabled()) {
653 // upnext will not trigger, and instead the next video will play immediately
654 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
656 } else if (this.isAutoPlayEnabled()) {
657 return true // upnext will trigger
659 return false // upnext will not trigger, and instead leave the video stopping
663 !isXPercentInViewport(this.player.el(), 80) ||
664 !document.getElementById('content').contains(document.activeElement)
669 this.player.one('stopped', () => {
671 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
675 this.player.one('ended', () => {
676 if (this.video.isLive) {
677 this.video.state.id = VideoState.LIVE_ENDED
681 this.player.on('theaterChange', (_: any, enabled: boolean) => {
682 this.zone.run(() => this.theaterEnabled = enabled)
685 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
689 private autoplayNext () {
691 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
692 } else if (this.nextVideoUuid) {
693 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
697 private setRating (nextRating: UserVideoRateType) {
698 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
699 like: this.videoService.setVideoLike,
700 dislike: this.videoService.setVideoDislike,
701 none: this.videoService.unsetVideoLike
704 ratingMethods[nextRating].call(this.videoService, this.video.id)
707 // Update the video like attribute
708 this.updateVideoRating(this.userRating, nextRating)
709 this.userRating = nextRating
712 (err: { message: string }) => this.notifier.error(err.message)
716 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
717 let likesToIncrement = 0
718 let dislikesToIncrement = 0
721 if (oldRating === 'like') likesToIncrement--
722 if (oldRating === 'dislike') dislikesToIncrement--
725 if (newRating === 'like') likesToIncrement++
726 if (newRating === 'dislike') dislikesToIncrement++
728 this.video.likes += likesToIncrement
729 this.video.dislikes += dislikesToIncrement
731 this.video.buildLikeAndDislikePercents()
732 this.setVideoLikesBarTooltipText()
735 private setOpenGraphTags () {
736 this.metaService.setTitle(this.video.name)
738 this.metaService.setTag('og:type', 'video')
740 this.metaService.setTag('og:title', this.video.name)
741 this.metaService.setTag('name', this.video.name)
743 this.metaService.setTag('og:description', this.video.description)
744 this.metaService.setTag('description', this.video.description)
746 this.metaService.setTag('og:image', this.video.previewPath)
748 this.metaService.setTag('og:duration', this.video.duration.toString())
750 this.metaService.setTag('og:site_name', 'PeerTube')
752 this.metaService.setTag('og:url', window.location.href)
753 this.metaService.setTag('url', window.location.href)
756 private isAutoplay () {
757 // We'll jump to the thread id, so do not play the video
758 if (this.route.snapshot.params['threadId']) return false
760 // Otherwise true by default
761 if (!this.user) return true
763 // Be sure the autoPlay is set to false
764 return this.user.autoPlayVideo !== false
767 private flushPlayer () {
768 // Remove player if it exists
771 this.player.dispose()
772 this.player = undefined
774 console.error('Cannot dispose player.', err)
779 private buildPlayerManagerOptions (params: {
781 videoCaptions: VideoCaption[],
782 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
785 const { video, videoCaptions, urlOptions, user } = params
786 const getStartTime = () => {
787 const byUrl = urlOptions.startTime !== undefined
788 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
789 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
791 if (byUrl) return timeToInt(urlOptions.startTime)
792 if (byHistory) return video.userHistory.currentTime
793 if (byLocalStorage) return byLocalStorage.duration
798 let startTime = getStartTime()
800 // If we are at the end of the video, reset the timer
801 if (video.duration - startTime <= 1) startTime = 0
803 const playerCaptions = videoCaptions.map(c => ({
804 label: c.language.label,
805 language: c.language.id,
806 src: environment.apiUrl + c.captionPath
809 const options: PeertubePlayerManagerOptions = {
811 autoplay: this.isAutoplay(),
812 nextVideo: () => this.zone.run(() => this.autoplayNext()),
814 playerElement: this.playerElement,
815 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
817 videoDuration: video.duration,
819 inactivityTimeout: 2500,
820 poster: video.previewUrl,
823 stopTime: urlOptions.stopTime,
824 controls: urlOptions.controls,
825 muted: urlOptions.muted,
826 loop: urlOptions.loop,
827 subtitle: urlOptions.subtitle,
829 peertubeLink: urlOptions.peertubeLink,
832 captions: videoCaptions.length !== 0,
834 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
835 ? this.videoService.getVideoViewUrl(video.uuid)
837 embedUrl: video.embedUrl,
838 embedTitle: video.name,
840 isLive: video.isLive,
842 language: this.localeId,
844 userWatching: user && user.videosHistoryEnabled === true ? {
845 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
846 authorizationHeader: this.authService.getRequestHeaderValue()
849 serverUrl: environment.apiUrl,
851 videoCaptions: playerCaptions,
853 videoUUID: video.uuid
857 videoFiles: video.files
861 // Only set this if we're in a playlist
863 options.common.previousVideo = () => {
864 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
870 if (urlOptions.playerMode) {
871 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
872 else mode = 'webtorrent'
874 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
875 else mode = 'webtorrent'
878 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
879 if (typeof TextEncoder === 'undefined') {
883 if (mode === 'p2p-media-loader') {
884 const hlsPlaylist = video.getHlsPlaylist()
886 const p2pMediaLoader = {
887 playlistUrl: hlsPlaylist.playlistUrl,
888 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
889 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
890 trackerAnnounce: video.trackerUrls,
891 videoFiles: hlsPlaylist.files
892 } as P2PMediaLoaderOptions
894 Object.assign(options, { p2pMediaLoader })
897 return { playerMode: mode, playerOptions: options }
900 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
901 if (!this.liveVideosSub) {
902 this.liveVideosSub = this.buildLiveEventsSubscription()
905 if (oldVideo && oldVideo.id !== newVideo.id) {
906 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
909 if (!newVideo.isLive) return
911 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
914 private buildLiveEventsSubscription () {
915 return this.peertubeSocket.getLiveVideosObservable()
916 .subscribe(({ type, payload }) => {
917 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
918 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
922 private handleLiveStateChange (newState: VideoState) {
923 if (newState !== VideoState.PUBLISHED) return
925 const videoState = this.video.state.id
926 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
928 console.log('Loading video after live update.')
930 const videoUUID = this.video.uuid
932 // Reset to refetch the video
933 this.video = undefined
934 this.loadVideo(videoUUID)
937 private handleLiveViewsChange (newViews: number) {
939 console.error('Cannot update video live views because video is no defined.')
943 console.log('Updating live views.')
945 this.video.views = newViews
948 private initHotkeys () {
950 // These hotkeys are managed by the player
951 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
952 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
953 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
955 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)`),
957 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
958 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
960 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
961 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
963 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
964 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
966 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
969 if (this.isUserLoggedIn()) {
970 this.hotkeys = this.hotkeys.concat([
971 new Hotkey('shift+l', () => {
974 }, undefined, $localize`Like the video`),
976 new Hotkey('shift+d', () => {
979 }, undefined, $localize`Dislike the video`),
981 new Hotkey('shift+s', () => {
982 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
984 }, undefined, $localize`Subscribe to the account`)
988 this.hotkeysService.add(this.hotkeys)