1 import { catchError } from 'rxjs/operators'
2 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { RedirectService } from '@app/core/routing/redirect.service'
5 import { peertubeLocalStorage } from '@app/shared/misc/peertube-web-storage'
6 import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
7 import { MetaService } from '@ngx-meta/core'
8 import { AuthUser, Notifier, ServerService } from '@app/core'
9 import { forkJoin, Observable, Subscription } from 'rxjs'
10 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
11 import { ServerConfig, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
12 import { AuthService, ConfirmService } from '../../core'
13 import { RestExtractor, UserService } from '../../shared'
14 import { VideoDetails } from '../../shared/video/video-details.model'
15 import { VideoService } from '../../shared/video/video.service'
16 import { VideoShareComponent } from './modal/video-share.component'
17 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
18 import { I18n } from '@ngx-translate/i18n-polyfill'
19 import { environment } from '../../../environments/environment'
20 import { VideoCaptionService } from '@app/shared/video-caption'
21 import { MarkdownService } from '@app/shared/renderer'
25 P2PMediaLoaderOptions,
26 PeertubePlayerManager,
27 PeertubePlayerManagerOptions,
29 } from '../../../assets/player/peertube-player-manager'
30 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
31 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
32 import { Video } from '@app/shared/video/video.model'
33 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
34 import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
35 import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
36 import { HooksService } from '@app/core/plugins/hooks.service'
37 import { PlatformLocation } from '@angular/common'
38 import { scrollToTop, isXPercentInViewport } from '@app/shared/misc/utils'
41 selector: 'my-video-watch',
42 templateUrl: './video-watch.component.html',
43 styleUrls: [ './video-watch.component.scss' ]
45 export class VideoWatchComponent implements OnInit, OnDestroy {
46 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
48 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
49 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
50 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
51 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
54 playerElement: HTMLVideoElement
55 theaterEnabled = false
56 userRating: UserVideoRateType = null
57 descriptionLoading = false
59 video: VideoDetails = null
60 videoCaptions: VideoCaption[] = []
62 playlist: VideoPlaylist = null
64 completeDescriptionShown = false
65 completeVideoDescription: string
66 shortVideoDescription: string
67 videoHTMLDescription = ''
68 likesBarTooltipText = ''
69 hasAlreadyAcceptedPrivacyConcern = false
70 remoteServerDown = false
71 hotkeys: Hotkey[] = []
76 tooltipSaveToPlaylist = ''
78 private nextVideoUuid = ''
79 private nextVideoTitle = ''
80 private currentTime: number
81 private paramsSub: Subscription
82 private queryParamsSub: Subscription
83 private configSub: Subscription
85 private serverConfig: ServerConfig
88 private elementRef: ElementRef,
89 private changeDetector: ChangeDetectorRef,
90 private route: ActivatedRoute,
91 private router: Router,
92 private videoService: VideoService,
93 private playlistService: VideoPlaylistService,
94 private confirmService: ConfirmService,
95 private metaService: MetaService,
96 private authService: AuthService,
97 private userService: UserService,
98 private serverService: ServerService,
99 private restExtractor: RestExtractor,
100 private notifier: Notifier,
101 private markdownService: MarkdownService,
102 private zone: NgZone,
103 private redirectService: RedirectService,
104 private videoCaptionService: VideoCaptionService,
106 private hotkeysService: HotkeysService,
107 private hooks: HooksService,
108 private location: PlatformLocation,
109 @Inject(LOCALE_ID) private localeId: string
111 this.tooltipLike = this.i18n('Like this video')
112 this.tooltipDislike = this.i18n('Dislike this video')
113 this.tooltipSupport = this.i18n('Support options for this video')
114 this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
118 return this.authService.getUser()
121 get anonymousUser () {
122 return this.userService.getAnonymousUser()
126 this.serverConfig = this.serverService.getTmpConfig()
128 this.configSub = this.serverService.getConfig()
129 .subscribe(config => {
130 this.serverConfig = config
133 isWebRTCDisabled() ||
134 this.serverConfig.tracker.enabled === false ||
135 getStoredP2PEnabled() === false ||
136 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
138 this.hasAlreadyAcceptedPrivacyConcern = true
142 this.paramsSub = this.route.params.subscribe(routeParams => {
143 const videoId = routeParams[ 'videoId' ]
144 if (videoId) this.loadVideo(videoId)
146 const playlistId = routeParams[ 'playlistId' ]
147 if (playlistId) this.loadPlaylist(playlistId)
150 this.queryParamsSub = this.route.queryParams.subscribe(async queryParams => {
151 const videoId = queryParams[ 'videoId' ]
152 if (videoId) this.loadVideo(videoId)
154 const start = queryParams[ 'start' ]
155 if (this.player && start) this.player.currentTime(parseInt(start, 10))
160 this.theaterEnabled = getStoredTheater()
162 this.hooks.runAction('action:video-watch.init', 'video-watch')
168 // Unsubscribe subscriptions
169 if (this.paramsSub) this.paramsSub.unsubscribe()
170 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
173 this.hotkeysService.remove(this.hotkeys)
177 if (this.isUserLoggedIn() === false) return
179 // Already liked this video
180 if (this.userRating === 'like') this.setRating('none')
181 else this.setRating('like')
185 if (this.isUserLoggedIn() === false) return
187 // Already disliked this video
188 if (this.userRating === 'dislike') this.setRating('none')
189 else this.setRating('dislike')
192 getRatePopoverText () {
193 if (this.isUserLoggedIn()) return undefined
195 return this.i18n('You need to be connected to rate this content.')
198 showMoreDescription () {
199 if (this.completeVideoDescription === undefined) {
200 return this.loadCompleteDescription()
203 this.updateVideoDescription(this.completeVideoDescription)
204 this.completeDescriptionShown = true
207 showLessDescription () {
208 this.updateVideoDescription(this.shortVideoDescription)
209 this.completeDescriptionShown = false
212 loadCompleteDescription () {
213 this.descriptionLoading = true
215 this.videoService.loadCompleteDescription(this.video.descriptionPath)
218 this.completeDescriptionShown = true
219 this.descriptionLoading = false
221 this.shortVideoDescription = this.video.description
222 this.completeVideoDescription = description
224 this.updateVideoDescription(this.completeVideoDescription)
228 this.descriptionLoading = false
229 this.notifier.error(error.message)
234 showSupportModal () {
237 this.videoSupportModal.show()
243 this.videoShareModal.show(this.currentTime)
247 return this.authService.isLoggedIn()
251 if (!this.video || Array.isArray(this.video.tags) === false) return []
253 return this.video.tags
256 onRecommendations (videos: Video[]) {
257 if (videos.length > 0) {
258 // The recommended videos's first element should be the next video
259 const video = videos[0]
260 this.nextVideoUuid = video.uuid
261 this.nextVideoTitle = video.name
270 this.redirectService.redirectToHomepage()
273 declinedPrivacyConcern () {
274 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
275 this.hasAlreadyAcceptedPrivacyConcern = false
278 acceptedPrivacyConcern () {
279 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
280 this.hasAlreadyAcceptedPrivacyConcern = true
283 isVideoToTranscode () {
284 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
288 return this.video && this.video.state.id === VideoState.TO_IMPORT
291 hasVideoScheduledPublication () {
292 return this.video && this.video.scheduledUpdate !== undefined
295 isVideoBlur (video: Video) {
296 return video.isVideoNSFWForUser(this.user, this.serverConfig)
299 isAutoPlayEnabled () {
301 (this.user && this.user.autoPlayNextVideo) ||
302 this.anonymousUser.autoPlayNextVideo
306 handleTimestampClicked (timestamp: number) {
307 if (this.player) this.player.currentTime(timestamp)
311 isPlaylistAutoPlayEnabled () {
313 (this.user && this.user.autoPlayNextVideoPlaylist) ||
314 this.anonymousUser.autoPlayNextVideoPlaylist
318 private loadVideo (videoId: string) {
319 // Video did not change
320 if (this.video && this.video.uuid === videoId) return
322 if (this.player) this.player.pause()
324 const videoObs = this.hooks.wrapObsFun(
325 this.videoService.getVideo.bind(this.videoService),
328 'filter:api.video-watch.video.get.params',
329 'filter:api.video-watch.video.get.result'
335 this.videoCaptionService.listCaptions(videoId)
338 // If 401, the video is private or blacklisted so redirect to 404
339 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
341 .subscribe(([ video, captionsResult ]) => {
342 const queryParams = this.route.snapshot.queryParams
345 startTime: queryParams.start,
346 stopTime: queryParams.stop,
348 muted: queryParams.muted,
349 loop: queryParams.loop,
350 subtitle: queryParams.subtitle,
352 playerMode: queryParams.mode,
356 this.onVideoFetched(video, captionsResult.data, urlOptions)
357 .catch(err => this.handleError(err))
361 private loadPlaylist (playlistId: string) {
362 // Playlist did not change
363 if (this.playlist && this.playlist.uuid === playlistId) return
365 this.playlistService.getVideoPlaylist(playlistId)
367 // If 401, the video is private or blacklisted so redirect to 404
368 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
370 .subscribe(playlist => {
371 this.playlist = playlist
373 const videoId = this.route.snapshot.queryParams['videoId']
374 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
378 private updateVideoDescription (description: string) {
379 this.video.description = description
380 this.setVideoDescriptionHTML()
381 .catch(err => console.error(err))
384 private async setVideoDescriptionHTML () {
385 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
386 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
389 private setVideoLikesBarTooltipText () {
390 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
391 likesNumber: this.video.likes,
392 dislikesNumber: this.video.dislikes
396 private handleError (err: any) {
397 const errorMessage: string = typeof err === 'string' ? err : err.message
398 if (!errorMessage) return
400 // Display a message in the video player instead of a notification
401 if (errorMessage.indexOf('from xs param') !== -1) {
403 this.remoteServerDown = true
404 this.changeDetector.detectChanges()
409 this.notifier.error(errorMessage)
412 private checkUserRating () {
413 // Unlogged users do not have ratings
414 if (this.isUserLoggedIn() === false) return
416 this.videoService.getUserVideoRating(this.video.id)
420 this.userRating = ratingObject.rating
424 err => this.notifier.error(err.message)
428 private async onVideoFetched (
430 videoCaptions: VideoCaption[],
431 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
434 this.videoCaptions = videoCaptions
436 // Re init attributes
437 this.descriptionLoading = false
438 this.completeDescriptionShown = false
439 this.remoteServerDown = false
440 this.currentTime = undefined
442 this.videoWatchPlaylist.updatePlaylistIndex(video)
444 if (this.isVideoBlur(this.video)) {
445 const res = await this.confirmService.confirm(
446 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
447 this.i18n('Mature or explicit content')
449 if (res === false) return this.location.back()
452 // Flush old player if needed
455 // Build video element, because videojs removes it on dispose
456 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
457 this.playerElement = document.createElement('video')
458 this.playerElement.className = 'video-js vjs-peertube-skin'
459 this.playerElement.setAttribute('playsinline', 'true')
460 playerElementWrapper.appendChild(this.playerElement)
468 const { playerMode, playerOptions } = await this.hooks.wrapFun(
469 this.buildPlayerManagerOptions.bind(this),
472 'filter:internal.video-watch.player.build-options.params',
473 'filter:internal.video-watch.player.build-options.result'
476 this.zone.runOutsideAngular(async () => {
477 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
480 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
482 this.player.on('timeupdate', () => {
483 this.currentTime = Math.floor(this.player.currentTime())
487 * replaces this.player.one('ended')
488 * 'condition()': true to make the upnext functionality trigger,
489 * false to disable the upnext functionality
490 * go to the next video in 'condition()' if you don't want of the timer.
491 * 'next': function triggered at the end of the timer.
492 * 'suspended': function used at each clic of the timer checking if we need
493 * to reset progress and wait until 'suspended' becomes truthy again.
496 timeout: 10000, // 10s
497 headText: this.i18n('Up Next'),
498 cancelText: this.i18n('Cancel'),
499 suspendedText: this.i18n('Autoplay is suspended'),
500 getTitle: () => this.nextVideoTitle,
501 next: () => this.zone.run(() => this.autoplayNext()),
504 if (this.isPlaylistAutoPlayEnabled()) {
505 // upnext will not trigger, and instead the next video will play immediately
506 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
508 } else if (this.isAutoPlayEnabled()) {
509 return true // upnext will trigger
511 return false // upnext will not trigger, and instead leave the video stopping
515 !isXPercentInViewport(this.player.el(), 80) ||
516 !document.getElementById('content').contains(document.activeElement)
521 this.player.one('stopped', () => {
523 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
527 this.player.on('theaterChange', (_: any, enabled: boolean) => {
528 this.zone.run(() => this.theaterEnabled = enabled)
531 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
534 this.setVideoDescriptionHTML()
535 this.setVideoLikesBarTooltipText()
537 this.setOpenGraphTags()
538 this.checkUserRating()
540 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
543 private autoplayNext () {
545 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
546 } else if (this.nextVideoUuid) {
547 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
551 private setRating (nextRating: UserVideoRateType) {
552 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
553 like: this.videoService.setVideoLike,
554 dislike: this.videoService.setVideoDislike,
555 none: this.videoService.unsetVideoLike
558 ratingMethods[nextRating].call(this.videoService, this.video.id)
561 // Update the video like attribute
562 this.updateVideoRating(this.userRating, nextRating)
563 this.userRating = nextRating
566 (err: { message: string }) => this.notifier.error(err.message)
570 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
571 let likesToIncrement = 0
572 let dislikesToIncrement = 0
575 if (oldRating === 'like') likesToIncrement--
576 if (oldRating === 'dislike') dislikesToIncrement--
579 if (newRating === 'like') likesToIncrement++
580 if (newRating === 'dislike') dislikesToIncrement++
582 this.video.likes += likesToIncrement
583 this.video.dislikes += dislikesToIncrement
585 this.video.buildLikeAndDislikePercents()
586 this.setVideoLikesBarTooltipText()
589 private setOpenGraphTags () {
590 this.metaService.setTitle(this.video.name)
592 this.metaService.setTag('og:type', 'video')
594 this.metaService.setTag('og:title', this.video.name)
595 this.metaService.setTag('name', this.video.name)
597 this.metaService.setTag('og:description', this.video.description)
598 this.metaService.setTag('description', this.video.description)
600 this.metaService.setTag('og:image', this.video.previewPath)
602 this.metaService.setTag('og:duration', this.video.duration.toString())
604 this.metaService.setTag('og:site_name', 'PeerTube')
606 this.metaService.setTag('og:url', window.location.href)
607 this.metaService.setTag('url', window.location.href)
610 private isAutoplay () {
611 // We'll jump to the thread id, so do not play the video
612 if (this.route.snapshot.params['threadId']) return false
614 // Otherwise true by default
615 if (!this.user) return true
617 // Be sure the autoPlay is set to false
618 return this.user.autoPlayVideo !== false
621 private flushPlayer () {
622 // Remove player if it exists
625 this.player.dispose()
626 this.player = undefined
628 console.error('Cannot dispose player.', err)
633 private buildPlayerManagerOptions (params: {
635 videoCaptions: VideoCaption[],
636 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
639 const { video, videoCaptions, urlOptions, user } = params
640 const getStartTime = () => {
641 const byUrl = urlOptions.startTime !== undefined
642 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
645 return timeToInt(urlOptions.startTime)
646 } else if (byHistory) {
647 return video.userHistory.currentTime
653 let startTime = getStartTime()
654 // If we are at the end of the video, reset the timer
655 if (video.duration - startTime <= 1) startTime = 0
657 const playerCaptions = videoCaptions.map(c => ({
658 label: c.language.label,
659 language: c.language.id,
660 src: environment.apiUrl + c.captionPath
663 const options: PeertubePlayerManagerOptions = {
665 autoplay: this.isAutoplay(),
666 nextVideo: () => this.zone.run(() => this.autoplayNext()),
668 playerElement: this.playerElement,
669 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
671 videoDuration: video.duration,
673 inactivityTimeout: 2500,
674 poster: video.previewUrl,
677 stopTime: urlOptions.stopTime,
678 controls: urlOptions.controls,
679 muted: urlOptions.muted,
680 loop: urlOptions.loop,
681 subtitle: urlOptions.subtitle,
683 peertubeLink: urlOptions.peertubeLink,
686 captions: videoCaptions.length !== 0,
688 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
689 ? this.videoService.getVideoViewUrl(video.uuid)
691 embedUrl: video.embedUrl,
693 language: this.localeId,
695 userWatching: user && user.videosHistoryEnabled === true ? {
696 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
697 authorizationHeader: this.authService.getRequestHeaderValue()
700 serverUrl: environment.apiUrl,
702 videoCaptions: playerCaptions
706 videoFiles: video.files
712 if (urlOptions.playerMode) {
713 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
714 else mode = 'webtorrent'
716 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
717 else mode = 'webtorrent'
720 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
721 if (typeof TextEncoder === 'undefined') {
725 if (mode === 'p2p-media-loader') {
726 const hlsPlaylist = video.getHlsPlaylist()
728 const p2pMediaLoader = {
729 playlistUrl: hlsPlaylist.playlistUrl,
730 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
731 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
732 trackerAnnounce: video.trackerUrls,
733 videoFiles: hlsPlaylist.files
734 } as P2PMediaLoaderOptions
736 Object.assign(options, { p2pMediaLoader })
739 return { playerMode: mode, playerOptions: options }
742 private pausePlayer () {
743 if (!this.player) return
748 private initHotkeys () {
750 // These hotkeys are managed by the player
751 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
752 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
753 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
755 new Hotkey('0-9', e => e, undefined, this.i18n('Skip to a percentage of the video: 0 is 0% and 9 is 90% (requires player focus)')),
757 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
758 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
760 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
761 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
763 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
764 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
766 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
769 if (this.isUserLoggedIn()) {
770 this.hotkeys = this.hotkeys.concat([
771 new Hotkey('shift+l', () => {
774 }, undefined, this.i18n('Like the video')),
776 new Hotkey('shift+d', () => {
779 }, undefined, this.i18n('Dislike the video')),
781 new Hotkey('shift+s', () => {
782 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
784 }, undefined, this.i18n('Subscribe to the account'))
788 this.hotkeysService.add(this.hotkeys)