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'
41 import { scrollToTop } from '@app/shared/misc/utils'
44 selector: 'my-video-watch',
45 templateUrl: './video-watch.component.html',
46 styleUrls: [ './video-watch.component.scss' ]
48 export class VideoWatchComponent implements OnInit, OnDestroy {
49 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
51 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
52 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
53 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
54 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
57 playerElement: HTMLVideoElement
58 theaterEnabled = false
59 userRating: UserVideoRateType = null
60 descriptionLoading = false
62 video: VideoDetails = null
63 videoCaptions: VideoCaption[] = []
65 playlist: VideoPlaylist = null
67 completeDescriptionShown = false
68 completeVideoDescription: string
69 shortVideoDescription: string
70 videoHTMLDescription = ''
71 likesBarTooltipText = ''
72 hasAlreadyAcceptedPrivacyConcern = false
73 remoteServerDown = false
74 hotkeys: Hotkey[] = []
79 tooltipSaveToPlaylist = ''
81 private nextVideoUuid = ''
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 // Pick a random video until the recommendations are improved
251 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
260 this.redirectService.redirectToHomepage()
263 acceptedPrivacyConcern () {
264 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
265 this.hasAlreadyAcceptedPrivacyConcern = true
268 isVideoToTranscode () {
269 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
273 return this.video && this.video.state.id === VideoState.TO_IMPORT
276 hasVideoScheduledPublication () {
277 return this.video && this.video.scheduledUpdate !== undefined
280 isVideoBlur (video: Video) {
281 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
284 isAutoPlayEnabled () {
286 (this.user && this.user.autoPlayNextVideo) ||
287 peertubeSessionStorage.getItem(RecommendedVideosComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
291 handleTimestampClicked (timestamp: number) {
292 if (this.player) this.player.currentTime(timestamp)
296 isPlaylistAutoPlayEnabled () {
298 (this.user && this.user.autoPlayNextVideoPlaylist) ||
299 peertubeSessionStorage.getItem(VideoWatchPlaylistComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO_PLAYLIST) === 'true'
303 private loadVideo (videoId: string) {
304 // Video did not change
305 if (this.video && this.video.uuid === videoId) return
307 if (this.player) this.player.pause()
309 const videoObs = this.hooks.wrapObsFun(
310 this.videoService.getVideo.bind(this.videoService),
313 'filter:api.video-watch.video.get.params',
314 'filter:api.video-watch.video.get.result'
320 this.videoCaptionService.listCaptions(videoId)
323 // If 401, the video is private or blacklisted so redirect to 404
324 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
326 .subscribe(([ video, captionsResult ]) => {
327 const queryParams = this.route.snapshot.queryParams
330 startTime: queryParams.start,
331 stopTime: queryParams.stop,
333 muted: queryParams.muted,
334 loop: queryParams.loop,
335 subtitle: queryParams.subtitle,
337 playerMode: queryParams.mode,
341 this.onVideoFetched(video, captionsResult.data, urlOptions)
342 .catch(err => this.handleError(err))
346 private loadPlaylist (playlistId: string) {
347 // Playlist did not change
348 if (this.playlist && this.playlist.uuid === playlistId) return
350 this.playlistService.getVideoPlaylist(playlistId)
352 // If 401, the video is private or blacklisted so redirect to 404
353 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
355 .subscribe(playlist => {
356 this.playlist = playlist
358 const videoId = this.route.snapshot.queryParams['videoId']
359 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
363 private updateVideoDescription (description: string) {
364 this.video.description = description
365 this.setVideoDescriptionHTML()
366 .catch(err => console.error(err))
369 private async setVideoDescriptionHTML () {
370 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
371 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
374 private setVideoLikesBarTooltipText () {
375 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
376 likesNumber: this.video.likes,
377 dislikesNumber: this.video.dislikes
381 private handleError (err: any) {
382 const errorMessage: string = typeof err === 'string' ? err : err.message
383 if (!errorMessage) return
385 // Display a message in the video player instead of a notification
386 if (errorMessage.indexOf('from xs param') !== -1) {
388 this.remoteServerDown = true
389 this.changeDetector.detectChanges()
394 this.notifier.error(errorMessage)
397 private checkUserRating () {
398 // Unlogged users do not have ratings
399 if (this.isUserLoggedIn() === false) return
401 this.videoService.getUserVideoRating(this.video.id)
405 this.userRating = ratingObject.rating
409 err => this.notifier.error(err.message)
413 private async onVideoFetched (
415 videoCaptions: VideoCaption[],
416 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
419 this.videoCaptions = videoCaptions
421 // Re init attributes
422 this.descriptionLoading = false
423 this.completeDescriptionShown = false
424 this.remoteServerDown = false
425 this.currentTime = undefined
427 this.videoWatchPlaylist.updatePlaylistIndex(video)
429 if (this.isVideoBlur(this.video)) {
430 const res = await this.confirmService.confirm(
431 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
432 this.i18n('Mature or explicit content')
434 if (res === false) return this.location.back()
437 // Flush old player if needed
440 // Build video element, because videojs removes it on dispose
441 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
442 this.playerElement = document.createElement('video')
443 this.playerElement.className = 'video-js vjs-peertube-skin'
444 this.playerElement.setAttribute('playsinline', 'true')
445 playerElementWrapper.appendChild(this.playerElement)
453 const { playerMode, playerOptions } = await this.hooks.wrapFun(
454 this.buildPlayerManagerOptions.bind(this),
457 'filter:internal.video-watch.player.build-options.params',
458 'filter:internal.video-watch.player.build-options.result'
461 this.zone.runOutsideAngular(async () => {
462 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
465 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
467 this.player.on('timeupdate', () => {
468 this.currentTime = Math.floor(this.player.currentTime())
471 this.player.one('ended', () => {
473 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
474 } else if (this.isAutoPlayEnabled()) {
475 this.zone.run(() => this.autoplayNext())
479 this.player.one('stopped', () => {
481 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
485 this.player.on('theaterChange', (_: any, enabled: boolean) => {
486 this.zone.run(() => this.theaterEnabled = enabled)
489 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
492 this.setVideoDescriptionHTML()
493 this.setVideoLikesBarTooltipText()
495 this.setOpenGraphTags()
496 this.checkUserRating()
498 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
501 private autoplayNext () {
502 if (this.nextVideoUuid) {
503 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
507 private setRating (nextRating: UserVideoRateType) {
508 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
509 like: this.videoService.setVideoLike,
510 dislike: this.videoService.setVideoDislike,
511 none: this.videoService.unsetVideoLike
514 ratingMethods[nextRating].call(this.videoService, this.video.id)
517 // Update the video like attribute
518 this.updateVideoRating(this.userRating, nextRating)
519 this.userRating = nextRating
522 (err: { message: string }) => this.notifier.error(err.message)
526 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
527 let likesToIncrement = 0
528 let dislikesToIncrement = 0
531 if (oldRating === 'like') likesToIncrement--
532 if (oldRating === 'dislike') dislikesToIncrement--
535 if (newRating === 'like') likesToIncrement++
536 if (newRating === 'dislike') dislikesToIncrement++
538 this.video.likes += likesToIncrement
539 this.video.dislikes += dislikesToIncrement
541 this.video.buildLikeAndDislikePercents()
542 this.setVideoLikesBarTooltipText()
545 private setOpenGraphTags () {
546 this.metaService.setTitle(this.video.name)
548 this.metaService.setTag('og:type', 'video')
550 this.metaService.setTag('og:title', this.video.name)
551 this.metaService.setTag('name', this.video.name)
553 this.metaService.setTag('og:description', this.video.description)
554 this.metaService.setTag('description', this.video.description)
556 this.metaService.setTag('og:image', this.video.previewPath)
558 this.metaService.setTag('og:duration', this.video.duration.toString())
560 this.metaService.setTag('og:site_name', 'PeerTube')
562 this.metaService.setTag('og:url', window.location.href)
563 this.metaService.setTag('url', window.location.href)
566 private isAutoplay () {
567 // We'll jump to the thread id, so do not play the video
568 if (this.route.snapshot.params['threadId']) return false
570 // Otherwise true by default
571 if (!this.user) return true
573 // Be sure the autoPlay is set to false
574 return this.user.autoPlayVideo !== false
577 private flushPlayer () {
578 // Remove player if it exists
581 this.player.dispose()
582 this.player = undefined
584 console.error('Cannot dispose player.', err)
589 private buildPlayerManagerOptions (params: {
591 videoCaptions: VideoCaption[],
592 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
595 const { video, videoCaptions, urlOptions, user } = params
596 const getStartTime = () => {
597 const byUrl = urlOptions.startTime !== undefined
598 const byHistory = video.userHistory && !this.playlist
601 return timeToInt(urlOptions.startTime)
602 } else if (byHistory) {
603 return video.userHistory.currentTime
609 let startTime = getStartTime()
610 // If we are at the end of the video, reset the timer
611 if (video.duration - startTime <= 1) startTime = 0
613 const playerCaptions = videoCaptions.map(c => ({
614 label: c.language.label,
615 language: c.language.id,
616 src: environment.apiUrl + c.captionPath
619 const options: PeertubePlayerManagerOptions = {
621 autoplay: this.isAutoplay(),
623 playerElement: this.playerElement,
624 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
626 videoDuration: video.duration,
628 inactivityTimeout: 2500,
629 poster: video.previewUrl,
632 stopTime: urlOptions.stopTime,
633 controls: urlOptions.controls,
634 muted: urlOptions.muted,
635 loop: urlOptions.loop,
636 subtitle: urlOptions.subtitle,
638 peertubeLink: urlOptions.peertubeLink,
641 captions: videoCaptions.length !== 0,
643 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
644 ? this.videoService.getVideoViewUrl(video.uuid)
646 embedUrl: video.embedUrl,
648 language: this.localeId,
650 userWatching: user && user.videosHistoryEnabled === true ? {
651 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
652 authorizationHeader: this.authService.getRequestHeaderValue()
655 serverUrl: environment.apiUrl,
657 videoCaptions: playerCaptions
661 videoFiles: video.files
667 if (urlOptions.playerMode) {
668 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
669 else mode = 'webtorrent'
671 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
672 else mode = 'webtorrent'
675 if (mode === 'p2p-media-loader') {
676 const hlsPlaylist = video.getHlsPlaylist()
678 const p2pMediaLoader = {
679 playlistUrl: hlsPlaylist.playlistUrl,
680 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
681 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
682 trackerAnnounce: video.trackerUrls,
683 videoFiles: hlsPlaylist.files
684 } as P2PMediaLoaderOptions
686 Object.assign(options, { p2pMediaLoader })
689 return { playerMode: mode, playerOptions: options }
692 private pausePlayer () {
693 if (!this.player) return
698 private initHotkeys () {
700 // These hotkeys are managed by the player
701 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
702 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
703 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
705 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)')),
707 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
708 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
710 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
711 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
713 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
714 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
716 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
719 if (this.isUserLoggedIn()) {
720 this.hotkeys = this.hotkeys.concat([
721 new Hotkey('shift+l', () => {
724 }, undefined, this.i18n('Like the video')),
726 new Hotkey('shift+d', () => {
729 }, undefined, this.i18n('Dislike the video')),
731 new Hotkey('shift+s', () => {
732 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
734 }, undefined, this.i18n('Subscribe to the account'))
738 this.hotkeysService.add(this.hotkeys)