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 PeertubePlayerManager.initState()
122 this.serverConfig = this.serverService.getTmpConfig()
124 this.configSub = this.serverService.getConfig()
125 .subscribe(config => {
126 this.serverConfig = config
129 isWebRTCDisabled() ||
130 this.serverConfig.tracker.enabled === false ||
131 getStoredP2PEnabled() === false ||
132 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
134 this.hasAlreadyAcceptedPrivacyConcern = true
138 this.paramsSub = this.route.params.subscribe(routeParams => {
139 const videoId = routeParams[ 'videoId' ]
140 if (videoId) this.loadVideo(videoId)
142 const playlistId = routeParams[ 'playlistId' ]
143 if (playlistId) this.loadPlaylist(playlistId)
146 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
147 this.playlistPosition = queryParams[ 'playlistPosition' ]
148 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
150 const start = queryParams[ 'start' ]
151 if (this.player && start) this.player.currentTime(parseInt(start, 10))
156 this.theaterEnabled = getStoredTheater()
158 this.hooks.runAction('action:video-watch.init', 'video-watch')
164 // Unsubscribe subscriptions
165 if (this.paramsSub) this.paramsSub.unsubscribe()
166 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
167 if (this.configSub) this.configSub.unsubscribe()
170 this.hotkeysService.remove(this.hotkeys)
174 if (this.isUserLoggedIn() === false) return
176 // Already liked this video
177 if (this.userRating === 'like') this.setRating('none')
178 else this.setRating('like')
182 if (this.isUserLoggedIn() === false) return
184 // Already disliked this video
185 if (this.userRating === 'dislike') this.setRating('none')
186 else this.setRating('dislike')
189 getRatePopoverText () {
190 if (this.isUserLoggedIn()) return undefined
192 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
195 showMoreDescription () {
196 if (this.completeVideoDescription === undefined) {
197 return this.loadCompleteDescription()
200 this.updateVideoDescription(this.completeVideoDescription)
201 this.completeDescriptionShown = true
204 showLessDescription () {
205 this.updateVideoDescription(this.shortVideoDescription)
206 this.completeDescriptionShown = false
209 showDownloadModal () {
210 this.videoDownloadModal.show(this.video, this.videoCaptions)
213 isVideoDownloadable () {
214 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled
217 loadCompleteDescription () {
218 this.descriptionLoading = true
220 this.videoService.loadCompleteDescription(this.video.descriptionPath)
223 this.completeDescriptionShown = true
224 this.descriptionLoading = false
226 this.shortVideoDescription = this.video.description
227 this.completeVideoDescription = description
229 this.updateVideoDescription(this.completeVideoDescription)
233 this.descriptionLoading = false
234 this.notifier.error(error.message)
239 showSupportModal () {
240 // Check video was playing before opening support modal
241 const isVideoPlaying = this.isPlaying()
245 const modalRef = this.videoSupportModal.show()
247 modalRef.result.then(() => {
248 if (isVideoPlaying) {
257 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
261 return this.authService.isLoggedIn()
265 if (!this.video || Array.isArray(this.video.tags) === false) return []
267 return this.video.tags
270 onRecommendations (videos: Video[]) {
271 if (videos.length > 0) {
272 // The recommended videos's first element should be the next video
273 const video = videos[0]
274 this.nextVideoUuid = video.uuid
275 this.nextVideoTitle = video.name
284 this.redirectService.redirectToHomepage()
287 declinedPrivacyConcern () {
288 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
289 this.hasAlreadyAcceptedPrivacyConcern = false
292 acceptedPrivacyConcern () {
293 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
294 this.hasAlreadyAcceptedPrivacyConcern = true
297 isVideoToTranscode () {
298 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
302 return this.video && this.video.state.id === VideoState.TO_IMPORT
305 hasVideoScheduledPublication () {
306 return this.video && this.video.scheduledUpdate !== undefined
309 isVideoBlur (video: Video) {
310 return video.isVideoNSFWForUser(this.user, this.serverConfig)
313 isAutoPlayEnabled () {
315 (this.user && this.user.autoPlayNextVideo) ||
316 this.anonymousUser.autoPlayNextVideo
320 handleTimestampClicked (timestamp: number) {
321 if (this.player) this.player.currentTime(timestamp)
325 isPlaylistAutoPlayEnabled () {
327 (this.user && this.user.autoPlayNextVideoPlaylist) ||
328 this.anonymousUser.autoPlayNextVideoPlaylist
332 isChannelDisplayNameGeneric () {
333 const genericChannelDisplayName = [
334 `Main ${this.video.channel.ownerAccount.name} channel`,
335 `Default ${this.video.channel.ownerAccount.name} channel`
338 return genericChannelDisplayName.includes(this.video.channel.displayName)
341 onPlaylistVideoFound (videoId: string) {
342 this.loadVideo(videoId)
345 private loadVideo (videoId: string) {
346 // Video did not change
347 if (this.video && this.video.uuid === videoId) return
349 if (this.player) this.player.pause()
351 const videoObs = this.hooks.wrapObsFun(
352 this.videoService.getVideo.bind(this.videoService),
355 'filter:api.video-watch.video.get.params',
356 'filter:api.video-watch.video.get.result'
362 this.videoCaptionService.listCaptions(videoId)
365 // If 401, the video is private or blocked so redirect to 404
367 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
368 const search = window.location.search
369 let originUrl = err.body.originUrl
370 if (search) originUrl += search
372 this.confirmService.confirm(
373 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
374 $localize`Redirection`
376 if (res === false) return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
378 return window.location.href = originUrl
382 return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
385 .subscribe(([ video, captionsResult ]) => {
386 const queryParams = this.route.snapshot.queryParams
389 resume: queryParams.resume,
391 startTime: queryParams.start,
392 stopTime: queryParams.stop,
394 muted: queryParams.muted,
395 loop: queryParams.loop,
396 subtitle: queryParams.subtitle,
398 playerMode: queryParams.mode,
402 this.onVideoFetched(video, captionsResult.data, urlOptions)
403 .catch(err => this.handleError(err))
407 private loadPlaylist (playlistId: string) {
408 // Playlist did not change
409 if (this.playlist && this.playlist.uuid === playlistId) return
411 this.playlistService.getVideoPlaylist(playlistId)
413 // If 401, the video is private or blocked so redirect to 404
414 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
416 .subscribe(playlist => {
417 this.playlist = playlist
419 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
423 private updateVideoDescription (description: string) {
424 this.video.description = description
425 this.setVideoDescriptionHTML()
426 .catch(err => console.error(err))
429 private async setVideoDescriptionHTML () {
430 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
431 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
434 private setVideoLikesBarTooltipText () {
435 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
438 private handleError (err: any) {
439 const errorMessage: string = typeof err === 'string' ? err : err.message
440 if (!errorMessage) return
442 // Display a message in the video player instead of a notification
443 if (errorMessage.indexOf('from xs param') !== -1) {
445 this.remoteServerDown = true
446 this.changeDetector.detectChanges()
451 this.notifier.error(errorMessage)
454 private checkUserRating () {
455 // Unlogged users do not have ratings
456 if (this.isUserLoggedIn() === false) return
458 this.videoService.getUserVideoRating(this.video.id)
462 this.userRating = ratingObject.rating
466 err => this.notifier.error(err.message)
470 private async onVideoFetched (
472 videoCaptions: VideoCaption[],
473 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
476 this.videoCaptions = videoCaptions
478 // Re init attributes
479 this.descriptionLoading = false
480 this.completeDescriptionShown = false
481 this.remoteServerDown = false
482 this.currentTime = undefined
484 if (this.isVideoBlur(this.video)) {
485 const res = await this.confirmService.confirm(
486 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
487 $localize`Mature or explicit content`
489 if (res === false) return this.location.back()
492 // Flush old player if needed
495 // Build video element, because videojs removes it on dispose
496 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
497 this.playerElement = document.createElement('video')
498 this.playerElement.className = 'video-js vjs-peertube-skin'
499 this.playerElement.setAttribute('playsinline', 'true')
500 playerElementWrapper.appendChild(this.playerElement)
508 const { playerMode, playerOptions } = await this.hooks.wrapFun(
509 this.buildPlayerManagerOptions.bind(this),
512 'filter:internal.video-watch.player.build-options.params',
513 'filter:internal.video-watch.player.build-options.result'
516 this.zone.runOutsideAngular(async () => {
517 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
519 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
521 this.player.on('timeupdate', () => {
522 this.currentTime = Math.floor(this.player.currentTime())
526 * replaces this.player.one('ended')
527 * 'condition()': true to make the upnext functionality trigger,
528 * false to disable the upnext functionality
529 * go to the next video in 'condition()' if you don't want of the timer.
530 * 'next': function triggered at the end of the timer.
531 * 'suspended': function used at each clic of the timer checking if we need
532 * to reset progress and wait until 'suspended' becomes truthy again.
535 timeout: 10000, // 10s
536 headText: $localize`Up Next`,
537 cancelText: $localize`Cancel`,
538 suspendedText: $localize`Autoplay is suspended`,
539 getTitle: () => this.nextVideoTitle,
540 next: () => this.zone.run(() => this.autoplayNext()),
543 if (this.isPlaylistAutoPlayEnabled()) {
544 // upnext will not trigger, and instead the next video will play immediately
545 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
547 } else if (this.isAutoPlayEnabled()) {
548 return true // upnext will trigger
550 return false // upnext will not trigger, and instead leave the video stopping
554 !isXPercentInViewport(this.player.el(), 80) ||
555 !document.getElementById('content').contains(document.activeElement)
560 this.player.one('stopped', () => {
562 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
566 this.player.on('theaterChange', (_: any, enabled: boolean) => {
567 this.zone.run(() => this.theaterEnabled = enabled)
570 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
573 this.setVideoDescriptionHTML()
574 this.setVideoLikesBarTooltipText()
576 this.setOpenGraphTags()
577 this.checkUserRating()
579 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
582 private autoplayNext () {
584 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
585 } else if (this.nextVideoUuid) {
586 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
590 private setRating (nextRating: UserVideoRateType) {
591 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
592 like: this.videoService.setVideoLike,
593 dislike: this.videoService.setVideoDislike,
594 none: this.videoService.unsetVideoLike
597 ratingMethods[nextRating].call(this.videoService, this.video.id)
600 // Update the video like attribute
601 this.updateVideoRating(this.userRating, nextRating)
602 this.userRating = nextRating
605 (err: { message: string }) => this.notifier.error(err.message)
609 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
610 let likesToIncrement = 0
611 let dislikesToIncrement = 0
614 if (oldRating === 'like') likesToIncrement--
615 if (oldRating === 'dislike') dislikesToIncrement--
618 if (newRating === 'like') likesToIncrement++
619 if (newRating === 'dislike') dislikesToIncrement++
621 this.video.likes += likesToIncrement
622 this.video.dislikes += dislikesToIncrement
624 this.video.buildLikeAndDislikePercents()
625 this.setVideoLikesBarTooltipText()
628 private setOpenGraphTags () {
629 this.metaService.setTitle(this.video.name)
631 this.metaService.setTag('og:type', 'video')
633 this.metaService.setTag('og:title', this.video.name)
634 this.metaService.setTag('name', this.video.name)
636 this.metaService.setTag('og:description', this.video.description)
637 this.metaService.setTag('description', this.video.description)
639 this.metaService.setTag('og:image', this.video.previewPath)
641 this.metaService.setTag('og:duration', this.video.duration.toString())
643 this.metaService.setTag('og:site_name', 'PeerTube')
645 this.metaService.setTag('og:url', window.location.href)
646 this.metaService.setTag('url', window.location.href)
649 private isAutoplay () {
650 // We'll jump to the thread id, so do not play the video
651 if (this.route.snapshot.params['threadId']) return false
653 // Otherwise true by default
654 if (!this.user) return true
656 // Be sure the autoPlay is set to false
657 return this.user.autoPlayVideo !== false
660 private flushPlayer () {
661 // Remove player if it exists
664 this.player.dispose()
665 this.player = undefined
667 console.error('Cannot dispose player.', err)
672 private buildPlayerManagerOptions (params: {
674 videoCaptions: VideoCaption[],
675 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
678 const { video, videoCaptions, urlOptions, user } = params
679 const getStartTime = () => {
680 const byUrl = urlOptions.startTime !== undefined
681 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
683 if (byUrl) return timeToInt(urlOptions.startTime)
684 if (byHistory) return video.userHistory.currentTime
689 let startTime = getStartTime()
691 // If we are at the end of the video, reset the timer
692 if (video.duration - startTime <= 1) startTime = 0
694 const playerCaptions = videoCaptions.map(c => ({
695 label: c.language.label,
696 language: c.language.id,
697 src: environment.apiUrl + c.captionPath
700 const options: PeertubePlayerManagerOptions = {
702 autoplay: this.isAutoplay(),
703 nextVideo: () => this.zone.run(() => this.autoplayNext()),
705 playerElement: this.playerElement,
706 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
708 videoDuration: video.duration,
710 inactivityTimeout: 2500,
711 poster: video.previewUrl,
714 stopTime: urlOptions.stopTime,
715 controls: urlOptions.controls,
716 muted: urlOptions.muted,
717 loop: urlOptions.loop,
718 subtitle: urlOptions.subtitle,
720 peertubeLink: urlOptions.peertubeLink,
723 captions: videoCaptions.length !== 0,
725 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
726 ? this.videoService.getVideoViewUrl(video.uuid)
728 embedUrl: video.embedUrl,
730 language: this.localeId,
732 userWatching: user && user.videosHistoryEnabled === true ? {
733 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
734 authorizationHeader: this.authService.getRequestHeaderValue()
737 serverUrl: environment.apiUrl,
739 videoCaptions: playerCaptions
743 videoFiles: video.files
749 if (urlOptions.playerMode) {
750 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
751 else mode = 'webtorrent'
753 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
754 else mode = 'webtorrent'
757 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
758 if (typeof TextEncoder === 'undefined') {
762 if (mode === 'p2p-media-loader') {
763 const hlsPlaylist = video.getHlsPlaylist()
765 const p2pMediaLoader = {
766 playlistUrl: hlsPlaylist.playlistUrl,
767 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
768 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
769 trackerAnnounce: video.trackerUrls,
770 videoFiles: hlsPlaylist.files
771 } as P2PMediaLoaderOptions
773 Object.assign(options, { p2pMediaLoader })
776 return { playerMode: mode, playerOptions: options }
779 private pausePlayer () {
780 if (!this.player) return
785 private resumePlayer () {
786 if (!this.player) return
791 private isPlaying () {
792 if (!this.player) return
794 return !this.player.paused()
797 private initHotkeys () {
799 // These hotkeys are managed by the player
800 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
801 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
802 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
804 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)`),
806 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
807 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
809 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
810 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
812 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
813 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
815 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
818 if (this.isUserLoggedIn()) {
819 this.hotkeys = this.hotkeys.concat([
820 new Hotkey('shift+l', () => {
823 }, undefined, $localize`Like the video`),
825 new Hotkey('shift+d', () => {
828 }, undefined, $localize`Dislike the video`),
830 new Hotkey('shift+s', () => {
831 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
833 }, undefined, $localize`Subscribe to the account`)
837 this.hotkeysService.add(this.hotkeys)