1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, Subscription } from 'rxjs'
3 import { PlatformLocation } from '@angular/common'
4 import { Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
5 import { ActivatedRoute, Router } from '@angular/router'
19 import { HooksService } from '@app/core/plugins/hooks.service'
20 import { isXPercentInViewport, scrollToTop } from '@app/helpers'
21 import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
22 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
23 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
24 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
25 import { HTMLServerConfig, PeerTubeProblemDocument, ServerErrorCode, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
26 import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage'
29 P2PMediaLoaderOptions,
30 PeertubePlayerManager,
31 PeertubePlayerManagerOptions,
34 } from '../../../assets/player/peertube-player-manager'
35 import { timeToInt } from '../../../assets/player/utils'
36 import { environment } from '../../../environments/environment'
37 import { VideoWatchPlaylistComponent } from './shared'
39 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
42 selector: 'my-video-watch',
43 templateUrl: './video-watch.component.html',
44 styleUrls: [ './video-watch.component.scss' ]
46 export class VideoWatchComponent implements OnInit, OnDestroy {
47 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
48 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
51 playerElement: HTMLVideoElement
52 playerPlaceholderImgSrc: string
53 theaterEnabled = false
55 video: VideoDetails = null
56 videoCaptions: VideoCaption[] = []
58 playlistPosition: number
59 playlist: VideoPlaylist = null
61 remoteServerDown = false
63 private nextVideoUUID = ''
64 private nextVideoTitle = ''
66 private currentTime: number
68 private paramsSub: Subscription
69 private queryParamsSub: Subscription
70 private configSub: Subscription
71 private liveVideosSub: Subscription
73 private serverConfig: HTMLServerConfig
75 private hotkeys: Hotkey[] = []
78 private elementRef: ElementRef,
79 private route: ActivatedRoute,
80 private router: Router,
81 private videoService: VideoService,
82 private playlistService: VideoPlaylistService,
83 private confirmService: ConfirmService,
84 private metaService: MetaService,
85 private authService: AuthService,
86 private userService: UserService,
87 private serverService: ServerService,
88 private restExtractor: RestExtractor,
89 private notifier: Notifier,
91 private videoCaptionService: VideoCaptionService,
92 private hotkeysService: HotkeysService,
93 private hooks: HooksService,
94 private pluginService: PluginService,
95 private peertubeSocket: PeerTubeSocket,
96 private screenService: ScreenService,
97 private location: PlatformLocation,
98 @Inject(LOCALE_ID) private localeId: string
102 return this.authService.getUser()
105 get anonymousUser () {
106 return this.userService.getAnonymousUser()
110 this.serverConfig = this.serverService.getHTMLConfig()
112 PeertubePlayerManager.initState()
114 this.loadRouteParams()
115 this.loadRouteQuery()
119 this.theaterEnabled = getStoredTheater()
121 this.hooks.runAction('action:video-watch.init', 'video-watch')
123 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
129 // Unsubscribe subscriptions
130 if (this.paramsSub) this.paramsSub.unsubscribe()
131 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
132 if (this.configSub) this.configSub.unsubscribe()
133 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
136 this.hotkeysService.remove(this.hotkeys)
140 return this.currentTime
143 getCurrentPlaylistPosition () {
144 return this.videoWatchPlaylist.currentPlaylistPosition
147 onRecommendations (videos: Video[]) {
148 if (videos.length === 0) return
150 // The recommended videos's first element should be the next video
151 const video = videos[0]
152 this.nextVideoUUID = video.uuid
153 this.nextVideoTitle = video.name
156 handleTimestampClicked (timestamp: number) {
157 if (!this.player || this.video.isLive) return
159 this.player.currentTime(timestamp)
163 onPlaylistVideoFound (videoId: string) {
164 this.loadVideo(videoId)
168 return this.authService.isLoggedIn()
171 isVideoBlur (video: Video) {
172 return video.isVideoNSFWForUser(this.user, this.serverConfig)
175 isChannelDisplayNameGeneric () {
176 const genericChannelDisplayName = [
177 `Main ${this.video.channel.ownerAccount.name} channel`,
178 `Default ${this.video.channel.ownerAccount.name} channel`
181 return genericChannelDisplayName.includes(this.video.channel.displayName)
184 displayOtherVideosAsRow () {
185 // Use the same value as in the SASS file
186 return this.screenService.getWindowInnerWidth() <= 1100
189 private loadRouteParams () {
190 this.paramsSub = this.route.params.subscribe(routeParams => {
191 const videoId = routeParams[ 'videoId' ]
192 if (videoId) return this.loadVideo(videoId)
194 const playlistId = routeParams[ 'playlistId' ]
195 if (playlistId) return this.loadPlaylist(playlistId)
199 private loadRouteQuery () {
200 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
201 // Handle the ?playlistPosition
202 const positionParam = queryParams[ 'playlistPosition' ] ?? 1
204 this.playlistPosition = positionParam === 'last'
205 ? -1 // Handle the "last" index
206 : parseInt(positionParam + '', 10)
208 if (isNaN(this.playlistPosition)) {
209 console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
210 this.playlistPosition = 1
213 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
215 const start = queryParams[ 'start' ]
216 if (this.player && start) this.player.currentTime(parseInt(start, 10))
220 private loadVideo (videoId: string) {
221 if (this.isSameElement(this.video, videoId)) return
223 if (this.player) this.player.pause()
225 const videoObs = this.hooks.wrapObsFun(
226 this.videoService.getVideo.bind(this.videoService),
229 'filter:api.video-watch.video.get.params',
230 'filter:api.video-watch.video.get.result'
233 forkJoin([ videoObs, this.videoCaptionService.listCaptions(videoId)])
235 ([ video, captionsResult ]) => {
236 const queryParams = this.route.snapshot.queryParams
239 resume: queryParams.resume,
241 startTime: queryParams.start,
242 stopTime: queryParams.stop,
244 muted: queryParams.muted,
245 loop: queryParams.loop,
246 subtitle: queryParams.subtitle,
248 playerMode: queryParams.mode,
252 this.onVideoFetched(video, captionsResult.data, urlOptions)
253 .catch(err => this.handleGlobalError(err))
256 err => this.handleRequestError(err)
260 private loadPlaylist (playlistId: string) {
261 if (this.isSameElement(this.playlist, playlistId)) return
263 this.playlistService.getVideoPlaylist(playlistId)
266 this.playlist = playlist
268 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
271 err => this.handleRequestError(err)
275 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
276 if (!element) return false
278 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
281 private async handleRequestError (err: any) {
282 const errorBody = err.body as PeerTubeProblemDocument
284 if (errorBody.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
285 const originUrl = errorBody.originUrl + (window.location.search ?? '')
287 const res = await this.confirmService.confirm(
288 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
289 $localize`Redirection`
292 if (res === true) return window.location.href = originUrl
295 // If 400, 403 or 404, the video is private or blocked so redirect to 404
296 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
297 HttpStatusCode.BAD_REQUEST_400,
298 HttpStatusCode.FORBIDDEN_403,
299 HttpStatusCode.NOT_FOUND_404
303 private handleGlobalError (err: any) {
304 const errorMessage: string = typeof err === 'string' ? err : err.message
305 if (!errorMessage) return
307 // Display a message in the video player instead of a notification
308 if (errorMessage.indexOf('from xs param') !== -1) {
310 this.remoteServerDown = true
315 this.notifier.error(errorMessage)
318 private async onVideoFetched (
320 videoCaptions: VideoCaption[],
321 urlOptions: URLOptions
323 this.subscribeToLiveEventsIfNeeded(this.video, video)
326 this.videoCaptions = videoCaptions
328 // Re init attributes
329 this.playerPlaceholderImgSrc = undefined
330 this.remoteServerDown = false
331 this.currentTime = undefined
333 if (this.isVideoBlur(this.video)) {
334 const res = await this.confirmService.confirm(
335 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
336 $localize`Mature or explicit content`
338 if (res === false) return this.location.back()
341 this.buildPlayer(urlOptions)
342 .catch(err => console.error('Cannot build the player', err))
344 this.setOpenGraphTags()
346 const hookOptions = {
349 playlist: this.playlist
351 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
354 private async buildPlayer (urlOptions: URLOptions) {
355 // Flush old player if needed
358 const videoState = this.video.state.id
359 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
360 this.playerPlaceholderImgSrc = this.video.previewPath
364 // Build video element, because videojs removes it on dispose
365 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
366 this.playerElement = document.createElement('video')
367 this.playerElement.className = 'video-js vjs-peertube-skin'
368 this.playerElement.setAttribute('playsinline', 'true')
369 playerElementWrapper.appendChild(this.playerElement)
373 videoCaptions: this.videoCaptions,
377 const { playerMode, playerOptions } = await this.hooks.wrapFun(
378 this.buildPlayerManagerOptions.bind(this),
381 'filter:internal.video-watch.player.build-options.params',
382 'filter:internal.video-watch.player.build-options.result'
385 this.zone.runOutsideAngular(async () => {
386 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
388 this.player.on('customError', ({ err }: { err: any }) => {
389 this.zone.run(() => this.handleGlobalError(err))
392 this.player.on('timeupdate', () => {
393 // Don't need to trigger angular change for this variable, that is sent to children components on click
394 this.currentTime = Math.floor(this.player.currentTime())
398 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
399 * go to the next video in 'condition()' if you don't want of the timer.
400 * next: function triggered at the end of the timer.
401 * suspended: function used at each click of the timer checking if we need to reset progress
402 * and wait until suspended becomes truthy again.
407 headText: $localize`Up Next`,
408 cancelText: $localize`Cancel`,
409 suspendedText: $localize`Autoplay is suspended`,
411 getTitle: () => this.nextVideoTitle,
413 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
415 if (!this.playlist) return this.isAutoPlayNext()
417 // Don't wait timeout to play the next playlist video
418 if (this.isPlaylistAutoPlayNext()) {
419 this.playNextVideoInAngularZone()
428 !isXPercentInViewport(this.player.el(), 80) ||
429 !document.getElementById('content').contains(document.activeElement)
434 this.player.one('stopped', () => {
435 if (this.playlist && this.isPlaylistAutoPlayNext()) {
436 this.playNextVideoInAngularZone()
440 this.player.one('ended', () => {
441 if (this.video.isLive) {
442 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
446 this.player.on('theaterChange', (_: any, enabled: boolean) => {
447 this.zone.run(() => this.theaterEnabled = enabled)
450 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
454 private playNextVideoInAngularZone () {
456 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
460 if (this.nextVideoUUID) {
461 this.router.navigate([ '/w', this.nextVideoUUID ])
466 private isAutoplay () {
467 // We'll jump to the thread id, so do not play the video
468 if (this.route.snapshot.params['threadId']) return false
470 // Otherwise true by default
471 if (!this.user) return true
473 // Be sure the autoPlay is set to false
474 return this.user.autoPlayVideo !== false
477 private isAutoPlayNext () {
479 (this.user && this.user.autoPlayNextVideo) ||
480 this.anonymousUser.autoPlayNextVideo
484 private isPlaylistAutoPlayNext () {
486 (this.user && this.user.autoPlayNextVideoPlaylist) ||
487 this.anonymousUser.autoPlayNextVideoPlaylist
491 private flushPlayer () {
492 // Remove player if it exists
493 if (!this.player) return
496 this.player.dispose()
497 this.player = undefined
499 console.error('Cannot dispose player.', err)
503 private buildPlayerManagerOptions (params: {
505 videoCaptions: VideoCaption[],
506 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
509 const { video, videoCaptions, urlOptions, user } = params
511 const getStartTime = () => {
512 const byUrl = urlOptions.startTime !== undefined
513 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
514 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
516 if (byUrl) return timeToInt(urlOptions.startTime)
517 if (byHistory) return video.userHistory.currentTime
518 if (byLocalStorage) return byLocalStorage.duration
523 let startTime = getStartTime()
525 // If we are at the end of the video, reset the timer
526 if (video.duration - startTime <= 1) startTime = 0
528 const playerCaptions = videoCaptions.map(c => ({
529 label: c.language.label,
530 language: c.language.id,
531 src: environment.apiUrl + c.captionPath
534 const options: PeertubePlayerManagerOptions = {
536 autoplay: this.isAutoplay(),
537 nextVideo: () => this.playNextVideoInAngularZone(),
539 playerElement: this.playerElement,
540 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
542 videoDuration: video.duration,
544 inactivityTimeout: 2500,
545 poster: video.previewUrl,
548 stopTime: urlOptions.stopTime,
549 controls: urlOptions.controls,
550 muted: urlOptions.muted,
551 loop: urlOptions.loop,
552 subtitle: urlOptions.subtitle,
554 peertubeLink: urlOptions.peertubeLink,
557 captions: videoCaptions.length !== 0,
559 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
560 ? this.videoService.getVideoViewUrl(video.uuid)
562 embedUrl: video.embedUrl,
563 embedTitle: video.name,
565 isLive: video.isLive,
567 language: this.localeId,
569 userWatching: user && user.videosHistoryEnabled === true ? {
570 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
571 authorizationHeader: this.authService.getRequestHeaderValue()
574 serverUrl: environment.apiUrl,
576 videoCaptions: playerCaptions,
578 videoUUID: video.uuid
582 videoFiles: video.files
585 pluginsManager: this.pluginService.getPluginsManager()
588 // Only set this if we're in a playlist
590 options.common.previousVideo = () => {
591 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
597 if (urlOptions.playerMode) {
598 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
599 else mode = 'webtorrent'
601 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
602 else mode = 'webtorrent'
605 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
606 if (typeof TextEncoder === 'undefined') {
610 if (mode === 'p2p-media-loader') {
611 const hlsPlaylist = video.getHlsPlaylist()
613 const p2pMediaLoader = {
614 playlistUrl: hlsPlaylist.playlistUrl,
615 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
616 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
617 trackerAnnounce: video.trackerUrls,
618 videoFiles: hlsPlaylist.files
619 } as P2PMediaLoaderOptions
621 Object.assign(options, { p2pMediaLoader })
624 return { playerMode: mode, playerOptions: options }
627 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
628 if (!this.liveVideosSub) {
629 this.liveVideosSub = this.buildLiveEventsSubscription()
632 if (oldVideo && oldVideo.id !== newVideo.id) {
633 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
636 if (!newVideo.isLive) return
638 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
641 private buildLiveEventsSubscription () {
642 return this.peertubeSocket.getLiveVideosObservable()
643 .subscribe(({ type, payload }) => {
644 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
645 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
649 private handleLiveStateChange (newState: VideoState) {
650 if (newState !== VideoState.PUBLISHED) return
652 const videoState = this.video.state.id
653 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
655 console.log('Loading video after live update.')
657 const videoUUID = this.video.uuid
659 // Reset to force refresh the video
660 this.video = undefined
661 this.loadVideo(videoUUID)
664 private handleLiveViewsChange (newViews: number) {
666 console.error('Cannot update video live views because video is no defined.')
670 console.log('Updating live views.')
672 this.video.views = newViews
675 private initHotkeys () {
677 // These hotkeys are managed by the player
678 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
679 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
680 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
682 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90% (requires player focus)`),
684 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
685 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
687 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
688 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
690 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
691 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
693 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
696 if (this.isUserLoggedIn()) {
697 this.hotkeys = this.hotkeys.concat([
698 new Hotkey('shift+s', () => {
699 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
701 }, undefined, $localize`Subscribe to the account`)
705 this.hotkeysService.add(this.hotkeys)
708 private setOpenGraphTags () {
709 this.metaService.setTitle(this.video.name)
711 this.metaService.setTag('og:type', 'video')
713 this.metaService.setTag('og:title', this.video.name)
714 this.metaService.setTag('name', this.video.name)
716 this.metaService.setTag('og:description', this.video.description)
717 this.metaService.setTag('description', this.video.description)
719 this.metaService.setTag('og:image', this.video.previewPath)
721 this.metaService.setTag('og:duration', this.video.duration.toString())
723 this.metaService.setTag('og:site_name', 'PeerTube')
725 this.metaService.setTag('og:url', window.location.href)
726 this.metaService.setTag('url', window.location.href)