1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, map, Observable, of, Subscription, switchMap } from 'rxjs'
3 import { VideoJsPlayer } from 'video.js'
4 import { PlatformLocation } from '@angular/common'
5 import { Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
6 import { ActivatedRoute, Router } from '@angular/router'
21 import { HooksService } from '@app/core/plugins/hooks.service'
22 import { isXPercentInViewport, scrollToTop } from '@app/helpers'
23 import { Video, VideoCaptionService, VideoDetails, VideoFileTokenService, VideoService } from '@app/shared/shared-main'
24 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
25 import { LiveVideoService } from '@app/shared/shared-video-live'
26 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
27 import { logger } from '@root-helpers/logger'
28 import { isP2PEnabled, videoRequiresAuth } from '@root-helpers/video'
29 import { timeToInt } from '@shared/core-utils'
34 PeerTubeProblemDocument,
39 } from '@shared/models'
42 P2PMediaLoaderOptions,
43 PeertubePlayerManager,
44 PeertubePlayerManagerOptions,
47 } from '../../../assets/player'
48 import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage'
49 import { environment } from '../../../environments/environment'
50 import { VideoWatchPlaylistComponent } from './shared'
52 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
55 selector: 'my-video-watch',
56 templateUrl: './video-watch.component.html',
57 styleUrls: [ './video-watch.component.scss' ]
59 export class VideoWatchComponent implements OnInit, OnDestroy {
60 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
61 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
64 playerElement: HTMLVideoElement
65 playerPlaceholderImgSrc: string
66 theaterEnabled = false
68 video: VideoDetails = null
69 videoCaptions: VideoCaption[] = []
72 playlistPosition: number
73 playlist: VideoPlaylist = null
75 remoteServerDown = false
76 noPlaylistVideoFound = false
78 private nextVideoUUID = ''
79 private nextVideoTitle = ''
81 private videoFileToken: string
83 private currentTime: number
85 private paramsSub: Subscription
86 private queryParamsSub: Subscription
87 private configSub: Subscription
88 private liveVideosSub: Subscription
90 private serverConfig: HTMLServerConfig
92 private hotkeys: Hotkey[] = []
95 private elementRef: ElementRef,
96 private route: ActivatedRoute,
97 private router: Router,
98 private videoService: VideoService,
99 private playlistService: VideoPlaylistService,
100 private liveVideoService: LiveVideoService,
101 private confirmService: ConfirmService,
102 private metaService: MetaService,
103 private authService: AuthService,
104 private userService: UserService,
105 private serverService: ServerService,
106 private restExtractor: RestExtractor,
107 private notifier: Notifier,
108 private zone: NgZone,
109 private videoCaptionService: VideoCaptionService,
110 private hotkeysService: HotkeysService,
111 private hooks: HooksService,
112 private pluginService: PluginService,
113 private peertubeSocket: PeerTubeSocket,
114 private screenService: ScreenService,
115 private videoFileTokenService: VideoFileTokenService,
116 private location: PlatformLocation,
117 @Inject(LOCALE_ID) private localeId: string
121 return this.authService.getUser()
124 get anonymousUser () {
125 return this.userService.getAnonymousUser()
129 this.serverConfig = this.serverService.getHTMLConfig()
131 PeertubePlayerManager.initState()
133 this.loadRouteParams()
134 this.loadRouteQuery()
138 this.theaterEnabled = getStoredTheater()
140 this.hooks.runAction('action:video-watch.init', 'video-watch')
142 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
148 // Unsubscribe subscriptions
149 if (this.paramsSub) this.paramsSub.unsubscribe()
150 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
151 if (this.configSub) this.configSub.unsubscribe()
152 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
155 this.hotkeysService.remove(this.hotkeys)
159 return this.currentTime
162 getCurrentPlaylistPosition () {
163 return this.videoWatchPlaylist.currentPlaylistPosition
166 onRecommendations (videos: Video[]) {
167 if (videos.length === 0) return
169 // The recommended videos's first element should be the next video
170 const video = videos[0]
171 this.nextVideoUUID = video.uuid
172 this.nextVideoTitle = video.name
175 handleTimestampClicked (timestamp: number) {
176 if (!this.player || this.video.isLive) return
178 this.player.currentTime(timestamp)
182 onPlaylistVideoFound (videoId: string) {
183 this.loadVideo(videoId)
186 onPlaylistNoVideoFound () {
187 this.noPlaylistVideoFound = true
191 return this.authService.isLoggedIn()
194 isVideoBlur (video: Video) {
195 return video.isVideoNSFWForUser(this.user, this.serverConfig)
198 isChannelDisplayNameGeneric () {
199 const genericChannelDisplayName = [
200 `Main ${this.video.channel.ownerAccount.name} channel`,
201 `Default ${this.video.channel.ownerAccount.name} channel`
204 return genericChannelDisplayName.includes(this.video.channel.displayName)
207 displayOtherVideosAsRow () {
208 // Use the same value as in the SASS file
209 return this.screenService.getWindowInnerWidth() <= 1100
212 private loadRouteParams () {
213 this.paramsSub = this.route.params.subscribe(routeParams => {
214 const videoId = routeParams['videoId']
215 if (videoId) return this.loadVideo(videoId)
217 const playlistId = routeParams['playlistId']
218 if (playlistId) return this.loadPlaylist(playlistId)
222 private loadRouteQuery () {
223 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
224 // Handle the ?playlistPosition
225 const positionParam = queryParams['playlistPosition'] ?? 1
227 this.playlistPosition = positionParam === 'last'
228 ? -1 // Handle the "last" index
229 : parseInt(positionParam + '', 10)
231 if (isNaN(this.playlistPosition)) {
232 logger.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
233 this.playlistPosition = 1
236 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
238 const start = queryParams['start']
239 if (this.player && start) this.player.currentTime(parseInt(start, 10))
243 private loadVideo (videoId: string) {
244 if (this.isSameElement(this.video, videoId)) return
246 if (this.player) this.player.pause()
248 this.video = undefined
250 const videoObs = this.hooks.wrapObsFun(
251 this.videoService.getVideo.bind(this.videoService),
254 'filter:api.video-watch.video.get.params',
255 'filter:api.video-watch.video.get.result'
258 const videoAndLiveObs: Observable<{ video: VideoDetails, live?: LiveVideo, videoFileToken?: string }> = videoObs.pipe(
260 if (!video.isLive) return of({ video, live: undefined })
262 return this.liveVideoService.getVideoLive(video.uuid)
263 .pipe(map(live => ({ live, video })))
266 switchMap(({ video, live }) => {
267 if (!videoRequiresAuth(video)) return of({ video, live, videoFileToken: undefined })
269 return this.videoFileTokenService.getVideoFileToken(video.uuid)
270 .pipe(map(({ token }) => ({ video, live, videoFileToken: token })))
276 this.videoCaptionService.listCaptions(videoId),
277 this.userService.getAnonymousOrLoggedUser()
279 next: ([ { video, live, videoFileToken }, captionsResult, loggedInOrAnonymousUser ]) => {
280 const queryParams = this.route.snapshot.queryParams
283 resume: queryParams.resume,
285 startTime: queryParams.start,
286 stopTime: queryParams.stop,
288 muted: queryParams.muted,
289 loop: queryParams.loop,
290 subtitle: queryParams.subtitle,
292 playerMode: queryParams.mode,
296 this.onVideoFetched({ video, live, videoCaptions: captionsResult.data, videoFileToken, loggedInOrAnonymousUser, urlOptions })
297 .catch(err => this.handleGlobalError(err))
300 error: err => this.handleRequestError(err)
304 private loadPlaylist (playlistId: string) {
305 if (this.isSameElement(this.playlist, playlistId)) return
307 this.noPlaylistVideoFound = false
309 this.playlistService.getVideoPlaylist(playlistId)
312 this.playlist = playlist
314 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
317 error: err => this.handleRequestError(err)
321 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
322 if (!element) return false
324 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
327 private async handleRequestError (err: any) {
328 const errorBody = err.body as PeerTubeProblemDocument
330 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
331 const originUrl = errorBody.originUrl + (window.location.search ?? '')
333 const res = await this.confirmService.confirm(
334 // eslint-disable-next-line max-len
335 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
336 $localize`Redirection`
339 if (res === true) return window.location.href = originUrl
342 // If 400, 403 or 404, the video is private or blocked so redirect to 404
343 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
344 HttpStatusCode.BAD_REQUEST_400,
345 HttpStatusCode.FORBIDDEN_403,
346 HttpStatusCode.NOT_FOUND_404
350 private handleGlobalError (err: any) {
351 const errorMessage: string = typeof err === 'string' ? err : err.message
352 if (!errorMessage) return
354 // Display a message in the video player instead of a notification
355 if (errorMessage.includes('from xs param')) {
357 this.remoteServerDown = true
362 this.notifier.error(errorMessage)
365 private async onVideoFetched (options: {
368 videoCaptions: VideoCaption[]
369 videoFileToken: string
371 urlOptions: URLOptions
372 loggedInOrAnonymousUser: User
374 const { video, live, videoCaptions, urlOptions, videoFileToken, loggedInOrAnonymousUser } = options
376 this.subscribeToLiveEventsIfNeeded(this.video, video)
379 this.videoCaptions = videoCaptions
380 this.liveVideo = live
381 this.videoFileToken = videoFileToken
383 // Re init attributes
384 this.playerPlaceholderImgSrc = undefined
385 this.remoteServerDown = false
386 this.currentTime = undefined
388 if (this.isVideoBlur(this.video)) {
389 const res = await this.confirmService.confirm(
390 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
391 $localize`Mature or explicit content`
393 if (res === false) return this.location.back()
396 this.buildPlayer(urlOptions, loggedInOrAnonymousUser)
397 .catch(err => logger.error('Cannot build the player', err))
399 this.setOpenGraphTags()
401 const hookOptions = {
404 playlist: this.playlist
406 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
409 private async buildPlayer (urlOptions: URLOptions, loggedInOrAnonymousUser: User) {
410 // Flush old player if needed
413 const videoState = this.video.state.id
414 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
415 this.playerPlaceholderImgSrc = this.video.previewPath
419 // Build video element, because videojs removes it on dispose
420 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
421 this.playerElement = document.createElement('video')
422 this.playerElement.className = 'video-js vjs-peertube-skin'
423 this.playerElement.setAttribute('playsinline', 'true')
424 playerElementWrapper.appendChild(this.playerElement)
428 videoCaptions: this.videoCaptions,
429 liveVideo: this.liveVideo,
430 videoFileToken: this.videoFileToken,
432 loggedInOrAnonymousUser,
435 const { playerMode, playerOptions } = await this.hooks.wrapFun(
436 this.buildPlayerManagerOptions.bind(this),
439 'filter:internal.video-watch.player.build-options.params',
440 'filter:internal.video-watch.player.build-options.result'
443 this.zone.runOutsideAngular(async () => {
444 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
446 this.player.on('customError', (_e, data: any) => {
447 this.zone.run(() => this.handleGlobalError(data.err))
450 this.player.on('timeupdate', () => {
451 // Don't need to trigger angular change for this variable, that is sent to children components on click
452 this.currentTime = Math.floor(this.player.currentTime())
456 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
457 * go to the next video in 'condition()' if you don't want of the timer.
458 * next: function triggered at the end of the timer.
459 * suspended: function used at each click of the timer checking if we need to reset progress
460 * and wait until suspended becomes truthy again.
465 headText: $localize`Up Next`,
466 cancelText: $localize`Cancel`,
467 suspendedText: $localize`Autoplay is suspended`,
469 getTitle: () => this.nextVideoTitle,
471 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
473 if (!this.playlist) return this.isAutoPlayNext()
475 // Don't wait timeout to play the next playlist video
476 if (this.isPlaylistAutoPlayNext()) {
477 this.playNextVideoInAngularZone()
486 !isXPercentInViewport(this.player.el() as HTMLElement, 80) ||
487 !document.getElementById('content').contains(document.activeElement)
492 this.player.one('stopped', () => {
493 if (this.playlist && this.isPlaylistAutoPlayNext()) {
494 this.playNextVideoInAngularZone()
498 this.player.one('ended', () => {
499 if (this.video.isLive) {
500 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
504 this.player.on('theaterChange', (_: any, enabled: boolean) => {
505 this.zone.run(() => this.theaterEnabled = enabled)
508 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', {
510 playlist: this.playlist,
511 playlistPosition: this.playlistPosition,
518 private hasNextVideo () {
520 return this.videoWatchPlaylist.hasNextVideo()
526 private playNextVideoInAngularZone () {
528 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
532 if (this.nextVideoUUID) {
533 this.router.navigate([ '/w', this.nextVideoUUID ])
537 private isAutoplay () {
538 // We'll jump to the thread id, so do not play the video
539 if (this.route.snapshot.params['threadId']) return false
541 // Otherwise true by default
542 if (!this.user) return true
544 // Be sure the autoPlay is set to false
545 return this.user.autoPlayVideo !== false
548 private isAutoPlayNext () {
550 (this.user?.autoPlayNextVideo) ||
551 this.anonymousUser.autoPlayNextVideo
555 private isPlaylistAutoPlayNext () {
557 (this.user?.autoPlayNextVideoPlaylist) ||
558 this.anonymousUser.autoPlayNextVideoPlaylist
562 private flushPlayer () {
563 // Remove player if it exists
564 if (!this.player) return
567 this.player.dispose()
568 this.player = undefined
570 logger.error('Cannot dispose player.', err)
574 private buildPlayerManagerOptions (params: {
577 videoCaptions: VideoCaption[]
579 videoFileToken: string
581 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
583 loggedInOrAnonymousUser: User
584 user?: AuthUser // Keep for plugins
586 const { video, liveVideo, videoCaptions, videoFileToken, urlOptions, loggedInOrAnonymousUser } = params
588 const getStartTime = () => {
589 const byUrl = urlOptions.startTime !== undefined
590 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
591 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
593 if (byUrl) return timeToInt(urlOptions.startTime)
594 if (byHistory) return video.userHistory.currentTime
595 if (byLocalStorage) return byLocalStorage.duration
600 let startTime = getStartTime()
602 // If we are at the end of the video, reset the timer
603 if (video.duration - startTime <= 1) startTime = 0
605 const playerCaptions = videoCaptions.map(c => ({
606 label: c.language.label,
607 language: c.language.id,
608 src: environment.apiUrl + c.captionPath
611 const liveOptions = video.isLive
612 ? { latencyMode: liveVideo.latencyMode }
615 const options: PeertubePlayerManagerOptions = {
617 autoplay: this.isAutoplay(),
618 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
620 hasNextVideo: () => this.hasNextVideo(),
621 nextVideo: () => this.playNextVideoInAngularZone(),
623 playerElement: this.playerElement,
624 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
626 videoDuration: video.duration,
628 inactivityTimeout: 2500,
629 poster: video.previewUrl,
632 stopTime: urlOptions.stopTime,
633 controlBar: urlOptions.controlBar,
634 controls: urlOptions.controls,
635 muted: urlOptions.muted,
636 loop: urlOptions.loop,
637 subtitle: urlOptions.subtitle,
639 peertubeLink: urlOptions.peertubeLink,
642 captions: videoCaptions.length !== 0,
644 embedUrl: video.embedUrl,
645 embedTitle: video.name,
646 instanceName: this.serverConfig.instance.name,
648 isLive: video.isLive,
651 language: this.localeId,
653 metricsUrl: environment.apiUrl + '/api/v1/metrics/playback',
655 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
656 ? this.videoService.getVideoViewUrl(video.uuid)
658 authorizationHeader: () => this.authService.getRequestHeaderValue(),
660 serverUrl: environment.originServerUrl || window.location.origin,
662 videoFileToken: () => videoFileToken,
663 requiresAuth: videoRequiresAuth(video),
665 videoCaptions: playerCaptions,
667 videoShortUUID: video.shortUUID,
668 videoUUID: video.uuid,
670 errorNotifier: (message: string) => this.notifier.error(message)
674 videoFiles: video.files
677 pluginsManager: this.pluginService.getPluginsManager()
680 // Only set this if we're in a playlist
682 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
684 options.common.previousVideo = () => {
685 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
691 if (urlOptions.playerMode) {
692 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
693 else mode = 'webtorrent'
695 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
696 else mode = 'webtorrent'
699 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
700 if (typeof TextEncoder === 'undefined') {
704 if (mode === 'p2p-media-loader') {
705 const hlsPlaylist = video.getHlsPlaylist()
707 const p2pMediaLoader = {
708 playlistUrl: hlsPlaylist.playlistUrl,
709 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
710 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
711 trackerAnnounce: video.trackerUrls,
712 videoFiles: hlsPlaylist.files
713 } as P2PMediaLoaderOptions
715 Object.assign(options, { p2pMediaLoader })
718 return { playerMode: mode, playerOptions: options }
721 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
722 if (!this.liveVideosSub) {
723 this.liveVideosSub = this.buildLiveEventsSubscription()
726 if (oldVideo && oldVideo.id !== newVideo.id) {
727 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
730 if (!newVideo.isLive) return
732 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
735 private buildLiveEventsSubscription () {
736 return this.peertubeSocket.getLiveVideosObservable()
737 .subscribe(({ type, payload }) => {
738 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
739 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
743 private handleLiveStateChange (newState: VideoState) {
744 if (newState !== VideoState.PUBLISHED) return
746 logger.info('Loading video after live update.')
748 const videoUUID = this.video.uuid
750 // Reset to force refresh the video
751 this.video = undefined
752 this.loadVideo(videoUUID)
755 private handleLiveViewsChange (newViewers: number) {
757 logger.error('Cannot update video live views because video is no defined.')
761 logger.info('Updating live views.')
763 this.video.viewers = newViewers
766 private initHotkeys () {
768 // These hotkeys are managed by the player
769 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
770 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
771 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
773 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
775 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
776 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
778 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
779 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
781 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
782 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
784 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
785 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
787 new Hotkey('t', e => {
788 this.theaterEnabled = !this.theaterEnabled
790 }, undefined, $localize`Toggle theater mode`)
793 if (this.isUserLoggedIn()) {
794 this.hotkeys = this.hotkeys.concat([
795 new Hotkey('shift+s', () => {
796 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
797 else this.subscribeButton.subscribe()
800 }, undefined, $localize`Subscribe to the account`)
804 this.hotkeysService.add(this.hotkeys)
807 private setOpenGraphTags () {
808 this.metaService.setTitle(this.video.name)
810 this.metaService.setTag('og:type', 'video')
812 this.metaService.setTag('og:title', this.video.name)
813 this.metaService.setTag('name', this.video.name)
815 this.metaService.setTag('og:description', this.video.description)
816 this.metaService.setTag('description', this.video.description)
818 this.metaService.setTag('og:image', this.video.previewPath)
820 this.metaService.setTag('og:duration', this.video.duration.toString())
822 this.metaService.setTag('og:site_name', 'PeerTube')
824 this.metaService.setTag('og:url', window.location.href)
825 this.metaService.setTag('url', window.location.href)