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[] = []
75 private nextVideoUuid = ''
76 private currentTime: number
77 private paramsSub: Subscription
78 private queryParamsSub: Subscription
79 private configSub: Subscription
82 private elementRef: ElementRef,
83 private changeDetector: ChangeDetectorRef,
84 private route: ActivatedRoute,
85 private router: Router,
86 private videoService: VideoService,
87 private playlistService: VideoPlaylistService,
88 private videoBlacklistService: VideoBlacklistService,
89 private confirmService: ConfirmService,
90 private metaService: MetaService,
91 private authService: AuthService,
92 private serverService: ServerService,
93 private restExtractor: RestExtractor,
94 private notifier: Notifier,
95 private pluginService: PluginService,
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
108 return this.authService.getUser()
112 this.configSub = this.serverService.configLoaded
115 isWebRTCDisabled() ||
116 this.serverService.getConfig().tracker.enabled === false ||
117 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
119 this.hasAlreadyAcceptedPrivacyConcern = true
123 this.paramsSub = this.route.params.subscribe(routeParams => {
124 const videoId = routeParams[ 'videoId' ]
125 if (videoId) this.loadVideo(videoId)
127 const playlistId = routeParams[ 'playlistId' ]
128 if (playlistId) this.loadPlaylist(playlistId)
131 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
132 const videoId = queryParams[ 'videoId' ]
133 if (videoId) this.loadVideo(videoId)
138 this.theaterEnabled = getStoredTheater()
140 this.hooks.runAction('action:video-watch.init', 'video-watch')
146 // Unsubscribe subscriptions
147 if (this.paramsSub) this.paramsSub.unsubscribe()
148 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
151 this.hotkeysService.remove(this.hotkeys)
155 if (this.isUserLoggedIn() === false) return
157 // Already liked this video
158 if (this.userRating === 'like') this.setRating('none')
159 else this.setRating('like')
163 if (this.isUserLoggedIn() === false) return
165 // Already disliked this video
166 if (this.userRating === 'dislike') this.setRating('none')
167 else this.setRating('dislike')
170 getRatePopoverText () {
171 if (this.isUserLoggedIn()) return undefined
173 return this.i18n('You need to be connected to rate this content.')
176 showMoreDescription () {
177 if (this.completeVideoDescription === undefined) {
178 return this.loadCompleteDescription()
181 this.updateVideoDescription(this.completeVideoDescription)
182 this.completeDescriptionShown = true
185 showLessDescription () {
186 this.updateVideoDescription(this.shortVideoDescription)
187 this.completeDescriptionShown = false
190 loadCompleteDescription () {
191 this.descriptionLoading = true
193 this.videoService.loadCompleteDescription(this.video.descriptionPath)
196 this.completeDescriptionShown = true
197 this.descriptionLoading = false
199 this.shortVideoDescription = this.video.description
200 this.completeVideoDescription = description
202 this.updateVideoDescription(this.completeVideoDescription)
206 this.descriptionLoading = false
207 this.notifier.error(error.message)
212 showSupportModal () {
215 this.videoSupportModal.show()
221 this.videoShareModal.show(this.currentTime)
225 return this.authService.isLoggedIn()
229 if (!this.video || Array.isArray(this.video.tags) === false) return []
231 return this.video.tags
234 onRecommendations (videos: Video[]) {
235 if (videos.length > 0) {
236 // Pick a random video until the recommendations are improved
237 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
246 this.redirectService.redirectToHomepage()
249 acceptedPrivacyConcern () {
250 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
251 this.hasAlreadyAcceptedPrivacyConcern = true
254 isVideoToTranscode () {
255 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
259 return this.video && this.video.state.id === VideoState.TO_IMPORT
262 hasVideoScheduledPublication () {
263 return this.video && this.video.scheduledUpdate !== undefined
266 isVideoBlur (video: Video) {
267 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
270 private loadVideo (videoId: string) {
271 // Video did not change
272 if (this.video && this.video.uuid === videoId) return
274 if (this.player) this.player.pause()
276 const videoObs = this.hooks.wrapObsFun(
277 this.videoService.getVideo.bind(this.videoService),
280 'filter:api.video-watch.video.get.params',
281 'filter:api.video-watch.video.get.result'
287 this.videoCaptionService.listCaptions(videoId)
290 // If 401, the video is private or blacklisted so redirect to 404
291 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
293 .subscribe(([ video, captionsResult ]) => {
294 const queryParams = this.route.snapshot.queryParams
297 startTime: queryParams.start,
298 stopTime: queryParams.stop,
300 muted: queryParams.muted,
301 loop: queryParams.loop,
302 subtitle: queryParams.subtitle,
304 playerMode: queryParams.mode,
308 this.onVideoFetched(video, captionsResult.data, urlOptions)
309 .catch(err => this.handleError(err))
313 private loadPlaylist (playlistId: string) {
314 // Playlist did not change
315 if (this.playlist && this.playlist.uuid === playlistId) return
317 this.playlistService.getVideoPlaylist(playlistId)
319 // If 401, the video is private or blacklisted so redirect to 404
320 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
322 .subscribe(playlist => {
323 this.playlist = playlist
325 const videoId = this.route.snapshot.queryParams['videoId']
326 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
330 private updateVideoDescription (description: string) {
331 this.video.description = description
332 this.setVideoDescriptionHTML()
333 .catch(err => console.error(err))
336 private async setVideoDescriptionHTML () {
337 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
340 private setVideoLikesBarTooltipText () {
341 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
342 likesNumber: this.video.likes,
343 dislikesNumber: this.video.dislikes
347 private handleError (err: any) {
348 const errorMessage: string = typeof err === 'string' ? err : err.message
349 if (!errorMessage) return
351 // Display a message in the video player instead of a notification
352 if (errorMessage.indexOf('from xs param') !== -1) {
354 this.remoteServerDown = true
355 this.changeDetector.detectChanges()
360 this.notifier.error(errorMessage)
363 private checkUserRating () {
364 // Unlogged users do not have ratings
365 if (this.isUserLoggedIn() === false) return
367 this.videoService.getUserVideoRating(this.video.id)
371 this.userRating = ratingObject.rating
375 err => this.notifier.error(err.message)
379 private async onVideoFetched (
381 videoCaptions: VideoCaption[],
382 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
385 this.videoCaptions = videoCaptions
387 // Re init attributes
388 this.descriptionLoading = false
389 this.completeDescriptionShown = false
390 this.remoteServerDown = false
391 this.currentTime = undefined
393 this.videoWatchPlaylist.updatePlaylistIndex(video)
395 if (this.isVideoBlur(this.video)) {
396 const res = await this.confirmService.confirm(
397 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
398 this.i18n('Mature or explicit content')
400 if (res === false) return this.location.back()
403 // Flush old player if needed
406 // Build video element, because videojs removes it on dispose
407 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
408 this.playerElement = document.createElement('video')
409 this.playerElement.className = 'video-js vjs-peertube-skin'
410 this.playerElement.setAttribute('playsinline', 'true')
411 playerElementWrapper.appendChild(this.playerElement)
419 const { playerMode, playerOptions } = await this.hooks.wrapFun(
420 this.buildPlayerManagerOptions.bind(this),
423 'filter:internal.video-watch.player.build-options.params',
424 'filter:internal.video-watch.player.build-options.result'
427 this.zone.runOutsideAngular(async () => {
428 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
431 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
433 this.player.on('timeupdate', () => {
434 this.currentTime = Math.floor(this.player.currentTime())
437 this.player.one('ended', () => {
440 this.user && this.user.autoPlayNextVideoPlaylist ||
441 peertubeSessionStorage.getItem(VideoWatchPlaylistComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO_PLAYLIST) === 'true'
442 ) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
444 this.user && this.user.autoPlayNextVideo ||
445 peertubeSessionStorage.getItem(RecommendedVideosComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
447 this.zone.run(() => this.autoplayNext())
451 this.player.one('stopped', () => {
454 this.user && this.user.autoPlayNextVideoPlaylist ||
455 peertubeSessionStorage.getItem(VideoWatchPlaylistComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO_PLAYLIST) === 'true'
456 ) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
460 this.player.on('theaterChange', (_: any, enabled: boolean) => {
461 this.zone.run(() => this.theaterEnabled = enabled)
464 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
467 this.setVideoDescriptionHTML()
468 this.setVideoLikesBarTooltipText()
470 this.setOpenGraphTags()
471 this.checkUserRating()
473 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
476 private autoplayNext () {
477 if (this.nextVideoUuid) {
478 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
482 private setRating (nextRating: UserVideoRateType) {
483 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
484 like: this.videoService.setVideoLike,
485 dislike: this.videoService.setVideoDislike,
486 none: this.videoService.unsetVideoLike
489 ratingMethods[nextRating].call(this.videoService, this.video.id)
492 // Update the video like attribute
493 this.updateVideoRating(this.userRating, nextRating)
494 this.userRating = nextRating
497 (err: { message: string }) => this.notifier.error(err.message)
501 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
502 let likesToIncrement = 0
503 let dislikesToIncrement = 0
506 if (oldRating === 'like') likesToIncrement--
507 if (oldRating === 'dislike') dislikesToIncrement--
510 if (newRating === 'like') likesToIncrement++
511 if (newRating === 'dislike') dislikesToIncrement++
513 this.video.likes += likesToIncrement
514 this.video.dislikes += dislikesToIncrement
516 this.video.buildLikeAndDislikePercents()
517 this.setVideoLikesBarTooltipText()
520 private setOpenGraphTags () {
521 this.metaService.setTitle(this.video.name)
523 this.metaService.setTag('og:type', 'video')
525 this.metaService.setTag('og:title', this.video.name)
526 this.metaService.setTag('name', this.video.name)
528 this.metaService.setTag('og:description', this.video.description)
529 this.metaService.setTag('description', this.video.description)
531 this.metaService.setTag('og:image', this.video.previewPath)
533 this.metaService.setTag('og:duration', this.video.duration.toString())
535 this.metaService.setTag('og:site_name', 'PeerTube')
537 this.metaService.setTag('og:url', window.location.href)
538 this.metaService.setTag('url', window.location.href)
541 private isAutoplay () {
542 // We'll jump to the thread id, so do not play the video
543 if (this.route.snapshot.params['threadId']) return false
545 // Otherwise true by default
546 if (!this.user) return true
548 // Be sure the autoPlay is set to false
549 return this.user.autoPlayVideo !== false
552 private flushPlayer () {
553 // Remove player if it exists
556 this.player.dispose()
557 this.player = undefined
559 console.error('Cannot dispose player.', err)
564 private buildPlayerManagerOptions (params: {
566 videoCaptions: VideoCaption[],
567 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
570 const { video, videoCaptions, urlOptions, user } = params
572 let startTime = timeToInt(urlOptions.startTime) || (video.userHistory && !this.playlist ? video.userHistory.currentTime : 0)
573 // If we are at the end of the video, reset the timer
574 if (video.duration - startTime <= 1) startTime = 0
576 const playerCaptions = videoCaptions.map(c => ({
577 label: c.language.label,
578 language: c.language.id,
579 src: environment.apiUrl + c.captionPath
582 const options: PeertubePlayerManagerOptions = {
584 autoplay: this.isAutoplay(),
586 playerElement: this.playerElement,
587 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
589 videoDuration: video.duration,
591 inactivityTimeout: 2500,
592 poster: video.previewUrl,
595 stopTime: urlOptions.stopTime,
596 controls: urlOptions.controls,
597 muted: urlOptions.muted,
598 loop: urlOptions.loop,
599 subtitle: urlOptions.subtitle,
601 peertubeLink: urlOptions.peertubeLink,
604 captions: videoCaptions.length !== 0,
606 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
607 ? this.videoService.getVideoViewUrl(video.uuid)
609 embedUrl: video.embedUrl,
611 language: this.localeId,
613 userWatching: user && user.videosHistoryEnabled === true ? {
614 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
615 authorizationHeader: this.authService.getRequestHeaderValue()
618 serverUrl: environment.apiUrl,
620 videoCaptions: playerCaptions
624 videoFiles: video.files
630 if (urlOptions.playerMode) {
631 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
632 else mode = 'webtorrent'
634 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
635 else mode = 'webtorrent'
638 if (mode === 'p2p-media-loader') {
639 const hlsPlaylist = video.getHlsPlaylist()
641 const p2pMediaLoader = {
642 playlistUrl: hlsPlaylist.playlistUrl,
643 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
644 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
645 trackerAnnounce: video.trackerUrls,
646 videoFiles: hlsPlaylist.files
647 } as P2PMediaLoaderOptions
649 Object.assign(options, { p2pMediaLoader })
652 return { playerMode: mode, playerOptions: options }
655 private pausePlayer () {
656 if (!this.player) return
661 private initHotkeys () {
663 // These hotkeys are managed by the player
664 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
665 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
666 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
668 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)')),
670 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
671 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
673 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
674 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
676 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
677 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
679 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
682 if (this.isUserLoggedIn()) {
683 this.hotkeys = this.hotkeys.concat([
684 new Hotkey('shift+l', () => {
687 }, undefined, this.i18n('Like the video')),
689 new Hotkey('shift+d', () => {
692 }, undefined, this.i18n('Dislike the video')),
694 new Hotkey('shift+s', () => {
695 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
697 }, undefined, this.i18n('Subscribe to the account'))
701 this.hotkeysService.add(this.hotkeys)