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
185 this.paramsSub = this.route.params.subscribe(routeParams => {
186 const videoId = routeParams[ 'videoId' ]
187 if (videoId) this.loadVideo(videoId)
189 const playlistId = routeParams[ 'playlistId' ]
190 if (playlistId) this.loadPlaylist(playlistId)
193 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
194 // Handle the ?playlistPosition
195 const positionParam = queryParams[ 'playlistPosition' ] ?? 1
197 this.playlistPosition = positionParam === 'last'
198 ? -1 // Handle the "last" index
199 : parseInt(positionParam + '', 10)
201 if (isNaN(this.playlistPosition)) {
202 console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
203 this.playlistPosition = 1
206 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
208 const start = queryParams[ 'start' ]
209 if (this.player && start) this.player.currentTime(parseInt(start, 10))
214 this.theaterEnabled = getStoredTheater()
216 this.hooks.runAction('action:video-watch.init', 'video-watch')
218 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
224 // Unsubscribe subscriptions
225 if (this.paramsSub) this.paramsSub.unsubscribe()
226 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
227 if (this.configSub) this.configSub.unsubscribe()
228 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
231 this.hotkeysService.remove(this.hotkeys)
235 if (this.isUserLoggedIn() === false) return
237 // Already liked this video
238 if (this.userRating === 'like') this.setRating('none')
239 else this.setRating('like')
243 if (this.isUserLoggedIn() === false) return
245 // Already disliked this video
246 if (this.userRating === 'dislike') this.setRating('none')
247 else this.setRating('dislike')
250 getRatePopoverText () {
251 if (this.isUserLoggedIn()) return undefined
253 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
256 showMoreDescription () {
257 if (this.completeVideoDescription === undefined) {
258 return this.loadCompleteDescription()
261 this.updateVideoDescription(this.completeVideoDescription)
262 this.completeDescriptionShown = true
265 showLessDescription () {
266 this.updateVideoDescription(this.shortVideoDescription)
267 this.completeDescriptionShown = false
270 showDownloadModal () {
271 this.videoDownloadModal.show(this.video, this.videoCaptions)
274 isVideoDownloadable () {
275 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
278 loadCompleteDescription () {
279 this.descriptionLoading = true
281 this.videoService.loadCompleteDescription(this.video.descriptionPath)
284 this.completeDescriptionShown = true
285 this.descriptionLoading = false
287 this.shortVideoDescription = this.video.description
288 this.completeVideoDescription = description
290 this.updateVideoDescription(this.completeVideoDescription)
294 this.descriptionLoading = false
295 this.notifier.error(error.message)
300 showSupportModal () {
301 this.supportModal.show()
305 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
309 return this.authService.isLoggedIn()
313 if (!this.video.url) {
314 return this.video.originInstanceUrl + VideoDetails.buildClientUrl(this.video.uuid)
316 return this.video.url
320 if (!this.video || Array.isArray(this.video.tags) === false) return []
322 return this.video.tags
325 onRecommendations (videos: Video[]) {
326 if (videos.length > 0) {
327 // The recommended videos's first element should be the next video
328 const video = videos[0]
329 this.nextVideoUuid = video.uuid
330 this.nextVideoTitle = video.name
335 this.redirectService.redirectToHomepage()
338 declinedPrivacyConcern () {
339 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
340 this.hasAlreadyAcceptedPrivacyConcern = false
343 acceptedPrivacyConcern () {
344 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
345 this.hasAlreadyAcceptedPrivacyConcern = true
348 isVideoToTranscode () {
349 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
353 return this.video && this.video.state.id === VideoState.TO_IMPORT
356 hasVideoScheduledPublication () {
357 return this.video && this.video.scheduledUpdate !== undefined
361 return !!(this.video?.isLive)
364 isWaitingForLive () {
365 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
369 return this.video?.state.id === VideoState.LIVE_ENDED
372 isVideoBlur (video: Video) {
373 return video.isVideoNSFWForUser(this.user, this.serverConfig)
376 isAutoPlayEnabled () {
378 (this.user && this.user.autoPlayNextVideo) ||
379 this.anonymousUser.autoPlayNextVideo
383 handleTimestampClicked (timestamp: number) {
384 if (!this.player || this.video.isLive) return
386 this.player.currentTime(timestamp)
390 isPlaylistAutoPlayEnabled () {
392 (this.user && this.user.autoPlayNextVideoPlaylist) ||
393 this.anonymousUser.autoPlayNextVideoPlaylist
397 isChannelDisplayNameGeneric () {
398 const genericChannelDisplayName = [
399 `Main ${this.video.channel.ownerAccount.name} channel`,
400 `Default ${this.video.channel.ownerAccount.name} channel`
403 return genericChannelDisplayName.includes(this.video.channel.displayName)
406 onPlaylistVideoFound (videoId: string) {
407 this.loadVideo(videoId)
410 displayOtherVideosAsRow () {
411 // Use the same value as in the SASS file
412 return this.screenService.getWindowInnerWidth() <= 1100
415 private loadVideo (videoId: string) {
416 // Video did not change
417 if (this.video && this.video.uuid === videoId) return
419 if (this.player) this.player.pause()
421 const videoObs = this.hooks.wrapObsFun(
422 this.videoService.getVideo.bind(this.videoService),
425 'filter:api.video-watch.video.get.params',
426 'filter:api.video-watch.video.get.result'
432 this.videoCaptionService.listCaptions(videoId)
435 // If 400, 403 or 404, the video is private or blocked so redirect to 404
437 const errorBody = err.body as PeerTubeProblemDocument
439 if (errorBody.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
440 const search = window.location.search
441 let originUrl = errorBody.originUrl
442 if (search) originUrl += search
444 this.confirmService.confirm(
445 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
446 $localize`Redirection`
449 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
450 HttpStatusCode.BAD_REQUEST_400,
451 HttpStatusCode.FORBIDDEN_403,
452 HttpStatusCode.NOT_FOUND_404
456 return window.location.href = originUrl
460 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
461 HttpStatusCode.BAD_REQUEST_400,
462 HttpStatusCode.FORBIDDEN_403,
463 HttpStatusCode.NOT_FOUND_404
467 .subscribe(([ video, captionsResult ]) => {
468 const queryParams = this.route.snapshot.queryParams
471 resume: queryParams.resume,
473 startTime: queryParams.start,
474 stopTime: queryParams.stop,
476 muted: queryParams.muted,
477 loop: queryParams.loop,
478 subtitle: queryParams.subtitle,
480 playerMode: queryParams.mode,
484 this.onVideoFetched(video, captionsResult.data, urlOptions)
485 .catch(err => this.handleError(err))
489 private loadPlaylist (playlistId: string) {
490 // Playlist did not change
491 if (this.playlist && this.playlist.uuid === playlistId) return
493 this.playlistService.getVideoPlaylist(playlistId)
495 // If 400 or 403, the video is private or blocked so redirect to 404
496 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
497 HttpStatusCode.BAD_REQUEST_400,
498 HttpStatusCode.FORBIDDEN_403,
499 HttpStatusCode.NOT_FOUND_404
502 .subscribe(playlist => {
503 this.playlist = playlist
505 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
509 private updateVideoDescription (description: string) {
510 this.video.description = description
511 this.setVideoDescriptionHTML()
512 .catch(err => console.error(err))
515 private async setVideoDescriptionHTML () {
516 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
517 this.videoHTMLDescription = this.markdownService.processVideoTimestamps(html)
520 private setVideoLikesBarTooltipText () {
521 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
524 private handleError (err: any) {
525 const errorMessage: string = typeof err === 'string' ? err : err.message
526 if (!errorMessage) return
528 // Display a message in the video player instead of a notification
529 if (errorMessage.indexOf('from xs param') !== -1) {
531 this.remoteServerDown = true
532 this.changeDetector.detectChanges()
537 this.notifier.error(errorMessage)
540 private checkUserRating () {
541 // Unlogged users do not have ratings
542 if (this.isUserLoggedIn() === false) return
544 this.videoService.getUserVideoRating(this.video.id)
548 this.userRating = ratingObject.rating
552 err => this.notifier.error(err.message)
556 private async onVideoFetched (
558 videoCaptions: VideoCaption[],
559 urlOptions: URLOptions
561 this.subscribeToLiveEventsIfNeeded(this.video, video)
564 this.videoCaptions = videoCaptions
566 // Re init attributes
567 this.playerPlaceholderImgSrc = undefined
568 this.descriptionLoading = false
569 this.completeDescriptionShown = false
570 this.completeVideoDescription = undefined
571 this.remoteServerDown = false
572 this.currentTime = undefined
574 if (this.isVideoBlur(this.video)) {
575 const res = await this.confirmService.confirm(
576 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
577 $localize`Mature or explicit content`
579 if (res === false) return this.location.back()
582 this.buildPlayer(urlOptions)
583 .catch(err => console.error('Cannot build the player', err))
585 this.setVideoDescriptionHTML()
586 this.setVideoLikesBarTooltipText()
588 this.setOpenGraphTags()
589 this.checkUserRating()
591 const hookOptions = {
594 playlist: this.playlist
596 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
599 private async buildPlayer (urlOptions: URLOptions) {
600 // Flush old player if needed
603 const videoState = this.video.state.id
604 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
605 this.playerPlaceholderImgSrc = this.video.previewPath
609 // Build video element, because videojs removes it on dispose
610 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
611 this.playerElement = document.createElement('video')
612 this.playerElement.className = 'video-js vjs-peertube-skin'
613 this.playerElement.setAttribute('playsinline', 'true')
614 playerElementWrapper.appendChild(this.playerElement)
618 videoCaptions: this.videoCaptions,
622 const { playerMode, playerOptions } = await this.hooks.wrapFun(
623 this.buildPlayerManagerOptions.bind(this),
626 'filter:internal.video-watch.player.build-options.params',
627 'filter:internal.video-watch.player.build-options.result'
630 this.zone.runOutsideAngular(async () => {
631 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
633 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
635 this.player.on('timeupdate', () => {
636 this.currentTime = Math.floor(this.player.currentTime())
640 * replaces this.player.one('ended')
641 * 'condition()': true to make the upnext functionality trigger,
642 * false to disable the upnext functionality
643 * go to the next video in 'condition()' if you don't want of the timer.
644 * 'next': function triggered at the end of the timer.
645 * 'suspended': function used at each clic of the timer checking if we need
646 * to reset progress and wait until 'suspended' becomes truthy again.
649 timeout: 10000, // 10s
650 headText: $localize`Up Next`,
651 cancelText: $localize`Cancel`,
652 suspendedText: $localize`Autoplay is suspended`,
653 getTitle: () => this.nextVideoTitle,
654 next: () => this.zone.run(() => this.autoplayNext()),
657 if (this.isPlaylistAutoPlayEnabled()) {
658 // upnext will not trigger, and instead the next video will play immediately
659 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
661 } else if (this.isAutoPlayEnabled()) {
662 return true // upnext will trigger
664 return false // upnext will not trigger, and instead leave the video stopping
668 !isXPercentInViewport(this.player.el(), 80) ||
669 !document.getElementById('content').contains(document.activeElement)
674 this.player.one('stopped', () => {
676 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
680 this.player.one('ended', () => {
681 if (this.video.isLive) {
682 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
686 this.player.on('theaterChange', (_: any, enabled: boolean) => {
687 this.zone.run(() => this.theaterEnabled = enabled)
690 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
694 private autoplayNext () {
696 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
697 } else if (this.nextVideoUuid) {
698 this.router.navigate([ '/w', this.nextVideoUuid ])
702 private setRating (nextRating: UserVideoRateType) {
703 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
704 like: this.videoService.setVideoLike,
705 dislike: this.videoService.setVideoDislike,
706 none: this.videoService.unsetVideoLike
709 ratingMethods[nextRating].call(this.videoService, this.video.id)
712 // Update the video like attribute
713 this.updateVideoRating(this.userRating, nextRating)
714 this.userRating = nextRating
717 (err: { message: string }) => this.notifier.error(err.message)
721 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
722 let likesToIncrement = 0
723 let dislikesToIncrement = 0
726 if (oldRating === 'like') likesToIncrement--
727 if (oldRating === 'dislike') dislikesToIncrement--
730 if (newRating === 'like') likesToIncrement++
731 if (newRating === 'dislike') dislikesToIncrement++
733 this.video.likes += likesToIncrement
734 this.video.dislikes += dislikesToIncrement
736 this.video.buildLikeAndDislikePercents()
737 this.setVideoLikesBarTooltipText()
740 private setOpenGraphTags () {
741 this.metaService.setTitle(this.video.name)
743 this.metaService.setTag('og:type', 'video')
745 this.metaService.setTag('og:title', this.video.name)
746 this.metaService.setTag('name', this.video.name)
748 this.metaService.setTag('og:description', this.video.description)
749 this.metaService.setTag('description', this.video.description)
751 this.metaService.setTag('og:image', this.video.previewPath)
753 this.metaService.setTag('og:duration', this.video.duration.toString())
755 this.metaService.setTag('og:site_name', 'PeerTube')
757 this.metaService.setTag('og:url', window.location.href)
758 this.metaService.setTag('url', window.location.href)
761 private isAutoplay () {
762 // We'll jump to the thread id, so do not play the video
763 if (this.route.snapshot.params['threadId']) return false
765 // Otherwise true by default
766 if (!this.user) return true
768 // Be sure the autoPlay is set to false
769 return this.user.autoPlayVideo !== false
772 private flushPlayer () {
773 // Remove player if it exists
776 this.player.dispose()
777 this.player = undefined
779 console.error('Cannot dispose player.', err)
784 private buildPlayerManagerOptions (params: {
786 videoCaptions: VideoCaption[],
787 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
790 const { video, videoCaptions, urlOptions, user } = params
791 const getStartTime = () => {
792 const byUrl = urlOptions.startTime !== undefined
793 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
794 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
796 if (byUrl) return timeToInt(urlOptions.startTime)
797 if (byHistory) return video.userHistory.currentTime
798 if (byLocalStorage) return byLocalStorage.duration
803 let startTime = getStartTime()
805 // If we are at the end of the video, reset the timer
806 if (video.duration - startTime <= 1) startTime = 0
808 const playerCaptions = videoCaptions.map(c => ({
809 label: c.language.label,
810 language: c.language.id,
811 src: environment.apiUrl + c.captionPath
814 const options: PeertubePlayerManagerOptions = {
816 autoplay: this.isAutoplay(),
817 nextVideo: () => this.zone.run(() => this.autoplayNext()),
819 playerElement: this.playerElement,
820 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
822 videoDuration: video.duration,
824 inactivityTimeout: 2500,
825 poster: video.previewUrl,
828 stopTime: urlOptions.stopTime,
829 controls: urlOptions.controls,
830 muted: urlOptions.muted,
831 loop: urlOptions.loop,
832 subtitle: urlOptions.subtitle,
834 peertubeLink: urlOptions.peertubeLink,
837 captions: videoCaptions.length !== 0,
839 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
840 ? this.videoService.getVideoViewUrl(video.uuid)
842 embedUrl: video.embedUrl,
843 embedTitle: video.name,
845 isLive: video.isLive,
847 language: this.localeId,
849 userWatching: user && user.videosHistoryEnabled === true ? {
850 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
851 authorizationHeader: this.authService.getRequestHeaderValue()
854 serverUrl: environment.apiUrl,
856 videoCaptions: playerCaptions,
858 videoUUID: video.uuid
862 videoFiles: video.files
866 // Only set this if we're in a playlist
868 options.common.previousVideo = () => {
869 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
875 if (urlOptions.playerMode) {
876 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
877 else mode = 'webtorrent'
879 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
880 else mode = 'webtorrent'
883 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
884 if (typeof TextEncoder === 'undefined') {
888 if (mode === 'p2p-media-loader') {
889 const hlsPlaylist = video.getHlsPlaylist()
891 const p2pMediaLoader = {
892 playlistUrl: hlsPlaylist.playlistUrl,
893 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
894 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
895 trackerAnnounce: video.trackerUrls,
896 videoFiles: hlsPlaylist.files
897 } as P2PMediaLoaderOptions
899 Object.assign(options, { p2pMediaLoader })
902 return { playerMode: mode, playerOptions: options }
905 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
906 if (!this.liveVideosSub) {
907 this.liveVideosSub = this.buildLiveEventsSubscription()
910 if (oldVideo && oldVideo.id !== newVideo.id) {
911 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
914 if (!newVideo.isLive) return
916 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
919 private buildLiveEventsSubscription () {
920 return this.peertubeSocket.getLiveVideosObservable()
921 .subscribe(({ type, payload }) => {
922 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
923 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
927 private handleLiveStateChange (newState: VideoState) {
928 if (newState !== VideoState.PUBLISHED) return
930 const videoState = this.video.state.id
931 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
933 console.log('Loading video after live update.')
935 const videoUUID = this.video.uuid
937 // Reset to refetch the video
938 this.video = undefined
939 this.loadVideo(videoUUID)
942 private handleLiveViewsChange (newViews: number) {
944 console.error('Cannot update video live views because video is no defined.')
948 console.log('Updating live views.')
950 this.video.views = newViews
953 private initHotkeys () {
955 // These hotkeys are managed by the player
956 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
957 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
958 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
960 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)`),
962 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
963 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
965 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
966 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
968 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
969 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
971 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
974 if (this.isUserLoggedIn()) {
975 this.hotkeys = this.hotkeys.concat([
976 new Hotkey('shift+l', () => {
979 }, undefined, $localize`Like the video`),
981 new Hotkey('shift+d', () => {
984 }, undefined, $localize`Dislike the video`),
986 new Hotkey('shift+s', () => {
987 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
989 }, undefined, $localize`Subscribe to the account`)
993 this.hotkeysService.add(this.hotkeys)