1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, Subscription } from 'rxjs'
3 import { isP2PEnabled } from 'src/assets/player/utils'
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 { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
26 import { timeToInt } from '@shared/core-utils'
30 PeerTubeProblemDocument,
35 } from '@shared/models'
36 import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage'
39 P2PMediaLoaderOptions,
40 PeertubePlayerManager,
41 PeertubePlayerManagerOptions,
44 } from '../../../assets/player/peertube-player-manager'
45 import { environment } from '../../../environments/environment'
46 import { VideoWatchPlaylistComponent } from './shared'
48 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
51 selector: 'my-video-watch',
52 templateUrl: './video-watch.component.html',
53 styleUrls: [ './video-watch.component.scss' ]
55 export class VideoWatchComponent implements OnInit, OnDestroy {
56 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
57 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
60 playerElement: HTMLVideoElement
61 playerPlaceholderImgSrc: string
62 theaterEnabled = false
64 video: VideoDetails = null
65 videoCaptions: VideoCaption[] = []
67 playlistPosition: number
68 playlist: VideoPlaylist = null
70 remoteServerDown = false
72 private nextVideoUUID = ''
73 private nextVideoTitle = ''
75 private currentTime: number
77 private paramsSub: Subscription
78 private queryParamsSub: Subscription
79 private configSub: Subscription
80 private liveVideosSub: Subscription
82 private serverConfig: HTMLServerConfig
84 private hotkeys: Hotkey[] = []
87 private elementRef: ElementRef,
88 private route: ActivatedRoute,
89 private router: Router,
90 private videoService: VideoService,
91 private playlistService: VideoPlaylistService,
92 private confirmService: ConfirmService,
93 private metaService: MetaService,
94 private authService: AuthService,
95 private userService: UserService,
96 private serverService: ServerService,
97 private restExtractor: RestExtractor,
98 private notifier: Notifier,
100 private videoCaptionService: VideoCaptionService,
101 private hotkeysService: HotkeysService,
102 private hooks: HooksService,
103 private pluginService: PluginService,
104 private peertubeSocket: PeerTubeSocket,
105 private screenService: ScreenService,
106 private location: PlatformLocation,
107 @Inject(LOCALE_ID) private localeId: string
111 return this.authService.getUser()
114 get anonymousUser () {
115 return this.userService.getAnonymousUser()
119 this.serverConfig = this.serverService.getHTMLConfig()
121 PeertubePlayerManager.initState()
123 this.loadRouteParams()
124 this.loadRouteQuery()
128 this.theaterEnabled = getStoredTheater()
130 this.hooks.runAction('action:video-watch.init', 'video-watch')
132 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
138 // Unsubscribe subscriptions
139 if (this.paramsSub) this.paramsSub.unsubscribe()
140 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
141 if (this.configSub) this.configSub.unsubscribe()
142 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
145 this.hotkeysService.remove(this.hotkeys)
149 return this.currentTime
152 getCurrentPlaylistPosition () {
153 return this.videoWatchPlaylist.currentPlaylistPosition
156 onRecommendations (videos: Video[]) {
157 if (videos.length === 0) return
159 // The recommended videos's first element should be the next video
160 const video = videos[0]
161 this.nextVideoUUID = video.uuid
162 this.nextVideoTitle = video.name
165 handleTimestampClicked (timestamp: number) {
166 if (!this.player || this.video.isLive) return
168 this.player.currentTime(timestamp)
172 onPlaylistVideoFound (videoId: string) {
173 this.loadVideo(videoId)
177 return this.authService.isLoggedIn()
180 isVideoBlur (video: Video) {
181 return video.isVideoNSFWForUser(this.user, this.serverConfig)
184 isChannelDisplayNameGeneric () {
185 const genericChannelDisplayName = [
186 `Main ${this.video.channel.ownerAccount.name} channel`,
187 `Default ${this.video.channel.ownerAccount.name} channel`
190 return genericChannelDisplayName.includes(this.video.channel.displayName)
193 displayOtherVideosAsRow () {
194 // Use the same value as in the SASS file
195 return this.screenService.getWindowInnerWidth() <= 1100
198 private loadRouteParams () {
199 this.paramsSub = this.route.params.subscribe(routeParams => {
200 const videoId = routeParams['videoId']
201 if (videoId) return this.loadVideo(videoId)
203 const playlistId = routeParams['playlistId']
204 if (playlistId) return this.loadPlaylist(playlistId)
208 private loadRouteQuery () {
209 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
210 // Handle the ?playlistPosition
211 const positionParam = queryParams['playlistPosition'] ?? 1
213 this.playlistPosition = positionParam === 'last'
214 ? -1 // Handle the "last" index
215 : parseInt(positionParam + '', 10)
217 if (isNaN(this.playlistPosition)) {
218 console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
219 this.playlistPosition = 1
222 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
224 const start = queryParams['start']
225 if (this.player && start) this.player.currentTime(parseInt(start, 10))
229 private loadVideo (videoId: string) {
230 if (this.isSameElement(this.video, videoId)) return
232 if (this.player) this.player.pause()
234 const videoObs = this.hooks.wrapObsFun(
235 this.videoService.getVideo.bind(this.videoService),
238 'filter:api.video-watch.video.get.params',
239 'filter:api.video-watch.video.get.result'
244 this.videoCaptionService.listCaptions(videoId),
245 this.userService.getAnonymousOrLoggedUser()
247 next: ([ video, captionsResult, loggedInOrAnonymousUser ]) => {
248 const queryParams = this.route.snapshot.queryParams
251 resume: queryParams.resume,
253 startTime: queryParams.start,
254 stopTime: queryParams.stop,
256 muted: queryParams.muted,
257 loop: queryParams.loop,
258 subtitle: queryParams.subtitle,
260 playerMode: queryParams.mode,
264 this.onVideoFetched({ video, videoCaptions: captionsResult.data, loggedInOrAnonymousUser, urlOptions })
265 .catch(err => this.handleGlobalError(err))
268 error: err => this.handleRequestError(err)
272 private loadPlaylist (playlistId: string) {
273 if (this.isSameElement(this.playlist, playlistId)) return
275 this.playlistService.getVideoPlaylist(playlistId)
278 this.playlist = playlist
280 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
283 error: err => this.handleRequestError(err)
287 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
288 if (!element) return false
290 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
293 private async handleRequestError (err: any) {
294 const errorBody = err.body as PeerTubeProblemDocument
296 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
297 const originUrl = errorBody.originUrl + (window.location.search ?? '')
299 const res = await this.confirmService.confirm(
300 // eslint-disable-next-line max-len
301 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
302 $localize`Redirection`
305 if (res === true) return window.location.href = originUrl
308 // If 400, 403 or 404, the video is private or blocked so redirect to 404
309 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
310 HttpStatusCode.BAD_REQUEST_400,
311 HttpStatusCode.FORBIDDEN_403,
312 HttpStatusCode.NOT_FOUND_404
316 private handleGlobalError (err: any) {
317 const errorMessage: string = typeof err === 'string' ? err : err.message
318 if (!errorMessage) return
320 // Display a message in the video player instead of a notification
321 if (errorMessage.includes('from xs param')) {
323 this.remoteServerDown = true
328 this.notifier.error(errorMessage)
331 private async onVideoFetched (options: {
333 videoCaptions: VideoCaption[]
334 urlOptions: URLOptions
335 loggedInOrAnonymousUser: User
337 const { video, videoCaptions, urlOptions, loggedInOrAnonymousUser } = options
339 this.subscribeToLiveEventsIfNeeded(this.video, video)
342 this.videoCaptions = videoCaptions
344 // Re init attributes
345 this.playerPlaceholderImgSrc = undefined
346 this.remoteServerDown = false
347 this.currentTime = undefined
349 if (this.isVideoBlur(this.video)) {
350 const res = await this.confirmService.confirm(
351 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
352 $localize`Mature or explicit content`
354 if (res === false) return this.location.back()
357 this.buildPlayer(urlOptions, loggedInOrAnonymousUser)
358 .catch(err => console.error('Cannot build the player', err))
360 this.setOpenGraphTags()
362 const hookOptions = {
365 playlist: this.playlist
367 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
370 private async buildPlayer (urlOptions: URLOptions, loggedInOrAnonymousUser: User) {
371 // Flush old player if needed
374 const videoState = this.video.state.id
375 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
376 this.playerPlaceholderImgSrc = this.video.previewPath
380 // Build video element, because videojs removes it on dispose
381 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
382 this.playerElement = document.createElement('video')
383 this.playerElement.className = 'video-js vjs-peertube-skin'
384 this.playerElement.setAttribute('playsinline', 'true')
385 playerElementWrapper.appendChild(this.playerElement)
389 videoCaptions: this.videoCaptions,
391 loggedInOrAnonymousUser,
394 const { playerMode, playerOptions } = await this.hooks.wrapFun(
395 this.buildPlayerManagerOptions.bind(this),
398 'filter:internal.video-watch.player.build-options.params',
399 'filter:internal.video-watch.player.build-options.result'
402 this.zone.runOutsideAngular(async () => {
403 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
405 this.player.on('customError', ({ err }: { err: any }) => {
406 this.zone.run(() => this.handleGlobalError(err))
409 this.player.on('timeupdate', () => {
410 // Don't need to trigger angular change for this variable, that is sent to children components on click
411 this.currentTime = Math.floor(this.player.currentTime())
415 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
416 * go to the next video in 'condition()' if you don't want of the timer.
417 * next: function triggered at the end of the timer.
418 * suspended: function used at each click of the timer checking if we need to reset progress
419 * and wait until suspended becomes truthy again.
424 headText: $localize`Up Next`,
425 cancelText: $localize`Cancel`,
426 suspendedText: $localize`Autoplay is suspended`,
428 getTitle: () => this.nextVideoTitle,
430 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
432 if (!this.playlist) return this.isAutoPlayNext()
434 // Don't wait timeout to play the next playlist video
435 if (this.isPlaylistAutoPlayNext()) {
436 this.playNextVideoInAngularZone()
445 !isXPercentInViewport(this.player.el(), 80) ||
446 !document.getElementById('content').contains(document.activeElement)
451 this.player.one('stopped', () => {
452 if (this.playlist && this.isPlaylistAutoPlayNext()) {
453 this.playNextVideoInAngularZone()
457 this.player.one('ended', () => {
458 if (this.video.isLive) {
459 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
463 this.player.on('theaterChange', (_: any, enabled: boolean) => {
464 this.zone.run(() => this.theaterEnabled = enabled)
467 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', {
469 playlist: this.playlist,
470 playlistPosition: this.playlistPosition,
477 private hasNextVideo () {
479 return this.videoWatchPlaylist.hasNextVideo()
485 private playNextVideoInAngularZone () {
487 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
491 if (this.nextVideoUUID) {
492 this.router.navigate([ '/w', this.nextVideoUUID ])
496 private isAutoplay () {
497 // We'll jump to the thread id, so do not play the video
498 if (this.route.snapshot.params['threadId']) return false
500 // Otherwise true by default
501 if (!this.user) return true
503 // Be sure the autoPlay is set to false
504 return this.user.autoPlayVideo !== false
507 private isAutoPlayNext () {
509 (this.user?.autoPlayNextVideo) ||
510 this.anonymousUser.autoPlayNextVideo
514 private isPlaylistAutoPlayNext () {
516 (this.user?.autoPlayNextVideoPlaylist) ||
517 this.anonymousUser.autoPlayNextVideoPlaylist
521 private flushPlayer () {
522 // Remove player if it exists
523 if (!this.player) return
526 this.player.dispose()
527 this.player = undefined
529 console.error('Cannot dispose player.', err)
533 private buildPlayerManagerOptions (params: {
535 videoCaptions: VideoCaption[]
536 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
537 loggedInOrAnonymousUser: User
540 const { video, videoCaptions, urlOptions, loggedInOrAnonymousUser, user } = params
542 const getStartTime = () => {
543 const byUrl = urlOptions.startTime !== undefined
544 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
545 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
547 if (byUrl) return timeToInt(urlOptions.startTime)
548 if (byHistory) return video.userHistory.currentTime
549 if (byLocalStorage) return byLocalStorage.duration
554 let startTime = getStartTime()
556 // If we are at the end of the video, reset the timer
557 if (video.duration - startTime <= 1) startTime = 0
559 const playerCaptions = videoCaptions.map(c => ({
560 label: c.language.label,
561 language: c.language.id,
562 src: environment.apiUrl + c.captionPath
565 const options: PeertubePlayerManagerOptions = {
567 autoplay: this.isAutoplay(),
568 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
570 hasNextVideo: () => this.hasNextVideo(),
571 nextVideo: () => this.playNextVideoInAngularZone(),
573 playerElement: this.playerElement,
574 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
576 videoDuration: video.duration,
578 inactivityTimeout: 2500,
579 poster: video.previewUrl,
582 stopTime: urlOptions.stopTime,
583 controls: urlOptions.controls,
584 muted: urlOptions.muted,
585 loop: urlOptions.loop,
586 subtitle: urlOptions.subtitle,
588 peertubeLink: urlOptions.peertubeLink,
591 captions: videoCaptions.length !== 0,
593 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
594 ? this.videoService.getVideoViewUrl(video.uuid)
596 embedUrl: video.embedUrl,
597 embedTitle: video.name,
599 isLive: video.isLive,
601 language: this.localeId,
603 userWatching: user && user.videosHistoryEnabled === true
605 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
606 authorizationHeader: this.authService.getRequestHeaderValue()
610 serverUrl: environment.apiUrl,
612 videoCaptions: playerCaptions,
614 videoShortUUID: video.shortUUID,
615 videoUUID: video.uuid
619 videoFiles: video.files
622 pluginsManager: this.pluginService.getPluginsManager()
625 // Only set this if we're in a playlist
627 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
629 options.common.previousVideo = () => {
630 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
636 if (urlOptions.playerMode) {
637 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
638 else mode = 'webtorrent'
640 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
641 else mode = 'webtorrent'
644 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
645 if (typeof TextEncoder === 'undefined') {
649 if (mode === 'p2p-media-loader') {
650 const hlsPlaylist = video.getHlsPlaylist()
652 const p2pMediaLoader = {
653 playlistUrl: hlsPlaylist.playlistUrl,
654 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
655 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
656 trackerAnnounce: video.trackerUrls,
657 videoFiles: hlsPlaylist.files
658 } as P2PMediaLoaderOptions
660 Object.assign(options, { p2pMediaLoader })
663 return { playerMode: mode, playerOptions: options }
666 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
667 if (!this.liveVideosSub) {
668 this.liveVideosSub = this.buildLiveEventsSubscription()
671 if (oldVideo && oldVideo.id !== newVideo.id) {
672 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
675 if (!newVideo.isLive) return
677 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
680 private buildLiveEventsSubscription () {
681 return this.peertubeSocket.getLiveVideosObservable()
682 .subscribe(({ type, payload }) => {
683 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
684 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
688 private handleLiveStateChange (newState: VideoState) {
689 if (newState !== VideoState.PUBLISHED) return
691 const videoState = this.video.state.id
692 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
694 console.log('Loading video after live update.')
696 const videoUUID = this.video.uuid
698 // Reset to force refresh the video
699 this.video = undefined
700 this.loadVideo(videoUUID)
703 private handleLiveViewsChange (newViewers: number) {
705 console.error('Cannot update video live views because video is no defined.')
709 console.log('Updating live views.')
711 this.video.viewers = newViewers
714 private initHotkeys () {
716 // These hotkeys are managed by the player
717 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
718 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
719 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
721 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
723 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
724 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
726 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
727 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
729 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
730 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
732 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
733 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
735 new Hotkey('t', e => {
736 this.theaterEnabled = !this.theaterEnabled
738 }, undefined, $localize`Toggle theater mode`)
741 if (this.isUserLoggedIn()) {
742 this.hotkeys = this.hotkeys.concat([
743 new Hotkey('shift+s', () => {
744 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
745 else this.subscribeButton.subscribe()
748 }, undefined, $localize`Subscribe to the account`)
752 this.hotkeysService.add(this.hotkeys)
755 private setOpenGraphTags () {
756 this.metaService.setTitle(this.video.name)
758 this.metaService.setTag('og:type', 'video')
760 this.metaService.setTag('og:title', this.video.name)
761 this.metaService.setTag('name', this.video.name)
763 this.metaService.setTag('og:description', this.video.description)
764 this.metaService.setTag('description', this.video.description)
766 this.metaService.setTag('og:image', this.video.previewPath)
768 this.metaService.setTag('og:duration', this.video.duration.toString())
770 this.metaService.setTag('og:site_name', 'PeerTube')
772 this.metaService.setTag('og:url', window.location.href)
773 this.metaService.setTag('url', window.location.href)