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,
298 playbackRate: queryParams.playbackRate,
302 this.onVideoFetched({
305 videoCaptions: captionsResult.data,
307 loggedInOrAnonymousUser,
310 }).catch(err => this.handleGlobalError(err))
313 error: err => this.handleRequestError(err)
317 private loadPlaylist (playlistId: string) {
318 if (this.isSameElement(this.playlist, playlistId)) return
320 this.noPlaylistVideoFound = false
322 this.playlistService.getVideoPlaylist(playlistId)
325 this.playlist = playlist
327 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
330 error: err => this.handleRequestError(err)
334 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
335 if (!element) return false
337 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
340 private async handleRequestError (err: any) {
341 const errorBody = err.body as PeerTubeProblemDocument
343 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
344 const originUrl = errorBody.originUrl + (window.location.search ?? '')
346 const res = await this.confirmService.confirm(
347 // eslint-disable-next-line max-len
348 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
349 $localize`Redirection`
352 if (res === true) return window.location.href = originUrl
355 // If 400, 403 or 404, the video is private or blocked so redirect to 404
356 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
357 HttpStatusCode.BAD_REQUEST_400,
358 HttpStatusCode.FORBIDDEN_403,
359 HttpStatusCode.NOT_FOUND_404
363 private handleGlobalError (err: any) {
364 const errorMessage: string = typeof err === 'string' ? err : err.message
365 if (!errorMessage) return
367 // Display a message in the video player instead of a notification
368 if (errorMessage.includes('from xs param')) {
370 this.remoteServerDown = true
375 this.notifier.error(errorMessage)
378 private async onVideoFetched (options: {
381 videoCaptions: VideoCaption[]
382 videoFileToken: string
384 urlOptions: URLOptions
385 loggedInOrAnonymousUser: User
386 forceAutoplay: boolean
388 const { video, live, videoCaptions, urlOptions, videoFileToken, loggedInOrAnonymousUser, forceAutoplay } = options
390 this.subscribeToLiveEventsIfNeeded(this.video, video)
393 this.videoCaptions = videoCaptions
394 this.liveVideo = live
395 this.videoFileToken = videoFileToken
397 // Re init attributes
398 this.playerPlaceholderImgSrc = undefined
399 this.remoteServerDown = false
400 this.currentTime = undefined
402 if (this.isVideoBlur(this.video)) {
403 const res = await this.confirmService.confirm(
404 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
405 $localize`Mature or explicit content`
407 if (res === false) return this.location.back()
410 this.buildPlayer({ urlOptions, loggedInOrAnonymousUser, forceAutoplay })
411 .catch(err => logger.error('Cannot build the player', err))
413 this.setOpenGraphTags()
415 const hookOptions = {
418 playlist: this.playlist
420 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
423 private async buildPlayer (options: {
424 urlOptions: URLOptions
425 loggedInOrAnonymousUser: User
426 forceAutoplay: boolean
428 const { urlOptions, loggedInOrAnonymousUser, forceAutoplay } = options
430 // Flush old player if needed
433 const videoState = this.video.state.id
434 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
435 this.playerPlaceholderImgSrc = this.video.previewPath
439 // Build video element, because videojs removes it on dispose
440 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
441 this.playerElement = document.createElement('video')
442 this.playerElement.className = 'video-js vjs-peertube-skin'
443 this.playerElement.setAttribute('playsinline', 'true')
444 playerElementWrapper.appendChild(this.playerElement)
448 videoCaptions: this.videoCaptions,
449 liveVideo: this.liveVideo,
450 videoFileToken: this.videoFileToken,
452 loggedInOrAnonymousUser,
456 const { playerMode, playerOptions } = await this.hooks.wrapFun(
457 this.buildPlayerManagerOptions.bind(this),
460 'filter:internal.video-watch.player.build-options.params',
461 'filter:internal.video-watch.player.build-options.result'
464 this.zone.runOutsideAngular(async () => {
465 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
467 this.player.on('customError', (_e, data: any) => {
468 this.zone.run(() => this.handleGlobalError(data.err))
471 this.player.on('timeupdate', () => {
472 // Don't need to trigger angular change for this variable, that is sent to children components on click
473 this.currentTime = Math.floor(this.player.currentTime())
477 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
478 * go to the next video in 'condition()' if you don't want of the timer.
479 * next: function triggered at the end of the timer.
480 * suspended: function used at each click of the timer checking if we need to reset progress
481 * and wait until suspended becomes truthy again.
486 headText: $localize`Up Next`,
487 cancelText: $localize`Cancel`,
488 suspendedText: $localize`Autoplay is suspended`,
490 getTitle: () => this.nextVideoTitle,
492 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
494 if (!this.playlist) return this.isAutoPlayNext()
496 // Don't wait timeout to play the next playlist video
497 if (this.isPlaylistAutoPlayNext()) {
498 this.playNextVideoInAngularZone()
507 !isXPercentInViewport(this.player.el() as HTMLElement, 80) ||
508 !document.getElementById('content').contains(document.activeElement)
513 this.player.one('stopped', () => {
514 if (this.playlist && this.isPlaylistAutoPlayNext()) {
515 this.playNextVideoInAngularZone()
519 this.player.one('ended', () => {
520 if (this.video.isLive) {
521 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
525 this.player.on('theaterChange', (_: any, enabled: boolean) => {
526 this.zone.run(() => this.theaterEnabled = enabled)
529 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', {
531 playlist: this.playlist,
532 playlistPosition: this.playlistPosition,
539 private hasNextVideo () {
541 return this.videoWatchPlaylist.hasNextVideo()
547 private playNextVideoInAngularZone () {
549 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
553 if (this.nextVideoUUID) {
554 this.router.navigate([ '/w', this.nextVideoUUID ])
558 private isAutoplay () {
559 // We'll jump to the thread id, so do not play the video
560 if (this.route.snapshot.params['threadId']) return false
562 // Otherwise true by default
563 if (!this.user) return true
565 // Be sure the autoPlay is set to false
566 return this.user.autoPlayVideo !== false
569 private isAutoPlayNext () {
571 (this.user?.autoPlayNextVideo) ||
572 this.anonymousUser.autoPlayNextVideo
576 private isPlaylistAutoPlayNext () {
578 (this.user?.autoPlayNextVideoPlaylist) ||
579 this.anonymousUser.autoPlayNextVideoPlaylist
583 private flushPlayer () {
584 // Remove player if it exists
585 if (!this.player) return
588 this.player.dispose()
589 this.player = undefined
591 logger.error('Cannot dispose player.', err)
595 private buildPlayerManagerOptions (params: {
598 videoCaptions: VideoCaption[]
600 videoFileToken: string
602 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
604 loggedInOrAnonymousUser: User
605 forceAutoplay: boolean
606 user?: AuthUser // Keep for plugins
608 const { video, liveVideo, videoCaptions, videoFileToken, urlOptions, loggedInOrAnonymousUser, forceAutoplay } = params
610 const getStartTime = () => {
611 const byUrl = urlOptions.startTime !== undefined
612 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
613 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
615 if (byUrl) return timeToInt(urlOptions.startTime)
616 if (byHistory) return video.userHistory.currentTime
617 if (byLocalStorage) return byLocalStorage.duration
622 let startTime = getStartTime()
624 // If we are at the end of the video, reset the timer
625 if (video.duration - startTime <= 1) startTime = 0
627 const playerCaptions = videoCaptions.map(c => ({
628 label: c.language.label,
629 language: c.language.id,
630 src: environment.apiUrl + c.captionPath
633 const liveOptions = video.isLive
634 ? { latencyMode: liveVideo.latencyMode }
637 const options: PeertubePlayerManagerOptions = {
639 autoplay: this.isAutoplay(),
641 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
643 hasNextVideo: () => this.hasNextVideo(),
644 nextVideo: () => this.playNextVideoInAngularZone(),
646 playerElement: this.playerElement,
647 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
649 videoDuration: video.duration,
651 inactivityTimeout: 2500,
652 poster: video.previewUrl,
655 stopTime: urlOptions.stopTime,
656 controlBar: urlOptions.controlBar,
657 controls: urlOptions.controls,
658 muted: urlOptions.muted,
659 loop: urlOptions.loop,
660 subtitle: urlOptions.subtitle,
661 playbackRate: urlOptions.playbackRate,
663 peertubeLink: urlOptions.peertubeLink,
666 captions: videoCaptions.length !== 0,
668 embedUrl: video.embedUrl,
669 embedTitle: video.name,
670 instanceName: this.serverConfig.instance.name,
672 isLive: video.isLive,
675 language: this.localeId,
677 metricsUrl: environment.apiUrl + '/api/v1/metrics/playback',
679 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
680 ? this.videoService.getVideoViewUrl(video.uuid)
682 authorizationHeader: () => this.authService.getRequestHeaderValue(),
684 serverUrl: environment.originServerUrl || window.location.origin,
686 videoFileToken: () => videoFileToken,
687 requiresAuth: videoRequiresAuth(video),
689 videoCaptions: playerCaptions,
691 videoShortUUID: video.shortUUID,
692 videoUUID: video.uuid,
694 errorNotifier: (message: string) => this.notifier.error(message)
698 videoFiles: video.files
701 pluginsManager: this.pluginService.getPluginsManager()
704 // Only set this if we're in a playlist
706 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
708 options.common.previousVideo = () => {
709 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
715 if (urlOptions.playerMode) {
716 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
717 else mode = 'webtorrent'
719 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
720 else mode = 'webtorrent'
723 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
724 if (typeof TextEncoder === 'undefined') {
728 if (mode === 'p2p-media-loader') {
729 const hlsPlaylist = video.getHlsPlaylist()
731 const p2pMediaLoader = {
732 playlistUrl: hlsPlaylist.playlistUrl,
733 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
734 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
735 trackerAnnounce: video.trackerUrls,
736 videoFiles: hlsPlaylist.files
737 } as P2PMediaLoaderOptions
739 Object.assign(options, { p2pMediaLoader })
742 return { playerMode: mode, playerOptions: options }
745 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
746 if (!this.liveVideosSub) {
747 this.liveVideosSub = this.buildLiveEventsSubscription()
750 if (oldVideo && oldVideo.id !== newVideo.id) {
751 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
754 if (!newVideo.isLive) return
756 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
759 private buildLiveEventsSubscription () {
760 return this.peertubeSocket.getLiveVideosObservable()
761 .subscribe(({ type, payload }) => {
762 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
763 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
767 private handleLiveStateChange (newState: VideoState) {
768 if (newState !== VideoState.PUBLISHED) return
770 logger.info('Loading video after live update.')
772 const videoUUID = this.video.uuid
774 // Reset to force refresh the video
775 this.video = undefined
776 this.loadVideo({ videoId: videoUUID, forceAutoplay: true })
779 private handleLiveViewsChange (newViewers: number) {
781 logger.error('Cannot update video live views because video is no defined.')
785 logger.info('Updating live views.')
787 this.video.viewers = newViewers
790 private initHotkeys () {
792 // These hotkeys are managed by the player
793 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
794 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
795 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
797 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
799 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
800 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
802 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
803 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
805 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
806 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
808 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
809 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
811 new Hotkey('t', e => {
812 this.theaterEnabled = !this.theaterEnabled
814 }, undefined, $localize`Toggle theater mode`)
817 if (this.isUserLoggedIn()) {
818 this.hotkeys = this.hotkeys.concat([
819 new Hotkey('shift+s', () => {
820 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
821 else this.subscribeButton.subscribe()
824 }, undefined, $localize`Subscribe to the account`)
828 this.hotkeysService.add(this.hotkeys)
831 private setOpenGraphTags () {
832 this.metaService.setTitle(this.video.name)
834 this.metaService.setTag('og:type', 'video')
836 this.metaService.setTag('og:title', this.video.name)
837 this.metaService.setTag('name', this.video.name)
839 this.metaService.setTag('og:description', this.video.description)
840 this.metaService.setTag('description', this.video.description)
842 this.metaService.setTag('og:image', this.video.previewPath)
844 this.metaService.setTag('og:duration', this.video.duration.toString())
846 this.metaService.setTag('og:site_name', 'PeerTube')
848 this.metaService.setTag('og:url', window.location.href)
849 this.metaService.setTag('url', window.location.href)