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 { I18n } from '@ngx-translate/i18n-polyfill'
18 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
19 import { ServerConfig, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
20 import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
23 P2PMediaLoaderOptions,
24 PeertubePlayerManager,
25 PeertubePlayerManagerOptions,
28 } from '../../../assets/player/peertube-player-manager'
29 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
30 import { environment } from '../../../environments/environment'
31 import { VideoSupportComponent } from './modal/video-support.component'
32 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
35 selector: 'my-video-watch',
36 templateUrl: './video-watch.component.html',
37 styleUrls: [ './video-watch.component.scss' ]
39 export class VideoWatchComponent implements OnInit, OnDestroy {
40 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
42 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
43 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
44 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
45 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
46 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
49 playerElement: HTMLVideoElement
50 theaterEnabled = false
51 userRating: UserVideoRateType = null
52 descriptionLoading = false
54 video: VideoDetails = null
55 videoCaptions: VideoCaption[] = []
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,
101 private hotkeysService: HotkeysService,
102 private hooks: HooksService,
103 private location: PlatformLocation,
104 @Inject(LOCALE_ID) private localeId: string
106 this.tooltipLike = this.i18n('Like this video')
107 this.tooltipDislike = this.i18n('Dislike this video')
108 this.tooltipSupport = this.i18n('Support options for this video')
109 this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
113 return this.authService.getUser()
116 get anonymousUser () {
117 return this.userService.getAnonymousUser()
121 this.serverConfig = this.serverService.getTmpConfig()
123 this.configSub = this.serverService.getConfig()
124 .subscribe(config => {
125 this.serverConfig = config
128 isWebRTCDisabled() ||
129 this.serverConfig.tracker.enabled === false ||
130 getStoredP2PEnabled() === false ||
131 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
133 this.hasAlreadyAcceptedPrivacyConcern = true
137 this.paramsSub = this.route.params.subscribe(routeParams => {
138 const videoId = routeParams[ 'videoId' ]
139 if (videoId) this.loadVideo(videoId)
141 const playlistId = routeParams[ 'playlistId' ]
142 if (playlistId) this.loadPlaylist(playlistId)
145 this.queryParamsSub = this.route.queryParams.subscribe(async queryParams => {
146 const videoId = queryParams[ 'videoId' ]
147 if (videoId) this.loadVideo(videoId)
149 const start = queryParams[ 'start' ]
150 if (this.player && start) this.player.currentTime(parseInt(start, 10))
155 this.theaterEnabled = getStoredTheater()
157 this.hooks.runAction('action:video-watch.init', 'video-watch')
163 // Unsubscribe subscriptions
164 if (this.paramsSub) this.paramsSub.unsubscribe()
165 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
166 if (this.configSub) this.configSub.unsubscribe()
169 this.hotkeysService.remove(this.hotkeys)
173 if (this.isUserLoggedIn() === false) return
175 // Already liked this video
176 if (this.userRating === 'like') this.setRating('none')
177 else this.setRating('like')
181 if (this.isUserLoggedIn() === false) return
183 // Already disliked this video
184 if (this.userRating === 'dislike') this.setRating('none')
185 else this.setRating('dislike')
188 getRatePopoverText () {
189 if (this.isUserLoggedIn()) return undefined
191 return this.i18n('You need to be connected to rate this content.')
194 showMoreDescription () {
195 if (this.completeVideoDescription === undefined) {
196 return this.loadCompleteDescription()
199 this.updateVideoDescription(this.completeVideoDescription)
200 this.completeDescriptionShown = true
203 showLessDescription () {
204 this.updateVideoDescription(this.shortVideoDescription)
205 this.completeDescriptionShown = false
208 showDownloadModal () {
209 this.videoDownloadModal.show(this.video, this.videoCaptions)
212 isVideoDownloadable () {
213 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled
216 loadCompleteDescription () {
217 this.descriptionLoading = true
219 this.videoService.loadCompleteDescription(this.video.descriptionPath)
222 this.completeDescriptionShown = true
223 this.descriptionLoading = false
225 this.shortVideoDescription = this.video.description
226 this.completeVideoDescription = description
228 this.updateVideoDescription(this.completeVideoDescription)
232 this.descriptionLoading = false
233 this.notifier.error(error.message)
238 showSupportModal () {
239 // Check video was playing before opening support modal
240 const isVideoPlaying = this.isPlaying()
244 const modalRef = this.videoSupportModal.show()
246 modalRef.result.then(() => {
247 if (isVideoPlaying) {
256 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
260 return this.authService.isLoggedIn()
264 if (!this.video || Array.isArray(this.video.tags) === false) return []
266 return this.video.tags
269 onRecommendations (videos: Video[]) {
270 if (videos.length > 0) {
271 // The recommended videos's first element should be the next video
272 const video = videos[0]
273 this.nextVideoUuid = video.uuid
274 this.nextVideoTitle = video.name
283 this.redirectService.redirectToHomepage()
286 declinedPrivacyConcern () {
287 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
288 this.hasAlreadyAcceptedPrivacyConcern = false
291 acceptedPrivacyConcern () {
292 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
293 this.hasAlreadyAcceptedPrivacyConcern = true
296 isVideoToTranscode () {
297 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
301 return this.video && this.video.state.id === VideoState.TO_IMPORT
304 hasVideoScheduledPublication () {
305 return this.video && this.video.scheduledUpdate !== undefined
308 isVideoBlur (video: Video) {
309 return video.isVideoNSFWForUser(this.user, this.serverConfig)
312 isAutoPlayEnabled () {
314 (this.user && this.user.autoPlayNextVideo) ||
315 this.anonymousUser.autoPlayNextVideo
319 handleTimestampClicked (timestamp: number) {
320 if (this.player) this.player.currentTime(timestamp)
324 isPlaylistAutoPlayEnabled () {
326 (this.user && this.user.autoPlayNextVideoPlaylist) ||
327 this.anonymousUser.autoPlayNextVideoPlaylist
331 isChannelDisplayNameGeneric () {
332 const genericChannelDisplayName = [
333 `Main ${this.video.channel.ownerAccount.name} channel`,
334 `Default ${this.video.channel.ownerAccount.name} channel`
337 return genericChannelDisplayName.includes(this.video.channel.displayName)
340 private loadVideo (videoId: string) {
341 // Video did not change
342 if (this.video && this.video.uuid === videoId) return
344 if (this.player) this.player.pause()
346 const videoObs = this.hooks.wrapObsFun(
347 this.videoService.getVideo.bind(this.videoService),
350 'filter:api.video-watch.video.get.params',
351 'filter:api.video-watch.video.get.result'
357 this.videoCaptionService.listCaptions(videoId)
360 // If 401, the video is private or blocked so redirect to 404
361 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
363 .subscribe(([ video, captionsResult ]) => {
364 const queryParams = this.route.snapshot.queryParams
367 startTime: queryParams.start,
368 stopTime: queryParams.stop,
370 muted: queryParams.muted,
371 loop: queryParams.loop,
372 subtitle: queryParams.subtitle,
374 playerMode: queryParams.mode,
378 this.onVideoFetched(video, captionsResult.data, urlOptions)
379 .catch(err => this.handleError(err))
383 private loadPlaylist (playlistId: string) {
384 // Playlist did not change
385 if (this.playlist && this.playlist.uuid === playlistId) return
387 this.playlistService.getVideoPlaylist(playlistId)
389 // If 401, the video is private or blocked so redirect to 404
390 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
392 .subscribe(playlist => {
393 this.playlist = playlist
395 const videoId = this.route.snapshot.queryParams['videoId']
396 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
400 private updateVideoDescription (description: string) {
401 this.video.description = description
402 this.setVideoDescriptionHTML()
403 .catch(err => console.error(err))
406 private async setVideoDescriptionHTML () {
407 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
408 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
411 private setVideoLikesBarTooltipText () {
412 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
413 likesNumber: this.video.likes,
414 dislikesNumber: this.video.dislikes
418 private handleError (err: any) {
419 const errorMessage: string = typeof err === 'string' ? err : err.message
420 if (!errorMessage) return
422 // Display a message in the video player instead of a notification
423 if (errorMessage.indexOf('from xs param') !== -1) {
425 this.remoteServerDown = true
426 this.changeDetector.detectChanges()
431 this.notifier.error(errorMessage)
434 private checkUserRating () {
435 // Unlogged users do not have ratings
436 if (this.isUserLoggedIn() === false) return
438 this.videoService.getUserVideoRating(this.video.id)
442 this.userRating = ratingObject.rating
446 err => this.notifier.error(err.message)
450 private async onVideoFetched (
452 videoCaptions: VideoCaption[],
453 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
456 this.videoCaptions = videoCaptions
458 // Re init attributes
459 this.descriptionLoading = false
460 this.completeDescriptionShown = false
461 this.remoteServerDown = false
462 this.currentTime = undefined
464 this.videoWatchPlaylist.updatePlaylistIndex(video)
466 if (this.isVideoBlur(this.video)) {
467 const res = await this.confirmService.confirm(
468 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
469 this.i18n('Mature or explicit content')
471 if (res === false) return this.location.back()
474 // Flush old player if needed
477 // Build video element, because videojs removes it on dispose
478 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
479 this.playerElement = document.createElement('video')
480 this.playerElement.className = 'video-js vjs-peertube-skin'
481 this.playerElement.setAttribute('playsinline', 'true')
482 playerElementWrapper.appendChild(this.playerElement)
490 const { playerMode, playerOptions } = await this.hooks.wrapFun(
491 this.buildPlayerManagerOptions.bind(this),
494 'filter:internal.video-watch.player.build-options.params',
495 'filter:internal.video-watch.player.build-options.result'
498 this.zone.runOutsideAngular(async () => {
499 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
501 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
503 this.player.on('timeupdate', () => {
504 this.currentTime = Math.floor(this.player.currentTime())
508 * replaces this.player.one('ended')
509 * 'condition()': true to make the upnext functionality trigger,
510 * false to disable the upnext functionality
511 * go to the next video in 'condition()' if you don't want of the timer.
512 * 'next': function triggered at the end of the timer.
513 * 'suspended': function used at each clic of the timer checking if we need
514 * to reset progress and wait until 'suspended' becomes truthy again.
517 timeout: 10000, // 10s
518 headText: this.i18n('Up Next'),
519 cancelText: this.i18n('Cancel'),
520 suspendedText: this.i18n('Autoplay is suspended'),
521 getTitle: () => this.nextVideoTitle,
522 next: () => this.zone.run(() => this.autoplayNext()),
525 if (this.isPlaylistAutoPlayEnabled()) {
526 // upnext will not trigger, and instead the next video will play immediately
527 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
529 } else if (this.isAutoPlayEnabled()) {
530 return true // upnext will trigger
532 return false // upnext will not trigger, and instead leave the video stopping
536 !isXPercentInViewport(this.player.el(), 80) ||
537 !document.getElementById('content').contains(document.activeElement)
542 this.player.one('stopped', () => {
544 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
548 this.player.on('theaterChange', (_: any, enabled: boolean) => {
549 this.zone.run(() => this.theaterEnabled = enabled)
552 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
555 this.setVideoDescriptionHTML()
556 this.setVideoLikesBarTooltipText()
558 this.setOpenGraphTags()
559 this.checkUserRating()
561 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
564 private autoplayNext () {
566 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
567 } else if (this.nextVideoUuid) {
568 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
572 private setRating (nextRating: UserVideoRateType) {
573 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
574 like: this.videoService.setVideoLike,
575 dislike: this.videoService.setVideoDislike,
576 none: this.videoService.unsetVideoLike
579 ratingMethods[nextRating].call(this.videoService, this.video.id)
582 // Update the video like attribute
583 this.updateVideoRating(this.userRating, nextRating)
584 this.userRating = nextRating
587 (err: { message: string }) => this.notifier.error(err.message)
591 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
592 let likesToIncrement = 0
593 let dislikesToIncrement = 0
596 if (oldRating === 'like') likesToIncrement--
597 if (oldRating === 'dislike') dislikesToIncrement--
600 if (newRating === 'like') likesToIncrement++
601 if (newRating === 'dislike') dislikesToIncrement++
603 this.video.likes += likesToIncrement
604 this.video.dislikes += dislikesToIncrement
606 this.video.buildLikeAndDislikePercents()
607 this.setVideoLikesBarTooltipText()
610 private setOpenGraphTags () {
611 this.metaService.setTitle(this.video.name)
613 this.metaService.setTag('og:type', 'video')
615 this.metaService.setTag('og:title', this.video.name)
616 this.metaService.setTag('name', this.video.name)
618 this.metaService.setTag('og:description', this.video.description)
619 this.metaService.setTag('description', this.video.description)
621 this.metaService.setTag('og:image', this.video.previewPath)
623 this.metaService.setTag('og:duration', this.video.duration.toString())
625 this.metaService.setTag('og:site_name', 'PeerTube')
627 this.metaService.setTag('og:url', window.location.href)
628 this.metaService.setTag('url', window.location.href)
631 private isAutoplay () {
632 // We'll jump to the thread id, so do not play the video
633 if (this.route.snapshot.params['threadId']) return false
635 // Otherwise true by default
636 if (!this.user) return true
638 // Be sure the autoPlay is set to false
639 return this.user.autoPlayVideo !== false
642 private flushPlayer () {
643 // Remove player if it exists
646 this.player.dispose()
647 this.player = undefined
649 console.error('Cannot dispose player.', err)
654 private buildPlayerManagerOptions (params: {
656 videoCaptions: VideoCaption[],
657 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
660 const { video, videoCaptions, urlOptions, user } = params
661 const getStartTime = () => {
662 const byUrl = urlOptions.startTime !== undefined
663 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
666 return timeToInt(urlOptions.startTime)
667 } else if (byHistory) {
668 return video.userHistory.currentTime
674 let startTime = getStartTime()
675 // If we are at the end of the video, reset the timer
676 if (video.duration - startTime <= 1) startTime = 0
678 const playerCaptions = videoCaptions.map(c => ({
679 label: c.language.label,
680 language: c.language.id,
681 src: environment.apiUrl + c.captionPath
684 const options: PeertubePlayerManagerOptions = {
686 autoplay: this.isAutoplay(),
687 nextVideo: () => this.zone.run(() => this.autoplayNext()),
689 playerElement: this.playerElement,
690 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
692 videoDuration: video.duration,
694 inactivityTimeout: 2500,
695 poster: video.previewUrl,
698 stopTime: urlOptions.stopTime,
699 controls: urlOptions.controls,
700 muted: urlOptions.muted,
701 loop: urlOptions.loop,
702 subtitle: urlOptions.subtitle,
704 peertubeLink: urlOptions.peertubeLink,
707 captions: videoCaptions.length !== 0,
709 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
710 ? this.videoService.getVideoViewUrl(video.uuid)
712 embedUrl: video.embedUrl,
714 language: this.localeId,
716 userWatching: user && user.videosHistoryEnabled === true ? {
717 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
718 authorizationHeader: this.authService.getRequestHeaderValue()
721 serverUrl: environment.apiUrl,
723 videoCaptions: playerCaptions
727 videoFiles: video.files
733 if (urlOptions.playerMode) {
734 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
735 else mode = 'webtorrent'
737 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
738 else mode = 'webtorrent'
741 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
742 if (typeof TextEncoder === 'undefined') {
746 if (mode === 'p2p-media-loader') {
747 const hlsPlaylist = video.getHlsPlaylist()
749 const p2pMediaLoader = {
750 playlistUrl: hlsPlaylist.playlistUrl,
751 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
752 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
753 trackerAnnounce: video.trackerUrls,
754 videoFiles: hlsPlaylist.files
755 } as P2PMediaLoaderOptions
757 Object.assign(options, { p2pMediaLoader })
760 return { playerMode: mode, playerOptions: options }
763 private pausePlayer () {
764 if (!this.player) return
769 private resumePlayer () {
770 if (!this.player) return
775 private isPlaying () {
776 if (!this.player) return
778 return !this.player.paused()
781 private initHotkeys () {
783 // These hotkeys are managed by the player
784 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
785 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
786 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
788 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)')),
790 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
791 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
793 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
794 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
796 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
797 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
799 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
802 if (this.isUserLoggedIn()) {
803 this.hotkeys = this.hotkeys.concat([
804 new Hotkey('shift+l', () => {
807 }, undefined, this.i18n('Like the video')),
809 new Hotkey('shift+d', () => {
812 }, undefined, this.i18n('Dislike the video')),
814 new Hotkey('shift+s', () => {
815 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
817 }, undefined, this.i18n('Subscribe to the account'))
821 this.hotkeysService.add(this.hotkeys)