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'
20 import { HooksService } from '@app/core/plugins/hooks.service'
21 import { RedirectService } from '@app/core/routing/redirect.service'
22 import { isXPercentInViewport, scrollToTop } from '@app/helpers'
23 import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
24 import { VideoShareComponent } from '@app/shared/shared-share-modal'
25 import { SupportModalComponent } from '@app/shared/shared-support-modal'
26 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
27 import { VideoActionsDisplayType, VideoDownloadComponent } from '@app/shared/shared-video-miniature'
28 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
29 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
30 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
33 PeerTubeProblemDocument,
39 } from '@shared/models'
44 getStoredVideoWatchHistory
45 } from '../../../assets/player/peertube-player-local-storage'
48 P2PMediaLoaderOptions,
49 PeertubePlayerManager,
50 PeertubePlayerManagerOptions,
53 } from '../../../assets/player/peertube-player-manager'
54 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
55 import { environment } from '../../../environments/environment'
56 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
58 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
61 selector: 'my-video-watch',
62 templateUrl: './video-watch.component.html',
63 styleUrls: [ './video-watch.component.scss' ]
65 export class VideoWatchComponent implements OnInit, OnDestroy {
66 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
68 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
69 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
70 @ViewChild('supportModal') supportModal: SupportModalComponent
71 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
72 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
75 playerElement: HTMLVideoElement
77 theaterEnabled = false
79 userRating: UserVideoRateType = null
81 playerPlaceholderImgSrc: string
83 video: VideoDetails = null
84 videoCaptions: VideoCaption[] = []
86 playlistPosition: number
87 playlist: VideoPlaylist = null
89 descriptionLoading = false
90 completeDescriptionShown = false
91 completeVideoDescription: string
92 shortVideoDescription: string
93 videoHTMLDescription = ''
95 likesBarTooltipText = ''
97 hasAlreadyAcceptedPrivacyConcern = false
98 remoteServerDown = false
100 hotkeys: Hotkey[] = []
105 tooltipSaveToPlaylist = ''
107 videoActionsOptions: VideoActionsDisplayType = {
119 private nextVideoUuid = ''
120 private nextVideoTitle = ''
121 private currentTime: number
122 private paramsSub: Subscription
123 private queryParamsSub: Subscription
124 private configSub: Subscription
125 private liveVideosSub: Subscription
127 private serverConfig: HTMLServerConfig
130 private elementRef: ElementRef,
131 private changeDetector: ChangeDetectorRef,
132 private route: ActivatedRoute,
133 private router: Router,
134 private videoService: VideoService,
135 private playlistService: VideoPlaylistService,
136 private confirmService: ConfirmService,
137 private metaService: MetaService,
138 private authService: AuthService,
139 private userService: UserService,
140 private serverService: ServerService,
141 private restExtractor: RestExtractor,
142 private notifier: Notifier,
143 private markdownService: MarkdownService,
144 private zone: NgZone,
145 private redirectService: RedirectService,
146 private videoCaptionService: VideoCaptionService,
147 private hotkeysService: HotkeysService,
148 private hooks: HooksService,
149 private peertubeSocket: PeerTubeSocket,
150 private screenService: ScreenService,
151 private location: PlatformLocation,
152 @Inject(LOCALE_ID) private localeId: string
156 return this.authService.getUser()
159 get anonymousUser () {
160 return this.userService.getAnonymousUser()
164 // Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
165 if (this.user || !this.screenService.isInMobileView()) {
166 this.tooltipLike = $localize`Like this video`
167 this.tooltipDislike = $localize`Dislike this video`
168 this.tooltipSupport = $localize`Support options for this video`
169 this.tooltipSaveToPlaylist = $localize`Save to playlist`
172 PeertubePlayerManager.initState()
174 this.serverConfig = this.serverService.getHTMLConfig()
176 isWebRTCDisabled() ||
177 this.serverConfig.tracker.enabled === false ||
178 getStoredP2PEnabled() === false ||
179 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
181 this.hasAlreadyAcceptedPrivacyConcern = true
184 this.paramsSub = this.route.params.subscribe(routeParams => {
185 const videoId = routeParams[ 'videoId' ]
186 if (videoId) this.loadVideo(videoId)
188 const playlistId = routeParams[ 'playlistId' ]
189 if (playlistId) this.loadPlaylist(playlistId)
192 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
193 // Handle the ?playlistPosition
194 const positionParam = queryParams[ 'playlistPosition' ] ?? 1
196 this.playlistPosition = positionParam === 'last'
197 ? -1 // Handle the "last" index
198 : parseInt(positionParam + '', 10)
200 if (isNaN(this.playlistPosition)) {
201 console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
202 this.playlistPosition = 1
205 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
207 const start = queryParams[ 'start' ]
208 if (this.player && start) this.player.currentTime(parseInt(start, 10))
213 this.theaterEnabled = getStoredTheater()
215 this.hooks.runAction('action:video-watch.init', 'video-watch')
217 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
223 // Unsubscribe subscriptions
224 if (this.paramsSub) this.paramsSub.unsubscribe()
225 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
226 if (this.configSub) this.configSub.unsubscribe()
227 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
230 this.hotkeysService.remove(this.hotkeys)
234 if (this.isUserLoggedIn() === false) return
236 // Already liked this video
237 if (this.userRating === 'like') this.setRating('none')
238 else this.setRating('like')
242 if (this.isUserLoggedIn() === false) return
244 // Already disliked this video
245 if (this.userRating === 'dislike') this.setRating('none')
246 else this.setRating('dislike')
249 getRatePopoverText () {
250 if (this.isUserLoggedIn()) return undefined
252 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
255 showMoreDescription () {
256 if (this.completeVideoDescription === undefined) {
257 return this.loadCompleteDescription()
260 this.updateVideoDescription(this.completeVideoDescription)
261 this.completeDescriptionShown = true
264 showLessDescription () {
265 this.updateVideoDescription(this.shortVideoDescription)
266 this.completeDescriptionShown = false
269 showDownloadModal () {
270 this.videoDownloadModal.show(this.video, this.videoCaptions)
273 isVideoDownloadable () {
274 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
277 loadCompleteDescription () {
278 this.descriptionLoading = true
280 this.videoService.loadCompleteDescription(this.video.descriptionPath)
283 this.completeDescriptionShown = true
284 this.descriptionLoading = false
286 this.shortVideoDescription = this.video.description
287 this.completeVideoDescription = description
289 this.updateVideoDescription(this.completeVideoDescription)
293 this.descriptionLoading = false
294 this.notifier.error(error.message)
299 showSupportModal () {
300 this.supportModal.show()
304 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
308 return this.authService.isLoggedIn()
312 if (!this.video.url) {
313 return this.video.originInstanceUrl + VideoDetails.buildClientUrl(this.video.uuid)
315 return this.video.url
319 if (!this.video || Array.isArray(this.video.tags) === false) return []
321 return this.video.tags
324 onRecommendations (videos: Video[]) {
325 if (videos.length > 0) {
326 // The recommended videos's first element should be the next video
327 const video = videos[0]
328 this.nextVideoUuid = video.uuid
329 this.nextVideoTitle = video.name
334 this.redirectService.redirectToHomepage()
337 declinedPrivacyConcern () {
338 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
339 this.hasAlreadyAcceptedPrivacyConcern = false
342 acceptedPrivacyConcern () {
343 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
344 this.hasAlreadyAcceptedPrivacyConcern = true
347 isVideoToTranscode () {
348 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
352 return this.video && this.video.state.id === VideoState.TO_IMPORT
355 hasVideoScheduledPublication () {
356 return this.video && this.video.scheduledUpdate !== undefined
360 return !!(this.video?.isLive)
363 isWaitingForLive () {
364 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
368 return this.video?.state.id === VideoState.LIVE_ENDED
371 isVideoBlur (video: Video) {
372 return video.isVideoNSFWForUser(this.user, this.serverConfig)
375 isAutoPlayEnabled () {
377 (this.user && this.user.autoPlayNextVideo) ||
378 this.anonymousUser.autoPlayNextVideo
382 handleTimestampClicked (timestamp: number) {
383 if (!this.player || this.video.isLive) return
385 this.player.currentTime(timestamp)
389 isPlaylistAutoPlayEnabled () {
391 (this.user && this.user.autoPlayNextVideoPlaylist) ||
392 this.anonymousUser.autoPlayNextVideoPlaylist
396 isChannelDisplayNameGeneric () {
397 const genericChannelDisplayName = [
398 `Main ${this.video.channel.ownerAccount.name} channel`,
399 `Default ${this.video.channel.ownerAccount.name} channel`
402 return genericChannelDisplayName.includes(this.video.channel.displayName)
405 onPlaylistVideoFound (videoId: string) {
406 this.loadVideo(videoId)
409 displayOtherVideosAsRow () {
410 // Use the same value as in the SASS file
411 return this.screenService.getWindowInnerWidth() <= 1100
414 private loadVideo (videoId: string) {
415 // Video did not change
416 if (this.video && this.video.uuid === videoId) return
418 if (this.player) this.player.pause()
420 const videoObs = this.hooks.wrapObsFun(
421 this.videoService.getVideo.bind(this.videoService),
424 'filter:api.video-watch.video.get.params',
425 'filter:api.video-watch.video.get.result'
431 this.videoCaptionService.listCaptions(videoId)
434 // If 400, 403 or 404, the video is private or blocked so redirect to 404
436 const errorBody = err.body as PeerTubeProblemDocument
438 if (errorBody.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
439 const search = window.location.search
440 let originUrl = errorBody.originUrl
441 if (search) originUrl += search
443 this.confirmService.confirm(
444 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
445 $localize`Redirection`
448 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
449 HttpStatusCode.BAD_REQUEST_400,
450 HttpStatusCode.FORBIDDEN_403,
451 HttpStatusCode.NOT_FOUND_404
455 return window.location.href = originUrl
459 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
460 HttpStatusCode.BAD_REQUEST_400,
461 HttpStatusCode.FORBIDDEN_403,
462 HttpStatusCode.NOT_FOUND_404
466 .subscribe(([ video, captionsResult ]) => {
467 const queryParams = this.route.snapshot.queryParams
470 resume: queryParams.resume,
472 startTime: queryParams.start,
473 stopTime: queryParams.stop,
475 muted: queryParams.muted,
476 loop: queryParams.loop,
477 subtitle: queryParams.subtitle,
479 playerMode: queryParams.mode,
483 this.onVideoFetched(video, captionsResult.data, urlOptions)
484 .catch(err => this.handleError(err))
488 private loadPlaylist (playlistId: string) {
489 // Playlist did not change
490 if (this.playlist && this.playlist.uuid === playlistId) return
492 this.playlistService.getVideoPlaylist(playlistId)
494 // If 400 or 403, the video is private or blocked so redirect to 404
495 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
496 HttpStatusCode.BAD_REQUEST_400,
497 HttpStatusCode.FORBIDDEN_403,
498 HttpStatusCode.NOT_FOUND_404
501 .subscribe(playlist => {
502 this.playlist = playlist
504 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
508 private updateVideoDescription (description: string) {
509 this.video.description = description
510 this.setVideoDescriptionHTML()
511 .catch(err => console.error(err))
514 private async setVideoDescriptionHTML () {
515 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
516 this.videoHTMLDescription = this.markdownService.processVideoTimestamps(html)
519 private setVideoLikesBarTooltipText () {
520 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
523 private handleError (err: any) {
524 const errorMessage: string = typeof err === 'string' ? err : err.message
525 if (!errorMessage) return
527 // Display a message in the video player instead of a notification
528 if (errorMessage.indexOf('from xs param') !== -1) {
530 this.remoteServerDown = true
531 this.changeDetector.detectChanges()
536 this.notifier.error(errorMessage)
539 private checkUserRating () {
540 // Unlogged users do not have ratings
541 if (this.isUserLoggedIn() === false) return
543 this.videoService.getUserVideoRating(this.video.id)
547 this.userRating = ratingObject.rating
551 err => this.notifier.error(err.message)
555 private async onVideoFetched (
557 videoCaptions: VideoCaption[],
558 urlOptions: URLOptions
560 this.subscribeToLiveEventsIfNeeded(this.video, video)
563 this.videoCaptions = videoCaptions
565 // Re init attributes
566 this.playerPlaceholderImgSrc = undefined
567 this.descriptionLoading = false
568 this.completeDescriptionShown = false
569 this.completeVideoDescription = undefined
570 this.remoteServerDown = false
571 this.currentTime = undefined
573 if (this.isVideoBlur(this.video)) {
574 const res = await this.confirmService.confirm(
575 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
576 $localize`Mature or explicit content`
578 if (res === false) return this.location.back()
581 this.buildPlayer(urlOptions)
582 .catch(err => console.error('Cannot build the player', err))
584 this.setVideoDescriptionHTML()
585 this.setVideoLikesBarTooltipText()
587 this.setOpenGraphTags()
588 this.checkUserRating()
590 const hookOptions = {
593 playlist: this.playlist
595 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
598 private async buildPlayer (urlOptions: URLOptions) {
599 // Flush old player if needed
602 const videoState = this.video.state.id
603 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
604 this.playerPlaceholderImgSrc = this.video.previewPath
608 // Build video element, because videojs removes it on dispose
609 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
610 this.playerElement = document.createElement('video')
611 this.playerElement.className = 'video-js vjs-peertube-skin'
612 this.playerElement.setAttribute('playsinline', 'true')
613 playerElementWrapper.appendChild(this.playerElement)
617 videoCaptions: this.videoCaptions,
621 const { playerMode, playerOptions } = await this.hooks.wrapFun(
622 this.buildPlayerManagerOptions.bind(this),
625 'filter:internal.video-watch.player.build-options.params',
626 'filter:internal.video-watch.player.build-options.result'
629 this.zone.runOutsideAngular(async () => {
630 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
632 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
634 this.player.on('timeupdate', () => {
635 this.currentTime = Math.floor(this.player.currentTime())
639 * replaces this.player.one('ended')
640 * 'condition()': true to make the upnext functionality trigger,
641 * false to disable the upnext functionality
642 * go to the next video in 'condition()' if you don't want of the timer.
643 * 'next': function triggered at the end of the timer.
644 * 'suspended': function used at each clic of the timer checking if we need
645 * to reset progress and wait until 'suspended' becomes truthy again.
648 timeout: 10000, // 10s
649 headText: $localize`Up Next`,
650 cancelText: $localize`Cancel`,
651 suspendedText: $localize`Autoplay is suspended`,
652 getTitle: () => this.nextVideoTitle,
653 next: () => this.zone.run(() => this.autoplayNext()),
656 if (this.isPlaylistAutoPlayEnabled()) {
657 // upnext will not trigger, and instead the next video will play immediately
658 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
660 } else if (this.isAutoPlayEnabled()) {
661 return true // upnext will trigger
663 return false // upnext will not trigger, and instead leave the video stopping
667 !isXPercentInViewport(this.player.el(), 80) ||
668 !document.getElementById('content').contains(document.activeElement)
673 this.player.one('stopped', () => {
675 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
679 this.player.one('ended', () => {
680 if (this.video.isLive) {
681 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
685 this.player.on('theaterChange', (_: any, enabled: boolean) => {
686 this.zone.run(() => this.theaterEnabled = enabled)
689 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
693 private autoplayNext () {
695 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
696 } else if (this.nextVideoUuid) {
697 this.router.navigate([ '/w', this.nextVideoUuid ])
701 private setRating (nextRating: UserVideoRateType) {
702 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
703 like: this.videoService.setVideoLike,
704 dislike: this.videoService.setVideoDislike,
705 none: this.videoService.unsetVideoLike
708 ratingMethods[nextRating].call(this.videoService, this.video.id)
711 // Update the video like attribute
712 this.updateVideoRating(this.userRating, nextRating)
713 this.userRating = nextRating
716 (err: { message: string }) => this.notifier.error(err.message)
720 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
721 let likesToIncrement = 0
722 let dislikesToIncrement = 0
725 if (oldRating === 'like') likesToIncrement--
726 if (oldRating === 'dislike') dislikesToIncrement--
729 if (newRating === 'like') likesToIncrement++
730 if (newRating === 'dislike') dislikesToIncrement++
732 this.video.likes += likesToIncrement
733 this.video.dislikes += dislikesToIncrement
735 this.video.buildLikeAndDislikePercents()
736 this.setVideoLikesBarTooltipText()
739 private setOpenGraphTags () {
740 this.metaService.setTitle(this.video.name)
742 this.metaService.setTag('og:type', 'video')
744 this.metaService.setTag('og:title', this.video.name)
745 this.metaService.setTag('name', this.video.name)
747 this.metaService.setTag('og:description', this.video.description)
748 this.metaService.setTag('description', this.video.description)
750 this.metaService.setTag('og:image', this.video.previewPath)
752 this.metaService.setTag('og:duration', this.video.duration.toString())
754 this.metaService.setTag('og:site_name', 'PeerTube')
756 this.metaService.setTag('og:url', window.location.href)
757 this.metaService.setTag('url', window.location.href)
760 private isAutoplay () {
761 // We'll jump to the thread id, so do not play the video
762 if (this.route.snapshot.params['threadId']) return false
764 // Otherwise true by default
765 if (!this.user) return true
767 // Be sure the autoPlay is set to false
768 return this.user.autoPlayVideo !== false
771 private flushPlayer () {
772 // Remove player if it exists
775 this.player.dispose()
776 this.player = undefined
778 console.error('Cannot dispose player.', err)
783 private buildPlayerManagerOptions (params: {
785 videoCaptions: VideoCaption[],
786 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
789 const { video, videoCaptions, urlOptions, user } = params
790 const getStartTime = () => {
791 const byUrl = urlOptions.startTime !== undefined
792 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
793 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
795 if (byUrl) return timeToInt(urlOptions.startTime)
796 if (byHistory) return video.userHistory.currentTime
797 if (byLocalStorage) return byLocalStorage.duration
802 let startTime = getStartTime()
804 // If we are at the end of the video, reset the timer
805 if (video.duration - startTime <= 1) startTime = 0
807 const playerCaptions = videoCaptions.map(c => ({
808 label: c.language.label,
809 language: c.language.id,
810 src: environment.apiUrl + c.captionPath
813 const options: PeertubePlayerManagerOptions = {
815 autoplay: this.isAutoplay(),
816 nextVideo: () => this.zone.run(() => this.autoplayNext()),
818 playerElement: this.playerElement,
819 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
821 videoDuration: video.duration,
823 inactivityTimeout: 2500,
824 poster: video.previewUrl,
827 stopTime: urlOptions.stopTime,
828 controls: urlOptions.controls,
829 muted: urlOptions.muted,
830 loop: urlOptions.loop,
831 subtitle: urlOptions.subtitle,
833 peertubeLink: urlOptions.peertubeLink,
836 captions: videoCaptions.length !== 0,
838 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
839 ? this.videoService.getVideoViewUrl(video.uuid)
841 embedUrl: video.embedUrl,
842 embedTitle: video.name,
844 isLive: video.isLive,
846 language: this.localeId,
848 userWatching: user && user.videosHistoryEnabled === true ? {
849 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
850 authorizationHeader: this.authService.getRequestHeaderValue()
853 serverUrl: environment.apiUrl,
855 videoCaptions: playerCaptions,
857 videoUUID: video.uuid
861 videoFiles: video.files
865 // Only set this if we're in a playlist
867 options.common.previousVideo = () => {
868 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
874 if (urlOptions.playerMode) {
875 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
876 else mode = 'webtorrent'
878 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
879 else mode = 'webtorrent'
882 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
883 if (typeof TextEncoder === 'undefined') {
887 if (mode === 'p2p-media-loader') {
888 const hlsPlaylist = video.getHlsPlaylist()
890 const p2pMediaLoader = {
891 playlistUrl: hlsPlaylist.playlistUrl,
892 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
893 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
894 trackerAnnounce: video.trackerUrls,
895 videoFiles: hlsPlaylist.files
896 } as P2PMediaLoaderOptions
898 Object.assign(options, { p2pMediaLoader })
901 return { playerMode: mode, playerOptions: options }
904 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
905 if (!this.liveVideosSub) {
906 this.liveVideosSub = this.buildLiveEventsSubscription()
909 if (oldVideo && oldVideo.id !== newVideo.id) {
910 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
913 if (!newVideo.isLive) return
915 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
918 private buildLiveEventsSubscription () {
919 return this.peertubeSocket.getLiveVideosObservable()
920 .subscribe(({ type, payload }) => {
921 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
922 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
926 private handleLiveStateChange (newState: VideoState) {
927 if (newState !== VideoState.PUBLISHED) return
929 const videoState = this.video.state.id
930 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
932 console.log('Loading video after live update.')
934 const videoUUID = this.video.uuid
936 // Reset to refetch the video
937 this.video = undefined
938 this.loadVideo(videoUUID)
941 private handleLiveViewsChange (newViews: number) {
943 console.error('Cannot update video live views because video is no defined.')
947 console.log('Updating live views.')
949 this.video.views = newViews
952 private initHotkeys () {
954 // These hotkeys are managed by the player
955 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
956 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
957 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
959 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)`),
961 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
962 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
964 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
965 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
967 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
968 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
970 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
973 if (this.isUserLoggedIn()) {
974 this.hotkeys = this.hotkeys.concat([
975 new Hotkey('shift+l', () => {
978 }, undefined, $localize`Like the video`),
980 new Hotkey('shift+d', () => {
983 }, undefined, $localize`Dislike the video`),
985 new Hotkey('shift+s', () => {
986 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
988 }, undefined, $localize`Subscribe to the account`)
992 this.hotkeysService.add(this.hotkeys)