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 } 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 * define 'condition(next)' to return true to wait, false to stop
484 timeout: 10000, // 10s
485 headText: this.i18n('Up Next'),
486 cancelText: this.i18n('Cancel'),
487 getTitle: () => this.nextVideoTitle,
488 next: () => this.zone.run(() => this.autoplayNext()),
491 if (this.isPlaylistAutoPlayEnabled()) {
492 // upnext will not trigger, and instead the next video will play immediately
493 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
495 } else if (this.isAutoPlayEnabled()) {
496 return true // upnext will trigger
498 return false // upnext will not trigger, and instead leave the video stopping
502 this.player.one('stopped', () => {
504 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
508 this.player.on('theaterChange', (_: any, enabled: boolean) => {
509 this.zone.run(() => this.theaterEnabled = enabled)
512 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
515 this.setVideoDescriptionHTML()
516 this.setVideoLikesBarTooltipText()
518 this.setOpenGraphTags()
519 this.checkUserRating()
521 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
524 private autoplayNext () {
525 if (this.nextVideoUuid) {
526 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
530 private setRating (nextRating: UserVideoRateType) {
531 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
532 like: this.videoService.setVideoLike,
533 dislike: this.videoService.setVideoDislike,
534 none: this.videoService.unsetVideoLike
537 ratingMethods[nextRating].call(this.videoService, this.video.id)
540 // Update the video like attribute
541 this.updateVideoRating(this.userRating, nextRating)
542 this.userRating = nextRating
545 (err: { message: string }) => this.notifier.error(err.message)
549 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
550 let likesToIncrement = 0
551 let dislikesToIncrement = 0
554 if (oldRating === 'like') likesToIncrement--
555 if (oldRating === 'dislike') dislikesToIncrement--
558 if (newRating === 'like') likesToIncrement++
559 if (newRating === 'dislike') dislikesToIncrement++
561 this.video.likes += likesToIncrement
562 this.video.dislikes += dislikesToIncrement
564 this.video.buildLikeAndDislikePercents()
565 this.setVideoLikesBarTooltipText()
568 private setOpenGraphTags () {
569 this.metaService.setTitle(this.video.name)
571 this.metaService.setTag('og:type', 'video')
573 this.metaService.setTag('og:title', this.video.name)
574 this.metaService.setTag('name', this.video.name)
576 this.metaService.setTag('og:description', this.video.description)
577 this.metaService.setTag('description', this.video.description)
579 this.metaService.setTag('og:image', this.video.previewPath)
581 this.metaService.setTag('og:duration', this.video.duration.toString())
583 this.metaService.setTag('og:site_name', 'PeerTube')
585 this.metaService.setTag('og:url', window.location.href)
586 this.metaService.setTag('url', window.location.href)
589 private isAutoplay () {
590 // We'll jump to the thread id, so do not play the video
591 if (this.route.snapshot.params['threadId']) return false
593 // Otherwise true by default
594 if (!this.user) return true
596 // Be sure the autoPlay is set to false
597 return this.user.autoPlayVideo !== false
600 private flushPlayer () {
601 // Remove player if it exists
604 this.player.dispose()
605 this.player = undefined
607 console.error('Cannot dispose player.', err)
612 private buildPlayerManagerOptions (params: {
614 videoCaptions: VideoCaption[],
615 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
618 const { video, videoCaptions, urlOptions, user } = params
619 const getStartTime = () => {
620 const byUrl = urlOptions.startTime !== undefined
621 const byHistory = video.userHistory && !this.playlist
624 return timeToInt(urlOptions.startTime)
625 } else if (byHistory) {
626 return video.userHistory.currentTime
632 let startTime = getStartTime()
633 // If we are at the end of the video, reset the timer
634 if (video.duration - startTime <= 1) startTime = 0
636 const playerCaptions = videoCaptions.map(c => ({
637 label: c.language.label,
638 language: c.language.id,
639 src: environment.apiUrl + c.captionPath
642 const options: PeertubePlayerManagerOptions = {
644 autoplay: this.isAutoplay(),
646 playerElement: this.playerElement,
647 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
649 videoDuration: video.duration,
651 inactivityTimeout: 2500,
652 poster: video.previewUrl,
655 stopTime: urlOptions.stopTime,
656 controls: urlOptions.controls,
657 muted: urlOptions.muted,
658 loop: urlOptions.loop,
659 subtitle: urlOptions.subtitle,
661 peertubeLink: urlOptions.peertubeLink,
664 captions: videoCaptions.length !== 0,
666 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
667 ? this.videoService.getVideoViewUrl(video.uuid)
669 embedUrl: video.embedUrl,
671 language: this.localeId,
673 userWatching: user && user.videosHistoryEnabled === true ? {
674 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
675 authorizationHeader: this.authService.getRequestHeaderValue()
678 serverUrl: environment.apiUrl,
680 videoCaptions: playerCaptions
684 videoFiles: video.files
690 if (urlOptions.playerMode) {
691 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
692 else mode = 'webtorrent'
694 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
695 else mode = 'webtorrent'
698 if (mode === 'p2p-media-loader') {
699 const hlsPlaylist = video.getHlsPlaylist()
701 const p2pMediaLoader = {
702 playlistUrl: hlsPlaylist.playlistUrl,
703 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
704 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
705 trackerAnnounce: video.trackerUrls,
706 videoFiles: hlsPlaylist.files
707 } as P2PMediaLoaderOptions
709 Object.assign(options, { p2pMediaLoader })
712 return { playerMode: mode, playerOptions: options }
715 private pausePlayer () {
716 if (!this.player) return
721 private initHotkeys () {
723 // These hotkeys are managed by the player
724 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
725 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
726 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
728 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)')),
730 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
731 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
733 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
734 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
736 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
737 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
739 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
742 if (this.isUserLoggedIn()) {
743 this.hotkeys = this.hotkeys.concat([
744 new Hotkey('shift+l', () => {
747 }, undefined, this.i18n('Like the video')),
749 new Hotkey('shift+d', () => {
752 }, undefined, this.i18n('Dislike the video')),
754 new Hotkey('shift+s', () => {
755 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
757 }, undefined, this.i18n('Subscribe to the account'))
761 this.hotkeysService.add(this.hotkeys)