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 { randomInt } from '@shared/core-utils/miscs/miscs'
40 import { RecommendedVideosComponent } from '../recommendations/recommended-videos.component'
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 currentTime: number
82 private paramsSub: Subscription
83 private queryParamsSub: Subscription
84 private configSub: Subscription
87 private elementRef: ElementRef,
88 private changeDetector: ChangeDetectorRef,
89 private route: ActivatedRoute,
90 private router: Router,
91 private videoService: VideoService,
92 private playlistService: VideoPlaylistService,
93 private videoBlacklistService: VideoBlacklistService,
94 private confirmService: ConfirmService,
95 private metaService: MetaService,
96 private authService: AuthService,
97 private serverService: ServerService,
98 private restExtractor: RestExtractor,
99 private notifier: Notifier,
100 private pluginService: PluginService,
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()
122 this.configSub = this.serverService.configLoaded
125 isWebRTCDisabled() ||
126 this.serverService.getConfig().tracker.enabled === false ||
127 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
129 this.hasAlreadyAcceptedPrivacyConcern = true
133 this.paramsSub = this.route.params.subscribe(routeParams => {
134 const videoId = routeParams[ 'videoId' ]
135 if (videoId) this.loadVideo(videoId)
137 const playlistId = routeParams[ 'playlistId' ]
138 if (playlistId) this.loadPlaylist(playlistId)
141 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
142 const videoId = queryParams[ 'videoId' ]
143 if (videoId) this.loadVideo(videoId)
148 this.theaterEnabled = getStoredTheater()
150 this.hooks.runAction('action:video-watch.init', 'video-watch')
156 // Unsubscribe subscriptions
157 if (this.paramsSub) this.paramsSub.unsubscribe()
158 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
161 this.hotkeysService.remove(this.hotkeys)
165 if (this.isUserLoggedIn() === false) return
167 // Already liked this video
168 if (this.userRating === 'like') this.setRating('none')
169 else this.setRating('like')
173 if (this.isUserLoggedIn() === false) return
175 // Already disliked this video
176 if (this.userRating === 'dislike') this.setRating('none')
177 else this.setRating('dislike')
180 getRatePopoverText () {
181 if (this.isUserLoggedIn()) return undefined
183 return this.i18n('You need to be connected to rate this content.')
186 showMoreDescription () {
187 if (this.completeVideoDescription === undefined) {
188 return this.loadCompleteDescription()
191 this.updateVideoDescription(this.completeVideoDescription)
192 this.completeDescriptionShown = true
195 showLessDescription () {
196 this.updateVideoDescription(this.shortVideoDescription)
197 this.completeDescriptionShown = false
200 loadCompleteDescription () {
201 this.descriptionLoading = true
203 this.videoService.loadCompleteDescription(this.video.descriptionPath)
206 this.completeDescriptionShown = true
207 this.descriptionLoading = false
209 this.shortVideoDescription = this.video.description
210 this.completeVideoDescription = description
212 this.updateVideoDescription(this.completeVideoDescription)
216 this.descriptionLoading = false
217 this.notifier.error(error.message)
222 showSupportModal () {
225 this.videoSupportModal.show()
231 this.videoShareModal.show(this.currentTime)
235 return this.authService.isLoggedIn()
239 if (!this.video || Array.isArray(this.video.tags) === false) return []
241 return this.video.tags
244 onRecommendations (videos: Video[]) {
245 if (videos.length > 0) {
246 // Pick a random video until the recommendations are improved
247 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
256 this.redirectService.redirectToHomepage()
259 acceptedPrivacyConcern () {
260 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
261 this.hasAlreadyAcceptedPrivacyConcern = true
264 isVideoToTranscode () {
265 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
269 return this.video && this.video.state.id === VideoState.TO_IMPORT
272 hasVideoScheduledPublication () {
273 return this.video && this.video.scheduledUpdate !== undefined
276 isVideoBlur (video: Video) {
277 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
280 isAutoPlayEnabled () {
282 (this.user && this.user.autoPlayNextVideo) ||
283 peertubeSessionStorage.getItem(RecommendedVideosComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
287 isPlaylistAutoPlayEnabled () {
289 (this.user && this.user.autoPlayNextVideoPlaylist) ||
290 peertubeSessionStorage.getItem(VideoWatchPlaylistComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO_PLAYLIST) === 'true'
294 private loadVideo (videoId: string) {
295 // Video did not change
296 if (this.video && this.video.uuid === videoId) return
298 if (this.player) this.player.pause()
300 const videoObs = this.hooks.wrapObsFun(
301 this.videoService.getVideo.bind(this.videoService),
304 'filter:api.video-watch.video.get.params',
305 'filter:api.video-watch.video.get.result'
311 this.videoCaptionService.listCaptions(videoId)
314 // If 401, the video is private or blacklisted so redirect to 404
315 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
317 .subscribe(([ video, captionsResult ]) => {
318 const queryParams = this.route.snapshot.queryParams
321 startTime: queryParams.start,
322 stopTime: queryParams.stop,
324 muted: queryParams.muted,
325 loop: queryParams.loop,
326 subtitle: queryParams.subtitle,
328 playerMode: queryParams.mode,
332 this.onVideoFetched(video, captionsResult.data, urlOptions)
333 .catch(err => this.handleError(err))
337 private loadPlaylist (playlistId: string) {
338 // Playlist did not change
339 if (this.playlist && this.playlist.uuid === playlistId) return
341 this.playlistService.getVideoPlaylist(playlistId)
343 // If 401, the video is private or blacklisted so redirect to 404
344 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
346 .subscribe(playlist => {
347 this.playlist = playlist
349 const videoId = this.route.snapshot.queryParams['videoId']
350 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
354 private updateVideoDescription (description: string) {
355 this.video.description = description
356 this.setVideoDescriptionHTML()
357 .catch(err => console.error(err))
360 private async setVideoDescriptionHTML () {
361 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
362 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
365 private setVideoLikesBarTooltipText () {
366 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
367 likesNumber: this.video.likes,
368 dislikesNumber: this.video.dislikes
372 private handleError (err: any) {
373 const errorMessage: string = typeof err === 'string' ? err : err.message
374 if (!errorMessage) return
376 // Display a message in the video player instead of a notification
377 if (errorMessage.indexOf('from xs param') !== -1) {
379 this.remoteServerDown = true
380 this.changeDetector.detectChanges()
385 this.notifier.error(errorMessage)
388 private checkUserRating () {
389 // Unlogged users do not have ratings
390 if (this.isUserLoggedIn() === false) return
392 this.videoService.getUserVideoRating(this.video.id)
396 this.userRating = ratingObject.rating
400 err => this.notifier.error(err.message)
404 private async onVideoFetched (
406 videoCaptions: VideoCaption[],
407 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
410 this.videoCaptions = videoCaptions
412 // Re init attributes
413 this.descriptionLoading = false
414 this.completeDescriptionShown = false
415 this.remoteServerDown = false
416 this.currentTime = undefined
418 this.videoWatchPlaylist.updatePlaylistIndex(video)
420 if (this.isVideoBlur(this.video)) {
421 const res = await this.confirmService.confirm(
422 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
423 this.i18n('Mature or explicit content')
425 if (res === false) return this.location.back()
428 // Flush old player if needed
431 // Build video element, because videojs removes it on dispose
432 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
433 this.playerElement = document.createElement('video')
434 this.playerElement.className = 'video-js vjs-peertube-skin'
435 this.playerElement.setAttribute('playsinline', 'true')
436 playerElementWrapper.appendChild(this.playerElement)
444 const { playerMode, playerOptions } = await this.hooks.wrapFun(
445 this.buildPlayerManagerOptions.bind(this),
448 'filter:internal.video-watch.player.build-options.params',
449 'filter:internal.video-watch.player.build-options.result'
452 this.zone.runOutsideAngular(async () => {
453 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
456 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
458 this.player.on('timeupdate', () => {
459 this.currentTime = Math.floor(this.player.currentTime())
462 this.player.one('ended', () => {
464 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
465 } else if (this.isAutoPlayEnabled()) {
466 this.zone.run(() => this.autoplayNext())
470 this.player.one('stopped', () => {
472 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
476 this.player.on('theaterChange', (_: any, enabled: boolean) => {
477 this.zone.run(() => this.theaterEnabled = enabled)
480 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
483 this.setVideoDescriptionHTML()
484 this.setVideoLikesBarTooltipText()
486 this.setOpenGraphTags()
487 this.checkUserRating()
489 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
492 private autoplayNext () {
493 if (this.nextVideoUuid) {
494 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
498 private setRating (nextRating: UserVideoRateType) {
499 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
500 like: this.videoService.setVideoLike,
501 dislike: this.videoService.setVideoDislike,
502 none: this.videoService.unsetVideoLike
505 ratingMethods[nextRating].call(this.videoService, this.video.id)
508 // Update the video like attribute
509 this.updateVideoRating(this.userRating, nextRating)
510 this.userRating = nextRating
513 (err: { message: string }) => this.notifier.error(err.message)
517 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
518 let likesToIncrement = 0
519 let dislikesToIncrement = 0
522 if (oldRating === 'like') likesToIncrement--
523 if (oldRating === 'dislike') dislikesToIncrement--
526 if (newRating === 'like') likesToIncrement++
527 if (newRating === 'dislike') dislikesToIncrement++
529 this.video.likes += likesToIncrement
530 this.video.dislikes += dislikesToIncrement
532 this.video.buildLikeAndDislikePercents()
533 this.setVideoLikesBarTooltipText()
536 private setOpenGraphTags () {
537 this.metaService.setTitle(this.video.name)
539 this.metaService.setTag('og:type', 'video')
541 this.metaService.setTag('og:title', this.video.name)
542 this.metaService.setTag('name', this.video.name)
544 this.metaService.setTag('og:description', this.video.description)
545 this.metaService.setTag('description', this.video.description)
547 this.metaService.setTag('og:image', this.video.previewPath)
549 this.metaService.setTag('og:duration', this.video.duration.toString())
551 this.metaService.setTag('og:site_name', 'PeerTube')
553 this.metaService.setTag('og:url', window.location.href)
554 this.metaService.setTag('url', window.location.href)
557 private isAutoplay () {
558 // We'll jump to the thread id, so do not play the video
559 if (this.route.snapshot.params['threadId']) return false
561 // Otherwise true by default
562 if (!this.user) return true
564 // Be sure the autoPlay is set to false
565 return this.user.autoPlayVideo !== false
568 private flushPlayer () {
569 // Remove player if it exists
572 this.player.dispose()
573 this.player = undefined
575 console.error('Cannot dispose player.', err)
580 private buildPlayerManagerOptions (params: {
582 videoCaptions: VideoCaption[],
583 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
586 const { video, videoCaptions, urlOptions, user } = params
587 const getStartTime = () => {
588 const byUrl = urlOptions.startTime !== undefined
589 const byHistory = video.userHistory && !this.playlist
592 return timeToInt(urlOptions.startTime)
593 } else if (byHistory) {
594 return video.userHistory.currentTime
600 let startTime = getStartTime()
601 // If we are at the end of the video, reset the timer
602 if (video.duration - startTime <= 1) startTime = 0
604 const playerCaptions = videoCaptions.map(c => ({
605 label: c.language.label,
606 language: c.language.id,
607 src: environment.apiUrl + c.captionPath
610 const options: PeertubePlayerManagerOptions = {
612 autoplay: this.isAutoplay(),
614 playerElement: this.playerElement,
615 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
617 videoDuration: video.duration,
619 inactivityTimeout: 2500,
620 poster: video.previewUrl,
623 stopTime: urlOptions.stopTime,
624 controls: urlOptions.controls,
625 muted: urlOptions.muted,
626 loop: urlOptions.loop,
627 subtitle: urlOptions.subtitle,
629 peertubeLink: urlOptions.peertubeLink,
632 captions: videoCaptions.length !== 0,
634 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
635 ? this.videoService.getVideoViewUrl(video.uuid)
637 embedUrl: video.embedUrl,
639 language: this.localeId,
641 userWatching: user && user.videosHistoryEnabled === true ? {
642 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
643 authorizationHeader: this.authService.getRequestHeaderValue()
646 serverUrl: environment.apiUrl,
648 videoCaptions: playerCaptions
652 videoFiles: video.files
658 if (urlOptions.playerMode) {
659 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
660 else mode = 'webtorrent'
662 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
663 else mode = 'webtorrent'
666 if (mode === 'p2p-media-loader') {
667 const hlsPlaylist = video.getHlsPlaylist()
669 const p2pMediaLoader = {
670 playlistUrl: hlsPlaylist.playlistUrl,
671 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
672 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
673 trackerAnnounce: video.trackerUrls,
674 videoFiles: hlsPlaylist.files
675 } as P2PMediaLoaderOptions
677 Object.assign(options, { p2pMediaLoader })
680 return { playerMode: mode, playerOptions: options }
683 private pausePlayer () {
684 if (!this.player) return
689 private initHotkeys () {
691 // These hotkeys are managed by the player
692 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
693 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
694 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
696 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)')),
698 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
699 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
701 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
702 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
704 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
705 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
707 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
710 if (this.isUserLoggedIn()) {
711 this.hotkeys = this.hotkeys.concat([
712 new Hotkey('shift+l', () => {
715 }, undefined, this.i18n('Like the video')),
717 new Hotkey('shift+d', () => {
720 }, undefined, this.i18n('Dislike the video')),
722 new Hotkey('shift+s', () => {
723 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
725 }, undefined, this.i18n('Subscribe to the account'))
729 this.hotkeysService.add(this.hotkeys)