1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, Observable, Subscription } from 'rxjs'
3 import { catchError } from 'rxjs/operators'
4 import { PlatformLocation } from '@angular/common'
5 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
6 import { ActivatedRoute, Router } from '@angular/router'
7 import { AuthService, AuthUser, ConfirmService, MarkdownService, Notifier, RestExtractor, ServerService, UserService } from '@app/core'
8 import { HooksService } from '@app/core/plugins/hooks.service'
9 import { RedirectService } from '@app/core/routing/redirect.service'
10 import { isXPercentInViewport, scrollToTop } from '@app/helpers'
11 import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
12 import { VideoShareComponent } from '@app/shared/shared-share-modal'
13 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
14 import { VideoDownloadComponent } from '@app/shared/shared-video-miniature'
15 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
16 import { MetaService } from '@ngx-meta/core'
17 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
18 import { ServerConfig, ServerErrorCode, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
19 import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
22 P2PMediaLoaderOptions,
23 PeertubePlayerManager,
24 PeertubePlayerManagerOptions,
27 } from '../../../assets/player/peertube-player-manager'
28 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
29 import { environment } from '../../../environments/environment'
30 import { VideoSupportComponent } from './modal/video-support.component'
31 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
34 selector: 'my-video-watch',
35 templateUrl: './video-watch.component.html',
36 styleUrls: [ './video-watch.component.scss' ]
38 export class VideoWatchComponent implements OnInit, OnDestroy {
39 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
41 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
42 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
43 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
44 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
45 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
48 playerElement: HTMLVideoElement
49 theaterEnabled = false
50 userRating: UserVideoRateType = null
51 descriptionLoading = false
53 video: VideoDetails = null
54 videoCaptions: VideoCaption[] = []
56 playlistPosition: number
57 playlist: VideoPlaylist = null
59 completeDescriptionShown = false
60 completeVideoDescription: string
61 shortVideoDescription: string
62 videoHTMLDescription = ''
63 likesBarTooltipText = ''
64 hasAlreadyAcceptedPrivacyConcern = false
65 remoteServerDown = false
66 hotkeys: Hotkey[] = []
71 tooltipSaveToPlaylist = ''
73 private nextVideoUuid = ''
74 private nextVideoTitle = ''
75 private currentTime: number
76 private paramsSub: Subscription
77 private queryParamsSub: Subscription
78 private configSub: Subscription
80 private serverConfig: ServerConfig
83 private elementRef: ElementRef,
84 private changeDetector: ChangeDetectorRef,
85 private route: ActivatedRoute,
86 private router: Router,
87 private videoService: VideoService,
88 private playlistService: VideoPlaylistService,
89 private confirmService: ConfirmService,
90 private metaService: MetaService,
91 private authService: AuthService,
92 private userService: UserService,
93 private serverService: ServerService,
94 private restExtractor: RestExtractor,
95 private notifier: Notifier,
96 private markdownService: MarkdownService,
98 private redirectService: RedirectService,
99 private videoCaptionService: VideoCaptionService,
100 private hotkeysService: HotkeysService,
101 private hooks: HooksService,
102 private location: PlatformLocation,
103 @Inject(LOCALE_ID) private localeId: string
105 this.tooltipLike = $localize`Like this video`
106 this.tooltipDislike = $localize`Dislike this video`
107 this.tooltipSupport = $localize`Support options for this video`
108 this.tooltipSaveToPlaylist = $localize`Save to playlist`
112 return this.authService.getUser()
115 get anonymousUser () {
116 return this.userService.getAnonymousUser()
120 this.serverConfig = this.serverService.getTmpConfig()
122 this.configSub = this.serverService.getConfig()
123 .subscribe(config => {
124 this.serverConfig = config
127 isWebRTCDisabled() ||
128 this.serverConfig.tracker.enabled === false ||
129 getStoredP2PEnabled() === false ||
130 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
132 this.hasAlreadyAcceptedPrivacyConcern = true
136 this.paramsSub = this.route.params.subscribe(routeParams => {
137 const videoId = routeParams[ 'videoId' ]
138 if (videoId) this.loadVideo(videoId)
140 const playlistId = routeParams[ 'playlistId' ]
141 if (playlistId) this.loadPlaylist(playlistId)
144 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
145 this.playlistPosition = queryParams[ 'playlistPosition' ]
146 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
148 const start = queryParams[ 'start' ]
149 if (this.player && start) this.player.currentTime(parseInt(start, 10))
154 this.theaterEnabled = getStoredTheater()
156 this.hooks.runAction('action:video-watch.init', 'video-watch')
162 // Unsubscribe subscriptions
163 if (this.paramsSub) this.paramsSub.unsubscribe()
164 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
165 if (this.configSub) this.configSub.unsubscribe()
168 this.hotkeysService.remove(this.hotkeys)
172 if (this.isUserLoggedIn() === false) return
174 // Already liked this video
175 if (this.userRating === 'like') this.setRating('none')
176 else this.setRating('like')
180 if (this.isUserLoggedIn() === false) return
182 // Already disliked this video
183 if (this.userRating === 'dislike') this.setRating('none')
184 else this.setRating('dislike')
187 getRatePopoverText () {
188 if (this.isUserLoggedIn()) return undefined
190 return $localize`You need to be connected to rate this content.`
193 showMoreDescription () {
194 if (this.completeVideoDescription === undefined) {
195 return this.loadCompleteDescription()
198 this.updateVideoDescription(this.completeVideoDescription)
199 this.completeDescriptionShown = true
202 showLessDescription () {
203 this.updateVideoDescription(this.shortVideoDescription)
204 this.completeDescriptionShown = false
207 showDownloadModal () {
208 this.videoDownloadModal.show(this.video, this.videoCaptions)
211 isVideoDownloadable () {
212 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled
215 loadCompleteDescription () {
216 this.descriptionLoading = true
218 this.videoService.loadCompleteDescription(this.video.descriptionPath)
221 this.completeDescriptionShown = true
222 this.descriptionLoading = false
224 this.shortVideoDescription = this.video.description
225 this.completeVideoDescription = description
227 this.updateVideoDescription(this.completeVideoDescription)
231 this.descriptionLoading = false
232 this.notifier.error(error.message)
237 showSupportModal () {
238 // Check video was playing before opening support modal
239 const isVideoPlaying = this.isPlaying()
243 const modalRef = this.videoSupportModal.show()
245 modalRef.result.then(() => {
246 if (isVideoPlaying) {
255 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
259 return this.authService.isLoggedIn()
263 if (!this.video || Array.isArray(this.video.tags) === false) return []
265 return this.video.tags
268 onRecommendations (videos: Video[]) {
269 if (videos.length > 0) {
270 // The recommended videos's first element should be the next video
271 const video = videos[0]
272 this.nextVideoUuid = video.uuid
273 this.nextVideoTitle = video.name
282 this.redirectService.redirectToHomepage()
285 declinedPrivacyConcern () {
286 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
287 this.hasAlreadyAcceptedPrivacyConcern = false
290 acceptedPrivacyConcern () {
291 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
292 this.hasAlreadyAcceptedPrivacyConcern = true
295 isVideoToTranscode () {
296 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
300 return this.video && this.video.state.id === VideoState.TO_IMPORT
303 hasVideoScheduledPublication () {
304 return this.video && this.video.scheduledUpdate !== undefined
307 isVideoBlur (video: Video) {
308 return video.isVideoNSFWForUser(this.user, this.serverConfig)
311 isAutoPlayEnabled () {
313 (this.user && this.user.autoPlayNextVideo) ||
314 this.anonymousUser.autoPlayNextVideo
318 handleTimestampClicked (timestamp: number) {
319 if (this.player) this.player.currentTime(timestamp)
323 isPlaylistAutoPlayEnabled () {
325 (this.user && this.user.autoPlayNextVideoPlaylist) ||
326 this.anonymousUser.autoPlayNextVideoPlaylist
330 isChannelDisplayNameGeneric () {
331 const genericChannelDisplayName = [
332 `Main ${this.video.channel.ownerAccount.name} channel`,
333 `Default ${this.video.channel.ownerAccount.name} channel`
336 return genericChannelDisplayName.includes(this.video.channel.displayName)
339 onPlaylistVideoFound (videoId: string) {
340 this.loadVideo(videoId)
343 private loadVideo (videoId: string) {
344 // Video did not change
345 if (this.video && this.video.uuid === videoId) return
347 if (this.player) this.player.pause()
349 const videoObs = this.hooks.wrapObsFun(
350 this.videoService.getVideo.bind(this.videoService),
353 'filter:api.video-watch.video.get.params',
354 'filter:api.video-watch.video.get.result'
360 this.videoCaptionService.listCaptions(videoId)
363 // If 401, the video is private or blocked so redirect to 404
365 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
366 const search = window.location.search
367 let originUrl = err.body.originUrl
368 if (search) originUrl += search
370 this.confirmService.confirm(
371 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
372 $localize`Redirection`
374 if (res === false) return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
376 return window.location.href = originUrl
380 return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
383 .subscribe(([ video, captionsResult ]) => {
384 const queryParams = this.route.snapshot.queryParams
387 resume: queryParams.resume,
389 startTime: queryParams.start,
390 stopTime: queryParams.stop,
392 muted: queryParams.muted,
393 loop: queryParams.loop,
394 subtitle: queryParams.subtitle,
396 playerMode: queryParams.mode,
400 this.onVideoFetched(video, captionsResult.data, urlOptions)
401 .catch(err => this.handleError(err))
405 private loadPlaylist (playlistId: string) {
406 // Playlist did not change
407 if (this.playlist && this.playlist.uuid === playlistId) return
409 this.playlistService.getVideoPlaylist(playlistId)
411 // If 401, the video is private or blocked so redirect to 404
412 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
414 .subscribe(playlist => {
415 this.playlist = playlist
417 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
421 private updateVideoDescription (description: string) {
422 this.video.description = description
423 this.setVideoDescriptionHTML()
424 .catch(err => console.error(err))
427 private async setVideoDescriptionHTML () {
428 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
429 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
432 private setVideoLikesBarTooltipText () {
433 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
436 private handleError (err: any) {
437 const errorMessage: string = typeof err === 'string' ? err : err.message
438 if (!errorMessage) return
440 // Display a message in the video player instead of a notification
441 if (errorMessage.indexOf('from xs param') !== -1) {
443 this.remoteServerDown = true
444 this.changeDetector.detectChanges()
449 this.notifier.error(errorMessage)
452 private checkUserRating () {
453 // Unlogged users do not have ratings
454 if (this.isUserLoggedIn() === false) return
456 this.videoService.getUserVideoRating(this.video.id)
460 this.userRating = ratingObject.rating
464 err => this.notifier.error(err.message)
468 private async onVideoFetched (
470 videoCaptions: VideoCaption[],
471 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
474 this.videoCaptions = videoCaptions
476 // Re init attributes
477 this.descriptionLoading = false
478 this.completeDescriptionShown = false
479 this.remoteServerDown = false
480 this.currentTime = undefined
482 if (this.isVideoBlur(this.video)) {
483 const res = await this.confirmService.confirm(
484 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
485 $localize`Mature or explicit content`
487 if (res === false) return this.location.back()
490 // Flush old player if needed
493 // Build video element, because videojs removes it on dispose
494 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
495 this.playerElement = document.createElement('video')
496 this.playerElement.className = 'video-js vjs-peertube-skin'
497 this.playerElement.setAttribute('playsinline', 'true')
498 playerElementWrapper.appendChild(this.playerElement)
506 const { playerMode, playerOptions } = await this.hooks.wrapFun(
507 this.buildPlayerManagerOptions.bind(this),
510 'filter:internal.video-watch.player.build-options.params',
511 'filter:internal.video-watch.player.build-options.result'
514 this.zone.runOutsideAngular(async () => {
515 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
517 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
519 this.player.on('timeupdate', () => {
520 this.currentTime = Math.floor(this.player.currentTime())
524 * replaces this.player.one('ended')
525 * 'condition()': true to make the upnext functionality trigger,
526 * false to disable the upnext functionality
527 * go to the next video in 'condition()' if you don't want of the timer.
528 * 'next': function triggered at the end of the timer.
529 * 'suspended': function used at each clic of the timer checking if we need
530 * to reset progress and wait until 'suspended' becomes truthy again.
533 timeout: 10000, // 10s
534 headText: $localize`Up Next`,
535 cancelText: $localize`Cancel`,
536 suspendedText: $localize`Autoplay is suspended`,
537 getTitle: () => this.nextVideoTitle,
538 next: () => this.zone.run(() => this.autoplayNext()),
541 if (this.isPlaylistAutoPlayEnabled()) {
542 // upnext will not trigger, and instead the next video will play immediately
543 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
545 } else if (this.isAutoPlayEnabled()) {
546 return true // upnext will trigger
548 return false // upnext will not trigger, and instead leave the video stopping
552 !isXPercentInViewport(this.player.el(), 80) ||
553 !document.getElementById('content').contains(document.activeElement)
558 this.player.one('stopped', () => {
560 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
564 this.player.on('theaterChange', (_: any, enabled: boolean) => {
565 this.zone.run(() => this.theaterEnabled = enabled)
568 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
571 this.setVideoDescriptionHTML()
572 this.setVideoLikesBarTooltipText()
574 this.setOpenGraphTags()
575 this.checkUserRating()
577 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
580 private autoplayNext () {
582 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
583 } else if (this.nextVideoUuid) {
584 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
588 private setRating (nextRating: UserVideoRateType) {
589 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
590 like: this.videoService.setVideoLike,
591 dislike: this.videoService.setVideoDislike,
592 none: this.videoService.unsetVideoLike
595 ratingMethods[nextRating].call(this.videoService, this.video.id)
598 // Update the video like attribute
599 this.updateVideoRating(this.userRating, nextRating)
600 this.userRating = nextRating
603 (err: { message: string }) => this.notifier.error(err.message)
607 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
608 let likesToIncrement = 0
609 let dislikesToIncrement = 0
612 if (oldRating === 'like') likesToIncrement--
613 if (oldRating === 'dislike') dislikesToIncrement--
616 if (newRating === 'like') likesToIncrement++
617 if (newRating === 'dislike') dislikesToIncrement++
619 this.video.likes += likesToIncrement
620 this.video.dislikes += dislikesToIncrement
622 this.video.buildLikeAndDislikePercents()
623 this.setVideoLikesBarTooltipText()
626 private setOpenGraphTags () {
627 this.metaService.setTitle(this.video.name)
629 this.metaService.setTag('og:type', 'video')
631 this.metaService.setTag('og:title', this.video.name)
632 this.metaService.setTag('name', this.video.name)
634 this.metaService.setTag('og:description', this.video.description)
635 this.metaService.setTag('description', this.video.description)
637 this.metaService.setTag('og:image', this.video.previewPath)
639 this.metaService.setTag('og:duration', this.video.duration.toString())
641 this.metaService.setTag('og:site_name', 'PeerTube')
643 this.metaService.setTag('og:url', window.location.href)
644 this.metaService.setTag('url', window.location.href)
647 private isAutoplay () {
648 // We'll jump to the thread id, so do not play the video
649 if (this.route.snapshot.params['threadId']) return false
651 // Otherwise true by default
652 if (!this.user) return true
654 // Be sure the autoPlay is set to false
655 return this.user.autoPlayVideo !== false
658 private flushPlayer () {
659 // Remove player if it exists
662 this.player.dispose()
663 this.player = undefined
665 console.error('Cannot dispose player.', err)
670 private buildPlayerManagerOptions (params: {
672 videoCaptions: VideoCaption[],
673 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
676 const { video, videoCaptions, urlOptions, user } = params
677 const getStartTime = () => {
678 const byUrl = urlOptions.startTime !== undefined
679 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
681 if (byUrl) return timeToInt(urlOptions.startTime)
682 if (byHistory) return video.userHistory.currentTime
687 let startTime = getStartTime()
689 // If we are at the end of the video, reset the timer
690 if (video.duration - startTime <= 1) startTime = 0
692 const playerCaptions = videoCaptions.map(c => ({
693 label: c.language.label,
694 language: c.language.id,
695 src: environment.apiUrl + c.captionPath
698 const options: PeertubePlayerManagerOptions = {
700 autoplay: this.isAutoplay(),
701 nextVideo: () => this.zone.run(() => this.autoplayNext()),
703 playerElement: this.playerElement,
704 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
706 videoDuration: video.duration,
708 inactivityTimeout: 2500,
709 poster: video.previewUrl,
712 stopTime: urlOptions.stopTime,
713 controls: urlOptions.controls,
714 muted: urlOptions.muted,
715 loop: urlOptions.loop,
716 subtitle: urlOptions.subtitle,
718 peertubeLink: urlOptions.peertubeLink,
721 captions: videoCaptions.length !== 0,
723 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
724 ? this.videoService.getVideoViewUrl(video.uuid)
726 embedUrl: video.embedUrl,
728 language: this.localeId,
730 userWatching: user && user.videosHistoryEnabled === true ? {
731 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
732 authorizationHeader: this.authService.getRequestHeaderValue()
735 serverUrl: environment.apiUrl,
737 videoCaptions: playerCaptions
741 videoFiles: video.files
747 if (urlOptions.playerMode) {
748 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
749 else mode = 'webtorrent'
751 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
752 else mode = 'webtorrent'
755 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
756 if (typeof TextEncoder === 'undefined') {
760 if (mode === 'p2p-media-loader') {
761 const hlsPlaylist = video.getHlsPlaylist()
763 const p2pMediaLoader = {
764 playlistUrl: hlsPlaylist.playlistUrl,
765 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
766 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
767 trackerAnnounce: video.trackerUrls,
768 videoFiles: hlsPlaylist.files
769 } as P2PMediaLoaderOptions
771 Object.assign(options, { p2pMediaLoader })
774 return { playerMode: mode, playerOptions: options }
777 private pausePlayer () {
778 if (!this.player) return
783 private resumePlayer () {
784 if (!this.player) return
789 private isPlaying () {
790 if (!this.player) return
792 return !this.player.paused()
795 private initHotkeys () {
797 // These hotkeys are managed by the player
798 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
799 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
800 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
802 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)`),
804 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
805 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
807 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
808 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
810 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
811 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
813 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
816 if (this.isUserLoggedIn()) {
817 this.hotkeys = this.hotkeys.concat([
818 new Hotkey('shift+l', () => {
821 }, undefined, $localize`Like the video`),
823 new Hotkey('shift+d', () => {
826 }, undefined, $localize`Dislike the video`),
828 new Hotkey('shift+s', () => {
829 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
831 }, undefined, $localize`Subscribe to the account`)
835 this.hotkeysService.add(this.hotkeys)