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, forceAutoplay: false })
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, forceAutoplay: false })
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 (options: {
245 forceAutoplay: boolean
247 const { videoId, forceAutoplay } = options
249 if (this.isSameElement(this.video, videoId)) return
251 if (this.player) this.player.pause()
253 this.video = undefined
255 const videoObs = this.hooks.wrapObsFun(
256 this.videoService.getVideo.bind(this.videoService),
259 'filter:api.video-watch.video.get.params',
260 'filter:api.video-watch.video.get.result'
263 const videoAndLiveObs: Observable<{ video: VideoDetails, live?: LiveVideo, videoFileToken?: string }> = videoObs.pipe(
265 if (!video.isLive) return of({ video, live: undefined })
267 return this.liveVideoService.getVideoLive(video.uuid)
268 .pipe(map(live => ({ live, video })))
271 switchMap(({ video, live }) => {
272 if (!videoRequiresAuth(video)) return of({ video, live, videoFileToken: undefined })
274 return this.videoFileTokenService.getVideoFileToken(video.uuid)
275 .pipe(map(({ token }) => ({ video, live, videoFileToken: token })))
281 this.videoCaptionService.listCaptions(videoId),
282 this.userService.getAnonymousOrLoggedUser()
284 next: ([ { video, live, videoFileToken }, captionsResult, loggedInOrAnonymousUser ]) => {
285 const queryParams = this.route.snapshot.queryParams
288 resume: queryParams.resume,
290 startTime: queryParams.start,
291 stopTime: queryParams.stop,
293 muted: queryParams.muted,
294 loop: queryParams.loop,
295 subtitle: queryParams.subtitle,
297 playerMode: queryParams.mode,
301 this.onVideoFetched({
304 videoCaptions: captionsResult.data,
306 loggedInOrAnonymousUser,
309 }).catch(err => this.handleGlobalError(err))
312 error: err => this.handleRequestError(err)
316 private loadPlaylist (playlistId: string) {
317 if (this.isSameElement(this.playlist, playlistId)) return
319 this.noPlaylistVideoFound = false
321 this.playlistService.getVideoPlaylist(playlistId)
324 this.playlist = playlist
326 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
329 error: err => this.handleRequestError(err)
333 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
334 if (!element) return false
336 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
339 private async handleRequestError (err: any) {
340 const errorBody = err.body as PeerTubeProblemDocument
342 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
343 const originUrl = errorBody.originUrl + (window.location.search ?? '')
345 const res = await this.confirmService.confirm(
346 // eslint-disable-next-line max-len
347 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
348 $localize`Redirection`
351 if (res === true) return window.location.href = originUrl
354 // If 400, 403 or 404, the video is private or blocked so redirect to 404
355 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
356 HttpStatusCode.BAD_REQUEST_400,
357 HttpStatusCode.FORBIDDEN_403,
358 HttpStatusCode.NOT_FOUND_404
362 private handleGlobalError (err: any) {
363 const errorMessage: string = typeof err === 'string' ? err : err.message
364 if (!errorMessage) return
366 // Display a message in the video player instead of a notification
367 if (errorMessage.includes('from xs param')) {
369 this.remoteServerDown = true
374 this.notifier.error(errorMessage)
377 private async onVideoFetched (options: {
380 videoCaptions: VideoCaption[]
381 videoFileToken: string
383 urlOptions: URLOptions
384 loggedInOrAnonymousUser: User
385 forceAutoplay: boolean
387 const { video, live, videoCaptions, urlOptions, videoFileToken, loggedInOrAnonymousUser, forceAutoplay } = options
389 this.subscribeToLiveEventsIfNeeded(this.video, video)
392 this.videoCaptions = videoCaptions
393 this.liveVideo = live
394 this.videoFileToken = videoFileToken
396 // Re init attributes
397 this.playerPlaceholderImgSrc = undefined
398 this.remoteServerDown = false
399 this.currentTime = undefined
401 if (this.isVideoBlur(this.video)) {
402 const res = await this.confirmService.confirm(
403 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
404 $localize`Mature or explicit content`
406 if (res === false) return this.location.back()
409 this.buildPlayer({ urlOptions, loggedInOrAnonymousUser, forceAutoplay })
410 .catch(err => logger.error('Cannot build the player', err))
412 this.setOpenGraphTags()
414 const hookOptions = {
417 playlist: this.playlist
419 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
422 private async buildPlayer (options: {
423 urlOptions: URLOptions
424 loggedInOrAnonymousUser: User
425 forceAutoplay: boolean
427 const { urlOptions, loggedInOrAnonymousUser, forceAutoplay } = options
429 // Flush old player if needed
432 const videoState = this.video.state.id
433 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
434 this.playerPlaceholderImgSrc = this.video.previewPath
438 // Build video element, because videojs removes it on dispose
439 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
440 this.playerElement = document.createElement('video')
441 this.playerElement.className = 'video-js vjs-peertube-skin'
442 this.playerElement.setAttribute('playsinline', 'true')
443 playerElementWrapper.appendChild(this.playerElement)
447 videoCaptions: this.videoCaptions,
448 liveVideo: this.liveVideo,
449 videoFileToken: this.videoFileToken,
451 loggedInOrAnonymousUser,
455 const { playerMode, playerOptions } = await this.hooks.wrapFun(
456 this.buildPlayerManagerOptions.bind(this),
459 'filter:internal.video-watch.player.build-options.params',
460 'filter:internal.video-watch.player.build-options.result'
463 this.zone.runOutsideAngular(async () => {
464 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
466 this.player.on('customError', (_e, data: any) => {
467 this.zone.run(() => this.handleGlobalError(data.err))
470 this.player.on('timeupdate', () => {
471 // Don't need to trigger angular change for this variable, that is sent to children components on click
472 this.currentTime = Math.floor(this.player.currentTime())
476 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
477 * go to the next video in 'condition()' if you don't want of the timer.
478 * next: function triggered at the end of the timer.
479 * suspended: function used at each click of the timer checking if we need to reset progress
480 * and wait until suspended becomes truthy again.
485 headText: $localize`Up Next`,
486 cancelText: $localize`Cancel`,
487 suspendedText: $localize`Autoplay is suspended`,
489 getTitle: () => this.nextVideoTitle,
491 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
493 if (!this.playlist) return this.isAutoPlayNext()
495 // Don't wait timeout to play the next playlist video
496 if (this.isPlaylistAutoPlayNext()) {
497 this.playNextVideoInAngularZone()
506 !isXPercentInViewport(this.player.el() as HTMLElement, 80) ||
507 !document.getElementById('content').contains(document.activeElement)
512 this.player.one('stopped', () => {
513 if (this.playlist && this.isPlaylistAutoPlayNext()) {
514 this.playNextVideoInAngularZone()
518 this.player.one('ended', () => {
519 if (this.video.isLive) {
520 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
524 this.player.on('theaterChange', (_: any, enabled: boolean) => {
525 this.zone.run(() => this.theaterEnabled = enabled)
528 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', {
530 playlist: this.playlist,
531 playlistPosition: this.playlistPosition,
538 private hasNextVideo () {
540 return this.videoWatchPlaylist.hasNextVideo()
546 private playNextVideoInAngularZone () {
548 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
552 if (this.nextVideoUUID) {
553 this.router.navigate([ '/w', this.nextVideoUUID ])
557 private isAutoplay () {
558 // We'll jump to the thread id, so do not play the video
559 if (this.route.snapshot.params['threadId']) return false
561 // Otherwise true by default
562 if (!this.user) return true
564 // Be sure the autoPlay is set to false
565 return this.user.autoPlayVideo !== false
568 private isAutoPlayNext () {
570 (this.user?.autoPlayNextVideo) ||
571 this.anonymousUser.autoPlayNextVideo
575 private isPlaylistAutoPlayNext () {
577 (this.user?.autoPlayNextVideoPlaylist) ||
578 this.anonymousUser.autoPlayNextVideoPlaylist
582 private flushPlayer () {
583 // Remove player if it exists
584 if (!this.player) return
587 this.player.dispose()
588 this.player = undefined
590 logger.error('Cannot dispose player.', err)
594 private buildPlayerManagerOptions (params: {
597 videoCaptions: VideoCaption[]
599 videoFileToken: string
601 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
603 loggedInOrAnonymousUser: User
604 forceAutoplay: boolean
605 user?: AuthUser // Keep for plugins
607 const { video, liveVideo, videoCaptions, videoFileToken, urlOptions, loggedInOrAnonymousUser, forceAutoplay } = params
609 const getStartTime = () => {
610 const byUrl = urlOptions.startTime !== undefined
611 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
612 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
614 if (byUrl) return timeToInt(urlOptions.startTime)
615 if (byHistory) return video.userHistory.currentTime
616 if (byLocalStorage) return byLocalStorage.duration
621 let startTime = getStartTime()
623 // If we are at the end of the video, reset the timer
624 if (video.duration - startTime <= 1) startTime = 0
626 const playerCaptions = videoCaptions.map(c => ({
627 label: c.language.label,
628 language: c.language.id,
629 src: environment.apiUrl + c.captionPath
632 const liveOptions = video.isLive
633 ? { latencyMode: liveVideo.latencyMode }
636 const options: PeertubePlayerManagerOptions = {
638 autoplay: this.isAutoplay(),
640 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
642 hasNextVideo: () => this.hasNextVideo(),
643 nextVideo: () => this.playNextVideoInAngularZone(),
645 playerElement: this.playerElement,
646 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
648 videoDuration: video.duration,
650 inactivityTimeout: 2500,
651 poster: video.previewUrl,
654 stopTime: urlOptions.stopTime,
655 controlBar: urlOptions.controlBar,
656 controls: urlOptions.controls,
657 muted: urlOptions.muted,
658 loop: urlOptions.loop,
659 subtitle: urlOptions.subtitle,
661 peertubeLink: urlOptions.peertubeLink,
664 captions: videoCaptions.length !== 0,
666 embedUrl: video.embedUrl,
667 embedTitle: video.name,
668 instanceName: this.serverConfig.instance.name,
670 isLive: video.isLive,
673 language: this.localeId,
675 metricsUrl: environment.apiUrl + '/api/v1/metrics/playback',
677 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
678 ? this.videoService.getVideoViewUrl(video.uuid)
680 authorizationHeader: () => this.authService.getRequestHeaderValue(),
682 serverUrl: environment.originServerUrl || window.location.origin,
684 videoFileToken: () => videoFileToken,
685 requiresAuth: videoRequiresAuth(video),
687 videoCaptions: playerCaptions,
689 videoShortUUID: video.shortUUID,
690 videoUUID: video.uuid,
692 errorNotifier: (message: string) => this.notifier.error(message)
696 videoFiles: video.files
699 pluginsManager: this.pluginService.getPluginsManager()
702 // Only set this if we're in a playlist
704 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
706 options.common.previousVideo = () => {
707 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
713 if (urlOptions.playerMode) {
714 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
715 else mode = 'webtorrent'
717 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
718 else mode = 'webtorrent'
721 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
722 if (typeof TextEncoder === 'undefined') {
726 if (mode === 'p2p-media-loader') {
727 const hlsPlaylist = video.getHlsPlaylist()
729 const p2pMediaLoader = {
730 playlistUrl: hlsPlaylist.playlistUrl,
731 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
732 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
733 trackerAnnounce: video.trackerUrls,
734 videoFiles: hlsPlaylist.files
735 } as P2PMediaLoaderOptions
737 Object.assign(options, { p2pMediaLoader })
740 return { playerMode: mode, playerOptions: options }
743 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
744 if (!this.liveVideosSub) {
745 this.liveVideosSub = this.buildLiveEventsSubscription()
748 if (oldVideo && oldVideo.id !== newVideo.id) {
749 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
752 if (!newVideo.isLive) return
754 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
757 private buildLiveEventsSubscription () {
758 return this.peertubeSocket.getLiveVideosObservable()
759 .subscribe(({ type, payload }) => {
760 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
761 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
765 private handleLiveStateChange (newState: VideoState) {
766 if (newState !== VideoState.PUBLISHED) return
768 logger.info('Loading video after live update.')
770 const videoUUID = this.video.uuid
772 // Reset to force refresh the video
773 this.video = undefined
774 this.loadVideo({ videoId: videoUUID, forceAutoplay: true })
777 private handleLiveViewsChange (newViewers: number) {
779 logger.error('Cannot update video live views because video is no defined.')
783 logger.info('Updating live views.')
785 this.video.viewers = newViewers
788 private initHotkeys () {
790 // These hotkeys are managed by the player
791 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
792 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
793 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
795 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
797 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
798 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
800 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
801 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
803 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
804 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
806 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
807 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
809 new Hotkey('t', e => {
810 this.theaterEnabled = !this.theaterEnabled
812 }, undefined, $localize`Toggle theater mode`)
815 if (this.isUserLoggedIn()) {
816 this.hotkeys = this.hotkeys.concat([
817 new Hotkey('shift+s', () => {
818 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
819 else this.subscribeButton.subscribe()
822 }, undefined, $localize`Subscribe to the account`)
826 this.hotkeysService.add(this.hotkeys)
829 private setOpenGraphTags () {
830 this.metaService.setTitle(this.video.name)
832 this.metaService.setTag('og:type', 'video')
834 this.metaService.setTag('og:title', this.video.name)
835 this.metaService.setTag('name', this.video.name)
837 this.metaService.setTag('og:description', this.video.description)
838 this.metaService.setTag('description', this.video.description)
840 this.metaService.setTag('og:image', this.video.previewPath)
842 this.metaService.setTag('og:duration', this.video.duration.toString())
844 this.metaService.setTag('og:site_name', 'PeerTube')
846 this.metaService.setTag('og:url', window.location.href)
847 this.metaService.setTag('url', window.location.href)