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 } from '@app/shared/misc/peertube-local-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'
42 selector: 'my-video-watch',
43 templateUrl: './video-watch.component.html',
44 styleUrls: [ './video-watch.component.scss' ]
46 export class VideoWatchComponent implements OnInit, OnDestroy {
47 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
49 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
50 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
51 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
52 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
55 playerElement: HTMLVideoElement
56 theaterEnabled = false
57 userRating: UserVideoRateType = null
58 descriptionLoading = false
60 video: VideoDetails = null
61 videoCaptions: VideoCaption[] = []
63 playlist: VideoPlaylist = null
65 completeDescriptionShown = false
66 completeVideoDescription: string
67 shortVideoDescription: string
68 videoHTMLDescription = ''
69 likesBarTooltipText = ''
70 hasAlreadyAcceptedPrivacyConcern = false
71 remoteServerDown = false
74 private nextVideoUuid = ''
75 private currentTime: number
76 private paramsSub: Subscription
77 private queryParamsSub: Subscription
78 private configSub: Subscription
81 private elementRef: ElementRef,
82 private changeDetector: ChangeDetectorRef,
83 private route: ActivatedRoute,
84 private router: Router,
85 private videoService: VideoService,
86 private playlistService: VideoPlaylistService,
87 private videoBlacklistService: VideoBlacklistService,
88 private confirmService: ConfirmService,
89 private metaService: MetaService,
90 private authService: AuthService,
91 private serverService: ServerService,
92 private restExtractor: RestExtractor,
93 private notifier: Notifier,
94 private pluginService: PluginService,
95 private markdownService: MarkdownService,
97 private redirectService: RedirectService,
98 private videoCaptionService: VideoCaptionService,
100 private hotkeysService: HotkeysService,
101 private hooks: HooksService,
102 private location: PlatformLocation,
103 @Inject(LOCALE_ID) private localeId: string
107 return this.authService.getUser()
111 this.configSub = this.serverService.configLoaded
114 isWebRTCDisabled() ||
115 this.serverService.getConfig().tracker.enabled === false ||
116 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
118 this.hasAlreadyAcceptedPrivacyConcern = true
122 this.paramsSub = this.route.params.subscribe(routeParams => {
123 const videoId = routeParams[ 'videoId' ]
124 if (videoId) this.loadVideo(videoId)
126 const playlistId = routeParams[ 'playlistId' ]
127 if (playlistId) this.loadPlaylist(playlistId)
130 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
131 const videoId = queryParams[ 'videoId' ]
132 if (videoId) this.loadVideo(videoId)
137 this.theaterEnabled = getStoredTheater()
139 this.hooks.runAction('action:video-watch.init', 'video-watch')
145 // Unsubscribe subscriptions
146 if (this.paramsSub) this.paramsSub.unsubscribe()
147 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
150 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
154 if (this.isUserLoggedIn() === false) return
156 // Already liked this video
157 if (this.userRating === 'like') this.setRating('none')
158 else this.setRating('like')
162 if (this.isUserLoggedIn() === false) return
164 // Already disliked this video
165 if (this.userRating === 'dislike') this.setRating('none')
166 else this.setRating('dislike')
169 getRatePopoverText () {
170 if (this.isUserLoggedIn()) return undefined
172 return this.i18n('You need to be connected to rate this content.')
175 showMoreDescription () {
176 if (this.completeVideoDescription === undefined) {
177 return this.loadCompleteDescription()
180 this.updateVideoDescription(this.completeVideoDescription)
181 this.completeDescriptionShown = true
184 showLessDescription () {
185 this.updateVideoDescription(this.shortVideoDescription)
186 this.completeDescriptionShown = false
189 loadCompleteDescription () {
190 this.descriptionLoading = true
192 this.videoService.loadCompleteDescription(this.video.descriptionPath)
195 this.completeDescriptionShown = true
196 this.descriptionLoading = false
198 this.shortVideoDescription = this.video.description
199 this.completeVideoDescription = description
201 this.updateVideoDescription(this.completeVideoDescription)
205 this.descriptionLoading = false
206 this.notifier.error(error.message)
211 showSupportModal () {
214 this.videoSupportModal.show()
220 this.videoShareModal.show(this.currentTime)
224 return this.authService.isLoggedIn()
228 if (!this.video || Array.isArray(this.video.tags) === false) return []
230 return this.video.tags
233 onRecommendations (videos: Video[]) {
234 if (videos.length > 0) {
235 // Pick a random video until the recommendations are improved
236 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
245 this.redirectService.redirectToHomepage()
248 acceptedPrivacyConcern () {
249 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
250 this.hasAlreadyAcceptedPrivacyConcern = true
253 isVideoToTranscode () {
254 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
258 return this.video && this.video.state.id === VideoState.TO_IMPORT
261 hasVideoScheduledPublication () {
262 return this.video && this.video.scheduledUpdate !== undefined
265 isVideoBlur (video: Video) {
266 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
269 private loadVideo (videoId: string) {
270 // Video did not change
271 if (this.video && this.video.uuid === videoId) return
273 if (this.player) this.player.pause()
275 const videoObs = this.hooks.wrapObsFun(
276 this.videoService.getVideo.bind(this.videoService),
279 'filter:api.video-watch.video.get.params',
280 'filter:api.video-watch.video.get.result'
286 this.videoCaptionService.listCaptions(videoId)
289 // If 401, the video is private or blacklisted so redirect to 404
290 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
292 .subscribe(([ video, captionsResult ]) => {
293 const queryParams = this.route.snapshot.queryParams
296 startTime: queryParams.start,
297 stopTime: queryParams.stop,
299 muted: queryParams.muted,
300 loop: queryParams.loop,
301 subtitle: queryParams.subtitle,
303 playerMode: queryParams.mode,
307 this.onVideoFetched(video, captionsResult.data, urlOptions)
308 .catch(err => this.handleError(err))
312 private loadPlaylist (playlistId: string) {
313 // Playlist did not change
314 if (this.playlist && this.playlist.uuid === playlistId) return
316 this.playlistService.getVideoPlaylist(playlistId)
318 // If 401, the video is private or blacklisted so redirect to 404
319 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
321 .subscribe(playlist => {
322 this.playlist = playlist
324 const videoId = this.route.snapshot.queryParams['videoId']
325 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
329 private updateVideoDescription (description: string) {
330 this.video.description = description
331 this.setVideoDescriptionHTML()
332 .catch(err => console.error(err))
335 private async setVideoDescriptionHTML () {
336 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
339 private setVideoLikesBarTooltipText () {
340 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
341 likesNumber: this.video.likes,
342 dislikesNumber: this.video.dislikes
346 private handleError (err: any) {
347 const errorMessage: string = typeof err === 'string' ? err : err.message
348 if (!errorMessage) return
350 // Display a message in the video player instead of a notification
351 if (errorMessage.indexOf('from xs param') !== -1) {
353 this.remoteServerDown = true
354 this.changeDetector.detectChanges()
359 this.notifier.error(errorMessage)
362 private checkUserRating () {
363 // Unlogged users do not have ratings
364 if (this.isUserLoggedIn() === false) return
366 this.videoService.getUserVideoRating(this.video.id)
370 this.userRating = ratingObject.rating
374 err => this.notifier.error(err.message)
378 private async onVideoFetched (
380 videoCaptions: VideoCaption[],
381 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
384 this.videoCaptions = videoCaptions
386 // Re init attributes
387 this.descriptionLoading = false
388 this.completeDescriptionShown = false
389 this.remoteServerDown = false
390 this.currentTime = undefined
392 this.videoWatchPlaylist.updatePlaylistIndex(video)
394 if (this.isVideoBlur(this.video)) {
395 const res = await this.confirmService.confirm(
396 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
397 this.i18n('Mature or explicit content')
399 if (res === false) return this.location.back()
402 // Flush old player if needed
405 // Build video element, because videojs removes it on dispose
406 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
407 this.playerElement = document.createElement('video')
408 this.playerElement.className = 'video-js vjs-peertube-skin'
409 this.playerElement.setAttribute('playsinline', 'true')
410 playerElementWrapper.appendChild(this.playerElement)
418 const { playerMode, playerOptions } = await this.hooks.wrapFun(
419 this.buildPlayerManagerOptions.bind(this),
421 'filter:internal.video-watch.player.build-options.result'
424 this.zone.runOutsideAngular(async () => {
425 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
428 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
430 this.player.on('timeupdate', () => {
431 this.currentTime = Math.floor(this.player.currentTime())
434 this.player.one('ended', () => {
436 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
437 } else if (this.user && this.user.autoPlayNextVideo) {
438 this.zone.run(() => this.autoplayNext())
442 this.player.one('stopped', () => {
444 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
448 this.player.on('theaterChange', (_: any, enabled: boolean) => {
449 this.zone.run(() => this.theaterEnabled = enabled)
452 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
455 this.setVideoDescriptionHTML()
456 this.setVideoLikesBarTooltipText()
458 this.setOpenGraphTags()
459 this.checkUserRating()
461 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
464 private autoplayNext () {
465 if (this.nextVideoUuid) {
466 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
470 private setRating (nextRating: UserVideoRateType) {
471 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
472 like: this.videoService.setVideoLike,
473 dislike: this.videoService.setVideoDislike,
474 none: this.videoService.unsetVideoLike
477 ratingMethods[nextRating].call(this.videoService, this.video.id)
480 // Update the video like attribute
481 this.updateVideoRating(this.userRating, nextRating)
482 this.userRating = nextRating
485 (err: { message: string }) => this.notifier.error(err.message)
489 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
490 let likesToIncrement = 0
491 let dislikesToIncrement = 0
494 if (oldRating === 'like') likesToIncrement--
495 if (oldRating === 'dislike') dislikesToIncrement--
498 if (newRating === 'like') likesToIncrement++
499 if (newRating === 'dislike') dislikesToIncrement++
501 this.video.likes += likesToIncrement
502 this.video.dislikes += dislikesToIncrement
504 this.video.buildLikeAndDislikePercents()
505 this.setVideoLikesBarTooltipText()
508 private setOpenGraphTags () {
509 this.metaService.setTitle(this.video.name)
511 this.metaService.setTag('og:type', 'video')
513 this.metaService.setTag('og:title', this.video.name)
514 this.metaService.setTag('name', this.video.name)
516 this.metaService.setTag('og:description', this.video.description)
517 this.metaService.setTag('description', this.video.description)
519 this.metaService.setTag('og:image', this.video.previewPath)
521 this.metaService.setTag('og:duration', this.video.duration.toString())
523 this.metaService.setTag('og:site_name', 'PeerTube')
525 this.metaService.setTag('og:url', window.location.href)
526 this.metaService.setTag('url', window.location.href)
529 private isAutoplay () {
530 // We'll jump to the thread id, so do not play the video
531 if (this.route.snapshot.params['threadId']) return false
533 // Otherwise true by default
534 if (!this.user) return true
536 // Be sure the autoPlay is set to false
537 return this.user.autoPlayVideo !== false
540 private flushPlayer () {
541 // Remove player if it exists
544 this.player.dispose()
545 this.player = undefined
547 console.error('Cannot dispose player.', err)
552 private initHotkeys () {
554 new Hotkey('shift+l', () => {
557 }, undefined, this.i18n('Like the video')),
559 new Hotkey('shift+d', () => {
562 }, undefined, this.i18n('Dislike the video')),
564 new Hotkey('shift+s', () => {
565 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
567 }, undefined, this.i18n('Subscribe to the account'))
569 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
572 private buildPlayerManagerOptions (params: {
574 videoCaptions: VideoCaption[],
575 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
578 const { video, videoCaptions, urlOptions, user } = params
580 let startTime = timeToInt(urlOptions.startTime) || (video.userHistory ? video.userHistory.currentTime : 0)
581 // If we are at the end of the video, reset the timer
582 if (video.duration - startTime <= 1) startTime = 0
584 const playerCaptions = videoCaptions.map(c => ({
585 label: c.language.label,
586 language: c.language.id,
587 src: environment.apiUrl + c.captionPath
590 const options: PeertubePlayerManagerOptions = {
592 autoplay: this.isAutoplay(),
594 playerElement: this.playerElement,
595 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
597 videoDuration: video.duration,
599 inactivityTimeout: 2500,
600 poster: video.previewUrl,
603 stopTime: urlOptions.stopTime,
604 controls: urlOptions.controls,
605 muted: urlOptions.muted,
606 loop: urlOptions.loop,
607 subtitle: urlOptions.subtitle,
609 peertubeLink: urlOptions.peertubeLink,
612 captions: videoCaptions.length !== 0,
614 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
615 ? this.videoService.getVideoViewUrl(video.uuid)
617 embedUrl: video.embedUrl,
619 language: this.localeId,
621 userWatching: user && user.videosHistoryEnabled === true ? {
622 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
623 authorizationHeader: this.authService.getRequestHeaderValue()
626 serverUrl: environment.apiUrl,
628 videoCaptions: playerCaptions
632 videoFiles: video.files
638 if (urlOptions.playerMode) {
639 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
640 else mode = 'webtorrent'
642 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
643 else mode = 'webtorrent'
646 if (mode === 'p2p-media-loader') {
647 const hlsPlaylist = video.getHlsPlaylist()
649 const p2pMediaLoader = {
650 playlistUrl: hlsPlaylist.playlistUrl,
651 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
652 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
653 trackerAnnounce: video.trackerUrls,
654 videoFiles: hlsPlaylist.files
655 } as P2PMediaLoaderOptions
657 Object.assign(options, { p2pMediaLoader })
660 return { playerMode: mode, playerOptions: options }
663 private pausePlayer () {
664 if (!this.player) return