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 { isP2PEnabled } from '@root-helpers/video'
28 import { timeToInt } from '@shared/core-utils'
33 PeerTubeProblemDocument,
38 } from '@shared/models'
41 P2PMediaLoaderOptions,
42 PeertubePlayerManager,
43 PeertubePlayerManagerOptions,
46 } from '../../../assets/player'
47 import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage'
48 import { environment } from '../../../environments/environment'
49 import { VideoWatchPlaylistComponent } from './shared'
51 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
54 selector: 'my-video-watch',
55 templateUrl: './video-watch.component.html',
56 styleUrls: [ './video-watch.component.scss' ]
58 export class VideoWatchComponent implements OnInit, OnDestroy {
59 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
60 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
63 playerElement: HTMLVideoElement
64 playerPlaceholderImgSrc: string
65 theaterEnabled = false
67 video: VideoDetails = null
68 videoCaptions: VideoCaption[] = []
71 playlistPosition: number
72 playlist: VideoPlaylist = null
74 remoteServerDown = false
76 private nextVideoUUID = ''
77 private nextVideoTitle = ''
79 private currentTime: number
81 private paramsSub: Subscription
82 private queryParamsSub: Subscription
83 private configSub: Subscription
84 private liveVideosSub: Subscription
86 private serverConfig: HTMLServerConfig
88 private hotkeys: Hotkey[] = []
91 private elementRef: ElementRef,
92 private route: ActivatedRoute,
93 private router: Router,
94 private videoService: VideoService,
95 private playlistService: VideoPlaylistService,
96 private liveVideoService: LiveVideoService,
97 private confirmService: ConfirmService,
98 private metaService: MetaService,
99 private authService: AuthService,
100 private userService: UserService,
101 private serverService: ServerService,
102 private restExtractor: RestExtractor,
103 private notifier: Notifier,
104 private zone: NgZone,
105 private videoCaptionService: VideoCaptionService,
106 private hotkeysService: HotkeysService,
107 private hooks: HooksService,
108 private pluginService: PluginService,
109 private peertubeSocket: PeerTubeSocket,
110 private screenService: ScreenService,
111 private location: PlatformLocation,
112 @Inject(LOCALE_ID) private localeId: string
116 return this.authService.getUser()
119 get anonymousUser () {
120 return this.userService.getAnonymousUser()
124 this.serverConfig = this.serverService.getHTMLConfig()
126 PeertubePlayerManager.initState()
128 this.loadRouteParams()
129 this.loadRouteQuery()
133 this.theaterEnabled = getStoredTheater()
135 this.hooks.runAction('action:video-watch.init', 'video-watch')
137 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
143 // Unsubscribe subscriptions
144 if (this.paramsSub) this.paramsSub.unsubscribe()
145 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
146 if (this.configSub) this.configSub.unsubscribe()
147 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
150 this.hotkeysService.remove(this.hotkeys)
154 return this.currentTime
157 getCurrentPlaylistPosition () {
158 return this.videoWatchPlaylist.currentPlaylistPosition
161 onRecommendations (videos: Video[]) {
162 if (videos.length === 0) return
164 // The recommended videos's first element should be the next video
165 const video = videos[0]
166 this.nextVideoUUID = video.uuid
167 this.nextVideoTitle = video.name
170 handleTimestampClicked (timestamp: number) {
171 if (!this.player || this.video.isLive) return
173 this.player.currentTime(timestamp)
177 onPlaylistVideoFound (videoId: string) {
178 this.loadVideo(videoId)
182 return this.authService.isLoggedIn()
185 isVideoBlur (video: Video) {
186 return video.isVideoNSFWForUser(this.user, this.serverConfig)
189 isChannelDisplayNameGeneric () {
190 const genericChannelDisplayName = [
191 `Main ${this.video.channel.ownerAccount.name} channel`,
192 `Default ${this.video.channel.ownerAccount.name} channel`
195 return genericChannelDisplayName.includes(this.video.channel.displayName)
198 displayOtherVideosAsRow () {
199 // Use the same value as in the SASS file
200 return this.screenService.getWindowInnerWidth() <= 1100
203 private loadRouteParams () {
204 this.paramsSub = this.route.params.subscribe(routeParams => {
205 const videoId = routeParams['videoId']
206 if (videoId) return this.loadVideo(videoId)
208 const playlistId = routeParams['playlistId']
209 if (playlistId) return this.loadPlaylist(playlistId)
213 private loadRouteQuery () {
214 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
215 // Handle the ?playlistPosition
216 const positionParam = queryParams['playlistPosition'] ?? 1
218 this.playlistPosition = positionParam === 'last'
219 ? -1 // Handle the "last" index
220 : parseInt(positionParam + '', 10)
222 if (isNaN(this.playlistPosition)) {
223 console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
224 this.playlistPosition = 1
227 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
229 const start = queryParams['start']
230 if (this.player && start) this.player.currentTime(parseInt(start, 10))
234 private loadVideo (videoId: string) {
235 if (this.isSameElement(this.video, videoId)) return
237 if (this.player) this.player.pause()
239 const videoObs = this.hooks.wrapObsFun(
240 this.videoService.getVideo.bind(this.videoService),
243 'filter:api.video-watch.video.get.params',
244 'filter:api.video-watch.video.get.result'
247 const videoAndLiveObs: Observable<{ video: VideoDetails, live?: LiveVideo }> = videoObs.pipe(
249 if (!video.isLive) return of({ video })
251 return this.liveVideoService.getVideoLive(video.uuid)
252 .pipe(map(live => ({ live, video })))
258 this.videoCaptionService.listCaptions(videoId),
259 this.userService.getAnonymousOrLoggedUser()
261 next: ([ { video, live }, captionsResult, loggedInOrAnonymousUser ]) => {
262 const queryParams = this.route.snapshot.queryParams
265 resume: queryParams.resume,
267 startTime: queryParams.start,
268 stopTime: queryParams.stop,
270 muted: queryParams.muted,
271 loop: queryParams.loop,
272 subtitle: queryParams.subtitle,
274 playerMode: queryParams.mode,
278 this.onVideoFetched({ video, live, videoCaptions: captionsResult.data, loggedInOrAnonymousUser, urlOptions })
279 .catch(err => this.handleGlobalError(err))
282 error: err => this.handleRequestError(err)
286 private loadPlaylist (playlistId: string) {
287 if (this.isSameElement(this.playlist, playlistId)) return
289 this.playlistService.getVideoPlaylist(playlistId)
292 this.playlist = playlist
294 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
297 error: err => this.handleRequestError(err)
301 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
302 if (!element) return false
304 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
307 private async handleRequestError (err: any) {
308 const errorBody = err.body as PeerTubeProblemDocument
310 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
311 const originUrl = errorBody.originUrl + (window.location.search ?? '')
313 const res = await this.confirmService.confirm(
314 // eslint-disable-next-line max-len
315 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
316 $localize`Redirection`
319 if (res === true) return window.location.href = originUrl
322 // If 400, 403 or 404, the video is private or blocked so redirect to 404
323 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
324 HttpStatusCode.BAD_REQUEST_400,
325 HttpStatusCode.FORBIDDEN_403,
326 HttpStatusCode.NOT_FOUND_404
330 private handleGlobalError (err: any) {
331 const errorMessage: string = typeof err === 'string' ? err : err.message
332 if (!errorMessage) return
334 // Display a message in the video player instead of a notification
335 if (errorMessage.includes('from xs param')) {
337 this.remoteServerDown = true
342 this.notifier.error(errorMessage)
345 private async onVideoFetched (options: {
348 videoCaptions: VideoCaption[]
349 urlOptions: URLOptions
350 loggedInOrAnonymousUser: User
352 const { video, live, videoCaptions, urlOptions, loggedInOrAnonymousUser } = options
354 this.subscribeToLiveEventsIfNeeded(this.video, video)
357 this.videoCaptions = videoCaptions
358 this.liveVideo = live
360 // Re init attributes
361 this.playerPlaceholderImgSrc = undefined
362 this.remoteServerDown = false
363 this.currentTime = undefined
365 if (this.isVideoBlur(this.video)) {
366 const res = await this.confirmService.confirm(
367 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
368 $localize`Mature or explicit content`
370 if (res === false) return this.location.back()
373 this.buildPlayer(urlOptions, loggedInOrAnonymousUser)
374 .catch(err => console.error('Cannot build the player', err))
376 this.setOpenGraphTags()
378 const hookOptions = {
381 playlist: this.playlist
383 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
386 private async buildPlayer (urlOptions: URLOptions, loggedInOrAnonymousUser: User) {
387 // Flush old player if needed
390 const videoState = this.video.state.id
391 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
392 this.playerPlaceholderImgSrc = this.video.previewPath
396 // Build video element, because videojs removes it on dispose
397 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
398 this.playerElement = document.createElement('video')
399 this.playerElement.className = 'video-js vjs-peertube-skin'
400 this.playerElement.setAttribute('playsinline', 'true')
401 playerElementWrapper.appendChild(this.playerElement)
405 videoCaptions: this.videoCaptions,
406 liveVideo: this.liveVideo,
408 loggedInOrAnonymousUser,
411 const { playerMode, playerOptions } = await this.hooks.wrapFun(
412 this.buildPlayerManagerOptions.bind(this),
415 'filter:internal.video-watch.player.build-options.params',
416 'filter:internal.video-watch.player.build-options.result'
419 this.zone.runOutsideAngular(async () => {
420 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
422 this.player.on('customError', (_e, data: any) => {
423 this.zone.run(() => this.handleGlobalError(data.err))
426 this.player.on('timeupdate', () => {
427 // Don't need to trigger angular change for this variable, that is sent to children components on click
428 this.currentTime = Math.floor(this.player.currentTime())
432 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
433 * go to the next video in 'condition()' if you don't want of the timer.
434 * next: function triggered at the end of the timer.
435 * suspended: function used at each click of the timer checking if we need to reset progress
436 * and wait until suspended becomes truthy again.
441 headText: $localize`Up Next`,
442 cancelText: $localize`Cancel`,
443 suspendedText: $localize`Autoplay is suspended`,
445 getTitle: () => this.nextVideoTitle,
447 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
449 if (!this.playlist) return this.isAutoPlayNext()
451 // Don't wait timeout to play the next playlist video
452 if (this.isPlaylistAutoPlayNext()) {
453 this.playNextVideoInAngularZone()
462 !isXPercentInViewport(this.player.el() as HTMLElement, 80) ||
463 !document.getElementById('content').contains(document.activeElement)
468 this.player.one('stopped', () => {
469 if (this.playlist && this.isPlaylistAutoPlayNext()) {
470 this.playNextVideoInAngularZone()
474 this.player.one('ended', () => {
475 if (this.video.isLive) {
476 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
480 this.player.on('theaterChange', (_: any, enabled: boolean) => {
481 this.zone.run(() => this.theaterEnabled = enabled)
484 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', {
486 playlist: this.playlist,
487 playlistPosition: this.playlistPosition,
494 private hasNextVideo () {
496 return this.videoWatchPlaylist.hasNextVideo()
502 private playNextVideoInAngularZone () {
504 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
508 if (this.nextVideoUUID) {
509 this.router.navigate([ '/w', this.nextVideoUUID ])
513 private isAutoplay () {
514 // We'll jump to the thread id, so do not play the video
515 if (this.route.snapshot.params['threadId']) return false
517 // Otherwise true by default
518 if (!this.user) return true
520 // Be sure the autoPlay is set to false
521 return this.user.autoPlayVideo !== false
524 private isAutoPlayNext () {
526 (this.user?.autoPlayNextVideo) ||
527 this.anonymousUser.autoPlayNextVideo
531 private isPlaylistAutoPlayNext () {
533 (this.user?.autoPlayNextVideoPlaylist) ||
534 this.anonymousUser.autoPlayNextVideoPlaylist
538 private flushPlayer () {
539 // Remove player if it exists
540 if (!this.player) return
543 this.player.dispose()
544 this.player = undefined
546 console.error('Cannot dispose player.', err)
550 private buildPlayerManagerOptions (params: {
553 videoCaptions: VideoCaption[]
554 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
555 loggedInOrAnonymousUser: User
558 const { video, liveVideo, videoCaptions, urlOptions, loggedInOrAnonymousUser, user } = params
560 const getStartTime = () => {
561 const byUrl = urlOptions.startTime !== undefined
562 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
563 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
565 if (byUrl) return timeToInt(urlOptions.startTime)
566 if (byHistory) return video.userHistory.currentTime
567 if (byLocalStorage) return byLocalStorage.duration
572 let startTime = getStartTime()
574 // If we are at the end of the video, reset the timer
575 if (video.duration - startTime <= 1) startTime = 0
577 const playerCaptions = videoCaptions.map(c => ({
578 label: c.language.label,
579 language: c.language.id,
580 src: environment.apiUrl + c.captionPath
583 const liveOptions = video.isLive
584 ? { latencyMode: liveVideo.latencyMode }
587 const options: PeertubePlayerManagerOptions = {
589 autoplay: this.isAutoplay(),
590 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
592 hasNextVideo: () => this.hasNextVideo(),
593 nextVideo: () => this.playNextVideoInAngularZone(),
595 playerElement: this.playerElement,
596 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
598 videoDuration: video.duration,
600 inactivityTimeout: 2500,
601 poster: video.previewUrl,
604 stopTime: urlOptions.stopTime,
605 controls: urlOptions.controls,
606 muted: urlOptions.muted,
607 loop: urlOptions.loop,
608 subtitle: urlOptions.subtitle,
610 peertubeLink: urlOptions.peertubeLink,
613 captions: videoCaptions.length !== 0,
615 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
616 ? this.videoService.getVideoViewUrl(video.uuid)
618 embedUrl: video.embedUrl,
619 embedTitle: video.name,
621 isLive: video.isLive,
624 language: this.localeId,
626 userWatching: user && user.videosHistoryEnabled === true
628 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
629 authorizationHeader: this.authService.getRequestHeaderValue()
633 serverUrl: environment.apiUrl,
635 videoCaptions: playerCaptions,
637 videoShortUUID: video.shortUUID,
638 videoUUID: video.uuid,
640 errorNotifier: (message: string) => this.notifier.error(message)
644 videoFiles: video.files
647 pluginsManager: this.pluginService.getPluginsManager()
650 // Only set this if we're in a playlist
652 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
654 options.common.previousVideo = () => {
655 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
661 if (urlOptions.playerMode) {
662 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
663 else mode = 'webtorrent'
665 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
666 else mode = 'webtorrent'
669 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
670 if (typeof TextEncoder === 'undefined') {
674 if (mode === 'p2p-media-loader') {
675 const hlsPlaylist = video.getHlsPlaylist()
677 const p2pMediaLoader = {
678 playlistUrl: hlsPlaylist.playlistUrl,
679 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
680 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
681 trackerAnnounce: video.trackerUrls,
682 videoFiles: hlsPlaylist.files
683 } as P2PMediaLoaderOptions
685 Object.assign(options, { p2pMediaLoader })
688 return { playerMode: mode, playerOptions: options }
691 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
692 if (!this.liveVideosSub) {
693 this.liveVideosSub = this.buildLiveEventsSubscription()
696 if (oldVideo && oldVideo.id !== newVideo.id) {
697 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
700 if (!newVideo.isLive) return
702 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
705 private buildLiveEventsSubscription () {
706 return this.peertubeSocket.getLiveVideosObservable()
707 .subscribe(({ type, payload }) => {
708 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
709 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
713 private handleLiveStateChange (newState: VideoState) {
714 if (newState !== VideoState.PUBLISHED) return
716 console.log('Loading video after live update.')
718 const videoUUID = this.video.uuid
720 // Reset to force refresh the video
721 this.video = undefined
722 this.loadVideo(videoUUID)
725 private handleLiveViewsChange (newViewers: number) {
727 console.error('Cannot update video live views because video is no defined.')
731 console.log('Updating live views.')
733 this.video.viewers = newViewers
736 private initHotkeys () {
738 // These hotkeys are managed by the player
739 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
740 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
741 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
743 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
745 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
746 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
748 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
749 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
751 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
752 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
754 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
755 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
757 new Hotkey('t', e => {
758 this.theaterEnabled = !this.theaterEnabled
760 }, undefined, $localize`Toggle theater mode`)
763 if (this.isUserLoggedIn()) {
764 this.hotkeys = this.hotkeys.concat([
765 new Hotkey('shift+s', () => {
766 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
767 else this.subscribeButton.subscribe()
770 }, undefined, $localize`Subscribe to the account`)
774 this.hotkeysService.add(this.hotkeys)
777 private setOpenGraphTags () {
778 this.metaService.setTitle(this.video.name)
780 this.metaService.setTag('og:type', 'video')
782 this.metaService.setTag('og:title', this.video.name)
783 this.metaService.setTag('name', this.video.name)
785 this.metaService.setTag('og:description', this.video.description)
786 this.metaService.setTag('description', this.video.description)
788 this.metaService.setTag('og:image', this.video.previewPath)
790 this.metaService.setTag('og:duration', this.video.duration.toString())
792 this.metaService.setTag('og:site_name', 'PeerTube')
794 this.metaService.setTag('og:url', window.location.href)
795 this.metaService.setTag('url', window.location.href)