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, 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 } 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 currentTime: number
83 private paramsSub: Subscription
84 private queryParamsSub: Subscription
85 private configSub: Subscription
86 private liveVideosSub: Subscription
88 private serverConfig: HTMLServerConfig
90 private hotkeys: Hotkey[] = []
93 private elementRef: ElementRef,
94 private route: ActivatedRoute,
95 private router: Router,
96 private videoService: VideoService,
97 private playlistService: VideoPlaylistService,
98 private liveVideoService: LiveVideoService,
99 private confirmService: ConfirmService,
100 private metaService: MetaService,
101 private authService: AuthService,
102 private userService: UserService,
103 private serverService: ServerService,
104 private restExtractor: RestExtractor,
105 private notifier: Notifier,
106 private zone: NgZone,
107 private videoCaptionService: VideoCaptionService,
108 private hotkeysService: HotkeysService,
109 private hooks: HooksService,
110 private pluginService: PluginService,
111 private peertubeSocket: PeerTubeSocket,
112 private screenService: ScreenService,
113 private location: PlatformLocation,
114 @Inject(LOCALE_ID) private localeId: string
118 return this.authService.getUser()
121 get anonymousUser () {
122 return this.userService.getAnonymousUser()
126 this.serverConfig = this.serverService.getHTMLConfig()
128 PeertubePlayerManager.initState()
130 this.loadRouteParams()
131 this.loadRouteQuery()
135 this.theaterEnabled = getStoredTheater()
137 this.hooks.runAction('action:video-watch.init', 'video-watch')
139 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
145 // Unsubscribe subscriptions
146 if (this.paramsSub) this.paramsSub.unsubscribe()
147 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
148 if (this.configSub) this.configSub.unsubscribe()
149 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
152 this.hotkeysService.remove(this.hotkeys)
156 return this.currentTime
159 getCurrentPlaylistPosition () {
160 return this.videoWatchPlaylist.currentPlaylistPosition
163 onRecommendations (videos: Video[]) {
164 if (videos.length === 0) return
166 // The recommended videos's first element should be the next video
167 const video = videos[0]
168 this.nextVideoUUID = video.uuid
169 this.nextVideoTitle = video.name
172 handleTimestampClicked (timestamp: number) {
173 if (!this.player || this.video.isLive) return
175 this.player.currentTime(timestamp)
179 onPlaylistVideoFound (videoId: string) {
180 this.loadVideo(videoId)
183 onPlaylistNoVideoFound () {
184 this.noPlaylistVideoFound = true
188 return this.authService.isLoggedIn()
191 isVideoBlur (video: Video) {
192 return video.isVideoNSFWForUser(this.user, this.serverConfig)
195 isChannelDisplayNameGeneric () {
196 const genericChannelDisplayName = [
197 `Main ${this.video.channel.ownerAccount.name} channel`,
198 `Default ${this.video.channel.ownerAccount.name} channel`
201 return genericChannelDisplayName.includes(this.video.channel.displayName)
204 displayOtherVideosAsRow () {
205 // Use the same value as in the SASS file
206 return this.screenService.getWindowInnerWidth() <= 1100
209 private loadRouteParams () {
210 this.paramsSub = this.route.params.subscribe(routeParams => {
211 const videoId = routeParams['videoId']
212 if (videoId) return this.loadVideo(videoId)
214 const playlistId = routeParams['playlistId']
215 if (playlistId) return this.loadPlaylist(playlistId)
219 private loadRouteQuery () {
220 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
221 // Handle the ?playlistPosition
222 const positionParam = queryParams['playlistPosition'] ?? 1
224 this.playlistPosition = positionParam === 'last'
225 ? -1 // Handle the "last" index
226 : parseInt(positionParam + '', 10)
228 if (isNaN(this.playlistPosition)) {
229 logger.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
230 this.playlistPosition = 1
233 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
235 const start = queryParams['start']
236 if (this.player && start) this.player.currentTime(parseInt(start, 10))
240 private loadVideo (videoId: string) {
241 if (this.isSameElement(this.video, videoId)) return
243 if (this.player) this.player.pause()
245 this.video = undefined
247 const videoObs = this.hooks.wrapObsFun(
248 this.videoService.getVideo.bind(this.videoService),
251 'filter:api.video-watch.video.get.params',
252 'filter:api.video-watch.video.get.result'
255 const videoAndLiveObs: Observable<{ video: VideoDetails, live?: LiveVideo }> = videoObs.pipe(
257 if (!video.isLive) return of({ video })
259 return this.liveVideoService.getVideoLive(video.uuid)
260 .pipe(map(live => ({ live, video })))
266 this.videoCaptionService.listCaptions(videoId),
267 this.userService.getAnonymousOrLoggedUser()
269 next: ([ { video, live }, captionsResult, loggedInOrAnonymousUser ]) => {
270 const queryParams = this.route.snapshot.queryParams
273 resume: queryParams.resume,
275 startTime: queryParams.start,
276 stopTime: queryParams.stop,
278 muted: queryParams.muted,
279 loop: queryParams.loop,
280 subtitle: queryParams.subtitle,
282 playerMode: queryParams.mode,
286 this.onVideoFetched({ video, live, videoCaptions: captionsResult.data, loggedInOrAnonymousUser, urlOptions })
287 .catch(err => this.handleGlobalError(err))
290 error: err => this.handleRequestError(err)
294 private loadPlaylist (playlistId: string) {
295 if (this.isSameElement(this.playlist, playlistId)) return
297 this.noPlaylistVideoFound = false
299 this.playlistService.getVideoPlaylist(playlistId)
302 this.playlist = playlist
304 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
307 error: err => this.handleRequestError(err)
311 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
312 if (!element) return false
314 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
317 private async handleRequestError (err: any) {
318 const errorBody = err.body as PeerTubeProblemDocument
320 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
321 const originUrl = errorBody.originUrl + (window.location.search ?? '')
323 const res = await this.confirmService.confirm(
324 // eslint-disable-next-line max-len
325 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
326 $localize`Redirection`
329 if (res === true) return window.location.href = originUrl
332 // If 400, 403 or 404, the video is private or blocked so redirect to 404
333 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
334 HttpStatusCode.BAD_REQUEST_400,
335 HttpStatusCode.FORBIDDEN_403,
336 HttpStatusCode.NOT_FOUND_404
340 private handleGlobalError (err: any) {
341 const errorMessage: string = typeof err === 'string' ? err : err.message
342 if (!errorMessage) return
344 // Display a message in the video player instead of a notification
345 if (errorMessage.includes('from xs param')) {
347 this.remoteServerDown = true
352 this.notifier.error(errorMessage)
355 private async onVideoFetched (options: {
358 videoCaptions: VideoCaption[]
359 urlOptions: URLOptions
360 loggedInOrAnonymousUser: User
362 const { video, live, videoCaptions, urlOptions, loggedInOrAnonymousUser } = options
364 this.subscribeToLiveEventsIfNeeded(this.video, video)
367 this.videoCaptions = videoCaptions
368 this.liveVideo = live
370 // Re init attributes
371 this.playerPlaceholderImgSrc = undefined
372 this.remoteServerDown = false
373 this.currentTime = undefined
375 if (this.isVideoBlur(this.video)) {
376 const res = await this.confirmService.confirm(
377 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
378 $localize`Mature or explicit content`
380 if (res === false) return this.location.back()
383 this.buildPlayer(urlOptions, loggedInOrAnonymousUser)
384 .catch(err => logger.error('Cannot build the player', err))
386 this.setOpenGraphTags()
388 const hookOptions = {
391 playlist: this.playlist
393 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
396 private async buildPlayer (urlOptions: URLOptions, loggedInOrAnonymousUser: User) {
397 // Flush old player if needed
400 const videoState = this.video.state.id
401 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
402 this.playerPlaceholderImgSrc = this.video.previewPath
406 // Build video element, because videojs removes it on dispose
407 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
408 this.playerElement = document.createElement('video')
409 this.playerElement.className = 'video-js vjs-peertube-skin'
410 this.playerElement.setAttribute('playsinline', 'true')
411 playerElementWrapper.appendChild(this.playerElement)
415 videoCaptions: this.videoCaptions,
416 liveVideo: this.liveVideo,
418 loggedInOrAnonymousUser,
421 const { playerMode, playerOptions } = await this.hooks.wrapFun(
422 this.buildPlayerManagerOptions.bind(this),
425 'filter:internal.video-watch.player.build-options.params',
426 'filter:internal.video-watch.player.build-options.result'
429 this.zone.runOutsideAngular(async () => {
430 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
432 this.player.on('customError', (_e, data: any) => {
433 this.zone.run(() => this.handleGlobalError(data.err))
436 this.player.on('timeupdate', () => {
437 // Don't need to trigger angular change for this variable, that is sent to children components on click
438 this.currentTime = Math.floor(this.player.currentTime())
442 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
443 * go to the next video in 'condition()' if you don't want of the timer.
444 * next: function triggered at the end of the timer.
445 * suspended: function used at each click of the timer checking if we need to reset progress
446 * and wait until suspended becomes truthy again.
451 headText: $localize`Up Next`,
452 cancelText: $localize`Cancel`,
453 suspendedText: $localize`Autoplay is suspended`,
455 getTitle: () => this.nextVideoTitle,
457 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
459 if (!this.playlist) return this.isAutoPlayNext()
461 // Don't wait timeout to play the next playlist video
462 if (this.isPlaylistAutoPlayNext()) {
463 this.playNextVideoInAngularZone()
472 !isXPercentInViewport(this.player.el() as HTMLElement, 80) ||
473 !document.getElementById('content').contains(document.activeElement)
478 this.player.one('stopped', () => {
479 if (this.playlist && this.isPlaylistAutoPlayNext()) {
480 this.playNextVideoInAngularZone()
484 this.player.one('ended', () => {
485 if (this.video.isLive) {
486 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
490 this.player.on('theaterChange', (_: any, enabled: boolean) => {
491 this.zone.run(() => this.theaterEnabled = enabled)
494 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', {
496 playlist: this.playlist,
497 playlistPosition: this.playlistPosition,
504 private hasNextVideo () {
506 return this.videoWatchPlaylist.hasNextVideo()
512 private playNextVideoInAngularZone () {
514 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
518 if (this.nextVideoUUID) {
519 this.router.navigate([ '/w', this.nextVideoUUID ])
523 private isAutoplay () {
524 // We'll jump to the thread id, so do not play the video
525 if (this.route.snapshot.params['threadId']) return false
527 // Otherwise true by default
528 if (!this.user) return true
530 // Be sure the autoPlay is set to false
531 return this.user.autoPlayVideo !== false
534 private isAutoPlayNext () {
536 (this.user?.autoPlayNextVideo) ||
537 this.anonymousUser.autoPlayNextVideo
541 private isPlaylistAutoPlayNext () {
543 (this.user?.autoPlayNextVideoPlaylist) ||
544 this.anonymousUser.autoPlayNextVideoPlaylist
548 private flushPlayer () {
549 // Remove player if it exists
550 if (!this.player) return
553 this.player.dispose()
554 this.player = undefined
556 logger.error('Cannot dispose player.', err)
560 private buildPlayerManagerOptions (params: {
563 videoCaptions: VideoCaption[]
564 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
565 loggedInOrAnonymousUser: User
566 user?: AuthUser // Keep for plugins
568 const { video, liveVideo, videoCaptions, urlOptions, loggedInOrAnonymousUser } = params
570 const getStartTime = () => {
571 const byUrl = urlOptions.startTime !== undefined
572 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
573 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
575 if (byUrl) return timeToInt(urlOptions.startTime)
576 if (byHistory) return video.userHistory.currentTime
577 if (byLocalStorage) return byLocalStorage.duration
582 let startTime = getStartTime()
584 // If we are at the end of the video, reset the timer
585 if (video.duration - startTime <= 1) startTime = 0
587 const playerCaptions = videoCaptions.map(c => ({
588 label: c.language.label,
589 language: c.language.id,
590 src: environment.apiUrl + c.captionPath
593 const liveOptions = video.isLive
594 ? { latencyMode: liveVideo.latencyMode }
597 const options: PeertubePlayerManagerOptions = {
599 autoplay: this.isAutoplay(),
600 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
602 hasNextVideo: () => this.hasNextVideo(),
603 nextVideo: () => this.playNextVideoInAngularZone(),
605 playerElement: this.playerElement,
606 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
608 videoDuration: video.duration,
610 inactivityTimeout: 2500,
611 poster: video.previewUrl,
614 stopTime: urlOptions.stopTime,
615 controlBar: urlOptions.controlBar,
616 controls: urlOptions.controls,
617 muted: urlOptions.muted,
618 loop: urlOptions.loop,
619 subtitle: urlOptions.subtitle,
621 peertubeLink: urlOptions.peertubeLink,
624 captions: videoCaptions.length !== 0,
626 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
627 ? this.videoService.getVideoViewUrl(video.uuid)
629 authorizationHeader: this.authService.getRequestHeaderValue(),
631 metricsUrl: environment.apiUrl + '/api/v1/metrics/playback',
633 embedUrl: video.embedUrl,
634 embedTitle: video.name,
635 instanceName: this.serverConfig.instance.name,
637 isLive: video.isLive,
640 language: this.localeId,
642 serverUrl: environment.apiUrl,
644 videoCaptions: playerCaptions,
646 videoShortUUID: video.shortUUID,
647 videoUUID: video.uuid,
649 errorNotifier: (message: string) => this.notifier.error(message)
653 videoFiles: video.files
656 pluginsManager: this.pluginService.getPluginsManager()
659 // Only set this if we're in a playlist
661 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
663 options.common.previousVideo = () => {
664 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
670 if (urlOptions.playerMode) {
671 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
672 else mode = 'webtorrent'
674 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
675 else mode = 'webtorrent'
678 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
679 if (typeof TextEncoder === 'undefined') {
683 if (mode === 'p2p-media-loader') {
684 const hlsPlaylist = video.getHlsPlaylist()
686 const p2pMediaLoader = {
687 playlistUrl: hlsPlaylist.playlistUrl,
688 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
689 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
690 trackerAnnounce: video.trackerUrls,
691 videoFiles: hlsPlaylist.files
692 } as P2PMediaLoaderOptions
694 Object.assign(options, { p2pMediaLoader })
697 return { playerMode: mode, playerOptions: options }
700 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
701 if (!this.liveVideosSub) {
702 this.liveVideosSub = this.buildLiveEventsSubscription()
705 if (oldVideo && oldVideo.id !== newVideo.id) {
706 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
709 if (!newVideo.isLive) return
711 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
714 private buildLiveEventsSubscription () {
715 return this.peertubeSocket.getLiveVideosObservable()
716 .subscribe(({ type, payload }) => {
717 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
718 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
722 private handleLiveStateChange (newState: VideoState) {
723 if (newState !== VideoState.PUBLISHED) return
725 logger.info('Loading video after live update.')
727 const videoUUID = this.video.uuid
729 // Reset to force refresh the video
730 this.video = undefined
731 this.loadVideo(videoUUID)
734 private handleLiveViewsChange (newViewers: number) {
736 logger.error('Cannot update video live views because video is no defined.')
740 logger.info('Updating live views.')
742 this.video.viewers = newViewers
745 private initHotkeys () {
747 // These hotkeys are managed by the player
748 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
749 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
750 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
752 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
754 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
755 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
757 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
758 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
760 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
761 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
763 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
764 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
766 new Hotkey('t', e => {
767 this.theaterEnabled = !this.theaterEnabled
769 }, undefined, $localize`Toggle theater mode`)
772 if (this.isUserLoggedIn()) {
773 this.hotkeys = this.hotkeys.concat([
774 new Hotkey('shift+s', () => {
775 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
776 else this.subscribeButton.subscribe()
779 }, undefined, $localize`Subscribe to the account`)
783 this.hotkeysService.add(this.hotkeys)
786 private setOpenGraphTags () {
787 this.metaService.setTitle(this.video.name)
789 this.metaService.setTag('og:type', 'video')
791 this.metaService.setTag('og:title', this.video.name)
792 this.metaService.setTag('name', this.video.name)
794 this.metaService.setTag('og:description', this.video.description)
795 this.metaService.setTag('description', this.video.description)
797 this.metaService.setTag('og:image', this.video.previewPath)
799 this.metaService.setTag('og:duration', this.video.duration.toString())
801 this.metaService.setTag('og:site_name', 'PeerTube')
803 this.metaService.setTag('og:url', window.location.href)
804 this.metaService.setTag('url', window.location.href)