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, peertubeSessionStorage } 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, VideoBlacklistService } 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 { getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
36 import { PluginService } from '@app/core/plugins/plugin.service'
37 import { HooksService } from '@app/core/plugins/hooks.service'
38 import { PlatformLocation } from '@angular/common'
39 import { RecommendedVideosComponent } from '../recommendations/recommended-videos.component'
40 import { scrollToTop, isInViewport, isXPercentInViewport } from '@app/shared/misc/utils'
43 selector: 'my-video-watch',
44 templateUrl: './video-watch.component.html',
45 styleUrls: [ './video-watch.component.scss' ]
47 export class VideoWatchComponent implements OnInit, OnDestroy {
48 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
50 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
51 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
52 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
53 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
56 playerElement: HTMLVideoElement
57 theaterEnabled = false
58 userRating: UserVideoRateType = null
59 descriptionLoading = false
61 video: VideoDetails = null
62 videoCaptions: VideoCaption[] = []
64 playlist: VideoPlaylist = null
66 completeDescriptionShown = false
67 completeVideoDescription: string
68 shortVideoDescription: string
69 videoHTMLDescription = ''
70 likesBarTooltipText = ''
71 hasAlreadyAcceptedPrivacyConcern = false
72 remoteServerDown = false
73 hotkeys: Hotkey[] = []
78 tooltipSaveToPlaylist = ''
80 private nextVideoUuid = ''
81 private nextVideoTitle = ''
82 private currentTime: number
83 private paramsSub: Subscription
84 private queryParamsSub: Subscription
85 private configSub: Subscription
87 private serverConfig: ServerConfig
90 private elementRef: ElementRef,
91 private changeDetector: ChangeDetectorRef,
92 private route: ActivatedRoute,
93 private router: Router,
94 private videoService: VideoService,
95 private playlistService: VideoPlaylistService,
96 private videoBlacklistService: VideoBlacklistService,
97 private confirmService: ConfirmService,
98 private metaService: MetaService,
99 private authService: AuthService,
100 private serverService: ServerService,
101 private restExtractor: RestExtractor,
102 private notifier: Notifier,
103 private pluginService: PluginService,
104 private markdownService: MarkdownService,
105 private zone: NgZone,
106 private redirectService: RedirectService,
107 private videoCaptionService: VideoCaptionService,
109 private hotkeysService: HotkeysService,
110 private hooks: HooksService,
111 private location: PlatformLocation,
112 @Inject(LOCALE_ID) private localeId: string
114 this.tooltipLike = this.i18n('Like this video')
115 this.tooltipDislike = this.i18n('Dislike this video')
116 this.tooltipSupport = this.i18n('Support options for this video')
117 this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
121 return this.authService.getUser()
125 this.serverConfig = this.serverService.getTmpConfig()
127 this.configSub = this.serverService.getConfig()
128 .subscribe(config => {
129 this.serverConfig = config
132 isWebRTCDisabled() ||
133 this.serverConfig.tracker.enabled === false ||
134 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
136 this.hasAlreadyAcceptedPrivacyConcern = true
140 this.paramsSub = this.route.params.subscribe(routeParams => {
141 const videoId = routeParams[ 'videoId' ]
142 if (videoId) this.loadVideo(videoId)
144 const playlistId = routeParams[ 'playlistId' ]
145 if (playlistId) this.loadPlaylist(playlistId)
148 this.queryParamsSub = this.route.queryParams.subscribe(async queryParams => {
149 const videoId = queryParams[ 'videoId' ]
150 if (videoId) this.loadVideo(videoId)
152 const start = queryParams[ 'start' ]
153 if (this.player && start) this.player.currentTime(parseInt(start, 10))
158 this.theaterEnabled = getStoredTheater()
160 this.hooks.runAction('action:video-watch.init', 'video-watch')
166 // Unsubscribe subscriptions
167 if (this.paramsSub) this.paramsSub.unsubscribe()
168 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
171 this.hotkeysService.remove(this.hotkeys)
175 if (this.isUserLoggedIn() === false) return
177 // Already liked this video
178 if (this.userRating === 'like') this.setRating('none')
179 else this.setRating('like')
183 if (this.isUserLoggedIn() === false) return
185 // Already disliked this video
186 if (this.userRating === 'dislike') this.setRating('none')
187 else this.setRating('dislike')
190 getRatePopoverText () {
191 if (this.isUserLoggedIn()) return undefined
193 return this.i18n('You need to be connected to rate this content.')
196 showMoreDescription () {
197 if (this.completeVideoDescription === undefined) {
198 return this.loadCompleteDescription()
201 this.updateVideoDescription(this.completeVideoDescription)
202 this.completeDescriptionShown = true
205 showLessDescription () {
206 this.updateVideoDescription(this.shortVideoDescription)
207 this.completeDescriptionShown = false
210 loadCompleteDescription () {
211 this.descriptionLoading = true
213 this.videoService.loadCompleteDescription(this.video.descriptionPath)
216 this.completeDescriptionShown = true
217 this.descriptionLoading = false
219 this.shortVideoDescription = this.video.description
220 this.completeVideoDescription = description
222 this.updateVideoDescription(this.completeVideoDescription)
226 this.descriptionLoading = false
227 this.notifier.error(error.message)
232 showSupportModal () {
235 this.videoSupportModal.show()
241 this.videoShareModal.show(this.currentTime)
245 return this.authService.isLoggedIn()
249 if (!this.video || Array.isArray(this.video.tags) === false) return []
251 return this.video.tags
254 onRecommendations (videos: Video[]) {
255 if (videos.length > 0) {
256 // The recommended videos's first element should be the next video
257 const video = videos[0]
258 this.nextVideoUuid = video.uuid
259 this.nextVideoTitle = video.name
268 this.redirectService.redirectToHomepage()
271 acceptedPrivacyConcern () {
272 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
273 this.hasAlreadyAcceptedPrivacyConcern = true
276 isVideoToTranscode () {
277 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
281 return this.video && this.video.state.id === VideoState.TO_IMPORT
284 hasVideoScheduledPublication () {
285 return this.video && this.video.scheduledUpdate !== undefined
288 isVideoBlur (video: Video) {
289 return video.isVideoNSFWForUser(this.user, this.serverConfig)
292 isAutoPlayEnabled () {
294 (this.user && this.user.autoPlayNextVideo) ||
295 peertubeSessionStorage.getItem(RecommendedVideosComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
299 handleTimestampClicked (timestamp: number) {
300 if (this.player) this.player.currentTime(timestamp)
304 isPlaylistAutoPlayEnabled () {
306 (this.user && this.user.autoPlayNextVideoPlaylist) ||
307 peertubeSessionStorage.getItem(VideoWatchPlaylistComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO_PLAYLIST) === 'true'
311 private loadVideo (videoId: string) {
312 // Video did not change
313 if (this.video && this.video.uuid === videoId) return
315 if (this.player) this.player.pause()
317 const videoObs = this.hooks.wrapObsFun(
318 this.videoService.getVideo.bind(this.videoService),
321 'filter:api.video-watch.video.get.params',
322 'filter:api.video-watch.video.get.result'
328 this.videoCaptionService.listCaptions(videoId)
331 // If 401, the video is private or blacklisted so redirect to 404
332 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
334 .subscribe(([ video, captionsResult ]) => {
335 const queryParams = this.route.snapshot.queryParams
338 startTime: queryParams.start,
339 stopTime: queryParams.stop,
341 muted: queryParams.muted,
342 loop: queryParams.loop,
343 subtitle: queryParams.subtitle,
345 playerMode: queryParams.mode,
349 this.onVideoFetched(video, captionsResult.data, urlOptions)
350 .catch(err => this.handleError(err))
354 private loadPlaylist (playlistId: string) {
355 // Playlist did not change
356 if (this.playlist && this.playlist.uuid === playlistId) return
358 this.playlistService.getVideoPlaylist(playlistId)
360 // If 401, the video is private or blacklisted so redirect to 404
361 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
363 .subscribe(playlist => {
364 this.playlist = playlist
366 const videoId = this.route.snapshot.queryParams['videoId']
367 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
371 private updateVideoDescription (description: string) {
372 this.video.description = description
373 this.setVideoDescriptionHTML()
374 .catch(err => console.error(err))
377 private async setVideoDescriptionHTML () {
378 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
379 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
382 private setVideoLikesBarTooltipText () {
383 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
384 likesNumber: this.video.likes,
385 dislikesNumber: this.video.dislikes
389 private handleError (err: any) {
390 const errorMessage: string = typeof err === 'string' ? err : err.message
391 if (!errorMessage) return
393 // Display a message in the video player instead of a notification
394 if (errorMessage.indexOf('from xs param') !== -1) {
396 this.remoteServerDown = true
397 this.changeDetector.detectChanges()
402 this.notifier.error(errorMessage)
405 private checkUserRating () {
406 // Unlogged users do not have ratings
407 if (this.isUserLoggedIn() === false) return
409 this.videoService.getUserVideoRating(this.video.id)
413 this.userRating = ratingObject.rating
417 err => this.notifier.error(err.message)
421 private async onVideoFetched (
423 videoCaptions: VideoCaption[],
424 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
427 this.videoCaptions = videoCaptions
429 // Re init attributes
430 this.descriptionLoading = false
431 this.completeDescriptionShown = false
432 this.remoteServerDown = false
433 this.currentTime = undefined
435 this.videoWatchPlaylist.updatePlaylistIndex(video)
437 if (this.isVideoBlur(this.video)) {
438 const res = await this.confirmService.confirm(
439 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
440 this.i18n('Mature or explicit content')
442 if (res === false) return this.location.back()
445 // Flush old player if needed
448 // Build video element, because videojs removes it on dispose
449 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
450 this.playerElement = document.createElement('video')
451 this.playerElement.className = 'video-js vjs-peertube-skin'
452 this.playerElement.setAttribute('playsinline', 'true')
453 playerElementWrapper.appendChild(this.playerElement)
461 const { playerMode, playerOptions } = await this.hooks.wrapFun(
462 this.buildPlayerManagerOptions.bind(this),
465 'filter:internal.video-watch.player.build-options.params',
466 'filter:internal.video-watch.player.build-options.result'
469 this.zone.runOutsideAngular(async () => {
470 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
473 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
475 this.player.on('timeupdate', () => {
476 this.currentTime = Math.floor(this.player.currentTime())
480 * replaces this.player.one('ended')
481 * 'condition()': true to make the upnext functionality trigger,
482 * false to disable the upnext functionality
483 * go to the next video in 'condition()' if you don't want of the timer.
484 * 'next': function triggered at the end of the timer.
485 * 'suspended': function used at each clic of the timer checking if we need
486 * to reset progress and wait until 'suspended' becomes truthy again.
489 timeout: 10000, // 10s
490 headText: this.i18n('Up Next'),
491 cancelText: this.i18n('Cancel'),
492 suspendedText: this.i18n('Autoplay is suspended'),
493 getTitle: () => this.nextVideoTitle,
494 next: () => this.zone.run(() => this.autoplayNext()),
497 if (this.isPlaylistAutoPlayEnabled()) {
498 // upnext will not trigger, and instead the next video will play immediately
499 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
501 } else if (this.isAutoPlayEnabled()) {
502 return true // upnext will trigger
504 return false // upnext will not trigger, and instead leave the video stopping
508 !isXPercentInViewport(this.player.el(), 80) ||
509 !document.getElementById('content').contains(document.activeElement)
514 this.player.one('stopped', () => {
516 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
520 this.player.on('theaterChange', (_: any, enabled: boolean) => {
521 this.zone.run(() => this.theaterEnabled = enabled)
524 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
527 this.setVideoDescriptionHTML()
528 this.setVideoLikesBarTooltipText()
530 this.setOpenGraphTags()
531 this.checkUserRating()
533 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
536 private autoplayNext () {
537 if (this.nextVideoUuid) {
538 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
542 private setRating (nextRating: UserVideoRateType) {
543 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
544 like: this.videoService.setVideoLike,
545 dislike: this.videoService.setVideoDislike,
546 none: this.videoService.unsetVideoLike
549 ratingMethods[nextRating].call(this.videoService, this.video.id)
552 // Update the video like attribute
553 this.updateVideoRating(this.userRating, nextRating)
554 this.userRating = nextRating
557 (err: { message: string }) => this.notifier.error(err.message)
561 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
562 let likesToIncrement = 0
563 let dislikesToIncrement = 0
566 if (oldRating === 'like') likesToIncrement--
567 if (oldRating === 'dislike') dislikesToIncrement--
570 if (newRating === 'like') likesToIncrement++
571 if (newRating === 'dislike') dislikesToIncrement++
573 this.video.likes += likesToIncrement
574 this.video.dislikes += dislikesToIncrement
576 this.video.buildLikeAndDislikePercents()
577 this.setVideoLikesBarTooltipText()
580 private setOpenGraphTags () {
581 this.metaService.setTitle(this.video.name)
583 this.metaService.setTag('og:type', 'video')
585 this.metaService.setTag('og:title', this.video.name)
586 this.metaService.setTag('name', this.video.name)
588 this.metaService.setTag('og:description', this.video.description)
589 this.metaService.setTag('description', this.video.description)
591 this.metaService.setTag('og:image', this.video.previewPath)
593 this.metaService.setTag('og:duration', this.video.duration.toString())
595 this.metaService.setTag('og:site_name', 'PeerTube')
597 this.metaService.setTag('og:url', window.location.href)
598 this.metaService.setTag('url', window.location.href)
601 private isAutoplay () {
602 // We'll jump to the thread id, so do not play the video
603 if (this.route.snapshot.params['threadId']) return false
605 // Otherwise true by default
606 if (!this.user) return true
608 // Be sure the autoPlay is set to false
609 return this.user.autoPlayVideo !== false
612 private flushPlayer () {
613 // Remove player if it exists
616 this.player.dispose()
617 this.player = undefined
619 console.error('Cannot dispose player.', err)
624 private buildPlayerManagerOptions (params: {
626 videoCaptions: VideoCaption[],
627 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
630 const { video, videoCaptions, urlOptions, user } = params
631 const getStartTime = () => {
632 const byUrl = urlOptions.startTime !== undefined
633 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
636 return timeToInt(urlOptions.startTime)
637 } else if (byHistory) {
638 return video.userHistory.currentTime
644 let startTime = getStartTime()
645 // If we are at the end of the video, reset the timer
646 if (video.duration - startTime <= 1) startTime = 0
648 const playerCaptions = videoCaptions.map(c => ({
649 label: c.language.label,
650 language: c.language.id,
651 src: environment.apiUrl + c.captionPath
654 const options: PeertubePlayerManagerOptions = {
656 autoplay: this.isAutoplay(),
657 nextVideo: () => this.zone.run(() => this.autoplayNext()),
659 playerElement: this.playerElement,
660 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
662 videoDuration: video.duration,
664 inactivityTimeout: 2500,
665 poster: video.previewUrl,
668 stopTime: urlOptions.stopTime,
669 controls: urlOptions.controls,
670 muted: urlOptions.muted,
671 loop: urlOptions.loop,
672 subtitle: urlOptions.subtitle,
674 peertubeLink: urlOptions.peertubeLink,
677 captions: videoCaptions.length !== 0,
679 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
680 ? this.videoService.getVideoViewUrl(video.uuid)
682 embedUrl: video.embedUrl,
684 language: this.localeId,
686 userWatching: user && user.videosHistoryEnabled === true ? {
687 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
688 authorizationHeader: this.authService.getRequestHeaderValue()
691 serverUrl: environment.apiUrl,
693 videoCaptions: playerCaptions
697 videoFiles: video.files
703 if (urlOptions.playerMode) {
704 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
705 else mode = 'webtorrent'
707 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
708 else mode = 'webtorrent'
711 if (mode === 'p2p-media-loader') {
712 const hlsPlaylist = video.getHlsPlaylist()
714 const p2pMediaLoader = {
715 playlistUrl: hlsPlaylist.playlistUrl,
716 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
717 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
718 trackerAnnounce: video.trackerUrls,
719 videoFiles: hlsPlaylist.files
720 } as P2PMediaLoaderOptions
722 Object.assign(options, { p2pMediaLoader })
725 return { playerMode: mode, playerOptions: options }
728 private pausePlayer () {
729 if (!this.player) return
734 private initHotkeys () {
736 // These hotkeys are managed by the player
737 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
738 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
739 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
741 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)')),
743 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
744 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
746 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
747 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
749 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
750 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
752 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
755 if (this.isUserLoggedIn()) {
756 this.hotkeys = this.hotkeys.concat([
757 new Hotkey('shift+l', () => {
760 }, undefined, this.i18n('Like the video')),
762 new Hotkey('shift+d', () => {
765 }, undefined, this.i18n('Dislike the video')),
767 new Hotkey('shift+s', () => {
768 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
770 }, undefined, this.i18n('Subscribe to the account'))
774 this.hotkeysService.add(this.hotkeys)