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 { 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
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 videoBlacklistService: VideoBlacklistService,
95 private confirmService: ConfirmService,
96 private metaService: MetaService,
97 private authService: AuthService,
98 private serverService: ServerService,
99 private restExtractor: RestExtractor,
100 private notifier: Notifier,
101 private pluginService: PluginService,
102 private markdownService: MarkdownService,
103 private zone: NgZone,
104 private redirectService: RedirectService,
105 private videoCaptionService: VideoCaptionService,
107 private hotkeysService: HotkeysService,
108 private hooks: HooksService,
109 private location: PlatformLocation,
110 @Inject(LOCALE_ID) private localeId: string
112 this.tooltipLike = this.i18n('Like this video')
113 this.tooltipDislike = this.i18n('Dislike this video')
114 this.tooltipSupport = this.i18n('Support options for this video')
115 this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
119 return this.authService.getUser()
123 this.configSub = this.serverService.configLoaded
126 isWebRTCDisabled() ||
127 this.serverService.getConfig().tracker.enabled === false ||
128 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
130 this.hasAlreadyAcceptedPrivacyConcern = true
134 this.paramsSub = this.route.params.subscribe(routeParams => {
135 const videoId = routeParams[ 'videoId' ]
136 if (videoId) this.loadVideo(videoId)
138 const playlistId = routeParams[ 'playlistId' ]
139 if (playlistId) this.loadPlaylist(playlistId)
142 this.queryParamsSub = this.route.queryParams.subscribe(async queryParams => {
143 const videoId = queryParams[ 'videoId' ]
144 if (videoId) await this.loadVideo(videoId)
146 const start = queryParams[ 'start' ]
147 if (this.player && start) this.player.currentTime(parseInt(start, 10))
152 this.theaterEnabled = getStoredTheater()
154 this.hooks.runAction('action:video-watch.init', 'video-watch')
160 // Unsubscribe subscriptions
161 if (this.paramsSub) this.paramsSub.unsubscribe()
162 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
165 this.hotkeysService.remove(this.hotkeys)
169 if (this.isUserLoggedIn() === false) return
171 // Already liked this video
172 if (this.userRating === 'like') this.setRating('none')
173 else this.setRating('like')
177 if (this.isUserLoggedIn() === false) return
179 // Already disliked this video
180 if (this.userRating === 'dislike') this.setRating('none')
181 else this.setRating('dislike')
184 getRatePopoverText () {
185 if (this.isUserLoggedIn()) return undefined
187 return this.i18n('You need to be connected to rate this content.')
190 showMoreDescription () {
191 if (this.completeVideoDescription === undefined) {
192 return this.loadCompleteDescription()
195 this.updateVideoDescription(this.completeVideoDescription)
196 this.completeDescriptionShown = true
199 showLessDescription () {
200 this.updateVideoDescription(this.shortVideoDescription)
201 this.completeDescriptionShown = false
204 loadCompleteDescription () {
205 this.descriptionLoading = true
207 this.videoService.loadCompleteDescription(this.video.descriptionPath)
210 this.completeDescriptionShown = true
211 this.descriptionLoading = false
213 this.shortVideoDescription = this.video.description
214 this.completeVideoDescription = description
216 this.updateVideoDescription(this.completeVideoDescription)
220 this.descriptionLoading = false
221 this.notifier.error(error.message)
226 showSupportModal () {
229 this.videoSupportModal.show()
235 this.videoShareModal.show(this.currentTime)
239 return this.authService.isLoggedIn()
243 if (!this.video || Array.isArray(this.video.tags) === false) return []
245 return this.video.tags
248 onRecommendations (videos: Video[]) {
249 if (videos.length > 0) {
250 // The recommended videos's first element should be the next video
251 const video = videos[0]
252 this.nextVideoUuid = video.uuid
253 this.nextVideoTitle = video.name
262 this.redirectService.redirectToHomepage()
265 acceptedPrivacyConcern () {
266 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
267 this.hasAlreadyAcceptedPrivacyConcern = true
270 isVideoToTranscode () {
271 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
275 return this.video && this.video.state.id === VideoState.TO_IMPORT
278 hasVideoScheduledPublication () {
279 return this.video && this.video.scheduledUpdate !== undefined
282 isVideoBlur (video: Video) {
283 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
286 isAutoPlayEnabled () {
288 (this.user && this.user.autoPlayNextVideo) ||
289 peertubeSessionStorage.getItem(RecommendedVideosComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
293 handleTimestampClicked (timestamp: number) {
294 if (this.player) this.player.currentTime(timestamp)
298 isPlaylistAutoPlayEnabled () {
300 (this.user && this.user.autoPlayNextVideoPlaylist) ||
301 peertubeSessionStorage.getItem(VideoWatchPlaylistComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO_PLAYLIST) === 'true'
305 private loadVideo (videoId: string) {
306 // Video did not change
307 if (this.video && this.video.uuid === videoId) return
309 if (this.player) this.player.pause()
311 const videoObs = this.hooks.wrapObsFun(
312 this.videoService.getVideo.bind(this.videoService),
315 'filter:api.video-watch.video.get.params',
316 'filter:api.video-watch.video.get.result'
322 this.videoCaptionService.listCaptions(videoId)
325 // If 401, the video is private or blacklisted so redirect to 404
326 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
328 .subscribe(([ video, captionsResult ]) => {
329 const queryParams = this.route.snapshot.queryParams
332 startTime: queryParams.start,
333 stopTime: queryParams.stop,
335 muted: queryParams.muted,
336 loop: queryParams.loop,
337 subtitle: queryParams.subtitle,
339 playerMode: queryParams.mode,
343 this.onVideoFetched(video, captionsResult.data, urlOptions)
344 .catch(err => this.handleError(err))
348 private loadPlaylist (playlistId: string) {
349 // Playlist did not change
350 if (this.playlist && this.playlist.uuid === playlistId) return
352 this.playlistService.getVideoPlaylist(playlistId)
354 // If 401, the video is private or blacklisted so redirect to 404
355 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
357 .subscribe(playlist => {
358 this.playlist = playlist
360 const videoId = this.route.snapshot.queryParams['videoId']
361 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
365 private updateVideoDescription (description: string) {
366 this.video.description = description
367 this.setVideoDescriptionHTML()
368 .catch(err => console.error(err))
371 private async setVideoDescriptionHTML () {
372 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
373 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
376 private setVideoLikesBarTooltipText () {
377 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
378 likesNumber: this.video.likes,
379 dislikesNumber: this.video.dislikes
383 private handleError (err: any) {
384 const errorMessage: string = typeof err === 'string' ? err : err.message
385 if (!errorMessage) return
387 // Display a message in the video player instead of a notification
388 if (errorMessage.indexOf('from xs param') !== -1) {
390 this.remoteServerDown = true
391 this.changeDetector.detectChanges()
396 this.notifier.error(errorMessage)
399 private checkUserRating () {
400 // Unlogged users do not have ratings
401 if (this.isUserLoggedIn() === false) return
403 this.videoService.getUserVideoRating(this.video.id)
407 this.userRating = ratingObject.rating
411 err => this.notifier.error(err.message)
415 private async onVideoFetched (
417 videoCaptions: VideoCaption[],
418 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
421 this.videoCaptions = videoCaptions
423 // Re init attributes
424 this.descriptionLoading = false
425 this.completeDescriptionShown = false
426 this.remoteServerDown = false
427 this.currentTime = undefined
429 this.videoWatchPlaylist.updatePlaylistIndex(video)
431 if (this.isVideoBlur(this.video)) {
432 const res = await this.confirmService.confirm(
433 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
434 this.i18n('Mature or explicit content')
436 if (res === false) return this.location.back()
439 // Flush old player if needed
442 // Build video element, because videojs removes it on dispose
443 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
444 this.playerElement = document.createElement('video')
445 this.playerElement.className = 'video-js vjs-peertube-skin'
446 this.playerElement.setAttribute('playsinline', 'true')
447 playerElementWrapper.appendChild(this.playerElement)
455 const { playerMode, playerOptions } = await this.hooks.wrapFun(
456 this.buildPlayerManagerOptions.bind(this),
459 'filter:internal.video-watch.player.build-options.params',
460 'filter:internal.video-watch.player.build-options.result'
463 this.zone.runOutsideAngular(async () => {
464 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
467 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
469 this.player.on('timeupdate', () => {
470 this.currentTime = Math.floor(this.player.currentTime())
474 * replaces this.player.one('ended')
475 * define 'condition(next)' to return true to wait, false to stop
478 timeout: 10000, // 10s
479 headText: this.i18n('Up Next'),
480 cancelText: this.i18n('Cancel'),
481 getTitle: () => this.nextVideoTitle,
482 next: () => this.zone.run(() => this.autoplayNext()),
485 if (this.isPlaylistAutoPlayEnabled()) {
486 // upnext will not trigger, and instead the next video will play immediately
487 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
489 } else if (this.isAutoPlayEnabled()) {
490 return true // upnext will trigger
492 return false // upnext will not trigger, and instead leave the video stopping
496 this.player.one('stopped', () => {
498 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
502 this.player.on('theaterChange', (_: any, enabled: boolean) => {
503 this.zone.run(() => this.theaterEnabled = enabled)
506 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
509 this.setVideoDescriptionHTML()
510 this.setVideoLikesBarTooltipText()
512 this.setOpenGraphTags()
513 this.checkUserRating()
515 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
518 private autoplayNext () {
519 if (this.nextVideoUuid) {
520 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
524 private setRating (nextRating: UserVideoRateType) {
525 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
526 like: this.videoService.setVideoLike,
527 dislike: this.videoService.setVideoDislike,
528 none: this.videoService.unsetVideoLike
531 ratingMethods[nextRating].call(this.videoService, this.video.id)
534 // Update the video like attribute
535 this.updateVideoRating(this.userRating, nextRating)
536 this.userRating = nextRating
539 (err: { message: string }) => this.notifier.error(err.message)
543 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
544 let likesToIncrement = 0
545 let dislikesToIncrement = 0
548 if (oldRating === 'like') likesToIncrement--
549 if (oldRating === 'dislike') dislikesToIncrement--
552 if (newRating === 'like') likesToIncrement++
553 if (newRating === 'dislike') dislikesToIncrement++
555 this.video.likes += likesToIncrement
556 this.video.dislikes += dislikesToIncrement
558 this.video.buildLikeAndDislikePercents()
559 this.setVideoLikesBarTooltipText()
562 private setOpenGraphTags () {
563 this.metaService.setTitle(this.video.name)
565 this.metaService.setTag('og:type', 'video')
567 this.metaService.setTag('og:title', this.video.name)
568 this.metaService.setTag('name', this.video.name)
570 this.metaService.setTag('og:description', this.video.description)
571 this.metaService.setTag('description', this.video.description)
573 this.metaService.setTag('og:image', this.video.previewPath)
575 this.metaService.setTag('og:duration', this.video.duration.toString())
577 this.metaService.setTag('og:site_name', 'PeerTube')
579 this.metaService.setTag('og:url', window.location.href)
580 this.metaService.setTag('url', window.location.href)
583 private isAutoplay () {
584 // We'll jump to the thread id, so do not play the video
585 if (this.route.snapshot.params['threadId']) return false
587 // Otherwise true by default
588 if (!this.user) return true
590 // Be sure the autoPlay is set to false
591 return this.user.autoPlayVideo !== false
594 private flushPlayer () {
595 // Remove player if it exists
598 this.player.dispose()
599 this.player = undefined
601 console.error('Cannot dispose player.', err)
606 private buildPlayerManagerOptions (params: {
608 videoCaptions: VideoCaption[],
609 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
612 const { video, videoCaptions, urlOptions, user } = params
613 const getStartTime = () => {
614 const byUrl = urlOptions.startTime !== undefined
615 const byHistory = video.userHistory && !this.playlist
618 return timeToInt(urlOptions.startTime)
619 } else if (byHistory) {
620 return video.userHistory.currentTime
626 let startTime = getStartTime()
627 // If we are at the end of the video, reset the timer
628 if (video.duration - startTime <= 1) startTime = 0
630 const playerCaptions = videoCaptions.map(c => ({
631 label: c.language.label,
632 language: c.language.id,
633 src: environment.apiUrl + c.captionPath
636 const options: PeertubePlayerManagerOptions = {
638 autoplay: this.isAutoplay(),
640 playerElement: this.playerElement,
641 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
643 videoDuration: video.duration,
645 inactivityTimeout: 2500,
646 poster: video.previewUrl,
649 stopTime: urlOptions.stopTime,
650 controls: urlOptions.controls,
651 muted: urlOptions.muted,
652 loop: urlOptions.loop,
653 subtitle: urlOptions.subtitle,
655 peertubeLink: urlOptions.peertubeLink,
658 captions: videoCaptions.length !== 0,
660 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
661 ? this.videoService.getVideoViewUrl(video.uuid)
663 embedUrl: video.embedUrl,
665 language: this.localeId,
667 userWatching: user && user.videosHistoryEnabled === true ? {
668 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
669 authorizationHeader: this.authService.getRequestHeaderValue()
672 serverUrl: environment.apiUrl,
674 videoCaptions: playerCaptions
678 videoFiles: video.files
684 if (urlOptions.playerMode) {
685 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
686 else mode = 'webtorrent'
688 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
689 else mode = 'webtorrent'
692 if (mode === 'p2p-media-loader') {
693 const hlsPlaylist = video.getHlsPlaylist()
695 const p2pMediaLoader = {
696 playlistUrl: hlsPlaylist.playlistUrl,
697 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
698 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
699 trackerAnnounce: video.trackerUrls,
700 videoFiles: hlsPlaylist.files
701 } as P2PMediaLoaderOptions
703 Object.assign(options, { p2pMediaLoader })
706 return { playerMode: mode, playerOptions: options }
709 private pausePlayer () {
710 if (!this.player) return
715 private initHotkeys () {
717 // These hotkeys are managed by the player
718 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
719 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
720 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
722 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)')),
724 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
725 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
727 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
728 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
730 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
731 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
733 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
736 if (this.isUserLoggedIn()) {
737 this.hotkeys = this.hotkeys.concat([
738 new Hotkey('shift+l', () => {
741 }, undefined, this.i18n('Like the video')),
743 new Hotkey('shift+d', () => {
746 }, undefined, this.i18n('Dislike the video')),
748 new Hotkey('shift+s', () => {
749 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
751 }, undefined, this.i18n('Subscribe to the account'))
755 this.hotkeysService.add(this.hotkeys)