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 { 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 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
395 // If we are at the end of the video, reset the timer
396 if (this.video.duration - startTime <= 1) startTime = 0
398 if (this.isVideoBlur(this.video)) {
399 const res = await this.confirmService.confirm(
400 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
401 this.i18n('Mature or explicit content')
403 if (res === false) return this.location.back()
406 // Flush old player if needed
409 // Build video element, because videojs removes it on dispose
410 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
411 this.playerElement = document.createElement('video')
412 this.playerElement.className = 'video-js vjs-peertube-skin'
413 this.playerElement.setAttribute('playsinline', 'true')
414 playerElementWrapper.appendChild(this.playerElement)
416 const playerCaptions = videoCaptions.map(c => ({
417 label: c.language.label,
418 language: c.language.id,
419 src: environment.apiUrl + c.captionPath
422 const options: PeertubePlayerManagerOptions = {
424 autoplay: this.isAutoplay(),
426 playerElement: this.playerElement,
427 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
429 videoDuration: this.video.duration,
431 inactivityTimeout: 2500,
432 poster: this.video.previewUrl,
435 stopTime: urlOptions.stopTime,
436 controls: urlOptions.controls,
437 muted: urlOptions.muted,
438 loop: urlOptions.loop,
439 subtitle: urlOptions.subtitle,
441 peertubeLink: urlOptions.peertubeLink,
444 captions: videoCaptions.length !== 0,
446 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
447 ? this.videoService.getVideoViewUrl(this.video.uuid)
449 embedUrl: this.video.embedUrl,
451 language: this.localeId,
453 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
454 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
455 authorizationHeader: this.authService.getRequestHeaderValue()
458 serverUrl: environment.apiUrl,
460 videoCaptions: playerCaptions
464 videoFiles: this.video.files
470 if (urlOptions.playerMode) {
471 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
472 else mode = 'webtorrent'
474 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
475 else mode = 'webtorrent'
478 if (mode === 'p2p-media-loader') {
479 const hlsPlaylist = this.video.getHlsPlaylist()
481 const p2pMediaLoader = {
482 playlistUrl: hlsPlaylist.playlistUrl,
483 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
484 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
485 trackerAnnounce: this.video.trackerUrls,
486 videoFiles: hlsPlaylist.files
487 } as P2PMediaLoaderOptions
489 Object.assign(options, { p2pMediaLoader })
492 this.zone.runOutsideAngular(async () => {
493 this.player = await PeertubePlayerManager.initialize(mode, options, player => this.player = player)
496 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
498 this.player.on('timeupdate', () => {
499 this.currentTime = Math.floor(this.player.currentTime())
502 this.player.one('ended', () => {
504 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
505 } else if (this.user && this.user.autoPlayNextVideo) {
506 this.zone.run(() => this.autoplayNext())
510 this.player.one('stopped', () => {
512 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
516 this.player.on('theaterChange', (_: any, enabled: boolean) => {
517 this.zone.run(() => this.theaterEnabled = enabled)
520 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
523 this.setVideoDescriptionHTML()
524 this.setVideoLikesBarTooltipText()
526 this.setOpenGraphTags()
527 this.checkUserRating()
529 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
532 private autoplayNext () {
533 if (this.nextVideoUuid) {
534 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
538 private setRating (nextRating: UserVideoRateType) {
539 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
540 like: this.videoService.setVideoLike,
541 dislike: this.videoService.setVideoDislike,
542 none: this.videoService.unsetVideoLike
545 ratingMethods[nextRating].call(this.videoService, this.video.id)
548 // Update the video like attribute
549 this.updateVideoRating(this.userRating, nextRating)
550 this.userRating = nextRating
553 (err: { message: string }) => this.notifier.error(err.message)
557 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
558 let likesToIncrement = 0
559 let dislikesToIncrement = 0
562 if (oldRating === 'like') likesToIncrement--
563 if (oldRating === 'dislike') dislikesToIncrement--
566 if (newRating === 'like') likesToIncrement++
567 if (newRating === 'dislike') dislikesToIncrement++
569 this.video.likes += likesToIncrement
570 this.video.dislikes += dislikesToIncrement
572 this.video.buildLikeAndDislikePercents()
573 this.setVideoLikesBarTooltipText()
576 private setOpenGraphTags () {
577 this.metaService.setTitle(this.video.name)
579 this.metaService.setTag('og:type', 'video')
581 this.metaService.setTag('og:title', this.video.name)
582 this.metaService.setTag('name', this.video.name)
584 this.metaService.setTag('og:description', this.video.description)
585 this.metaService.setTag('description', this.video.description)
587 this.metaService.setTag('og:image', this.video.previewPath)
589 this.metaService.setTag('og:duration', this.video.duration.toString())
591 this.metaService.setTag('og:site_name', 'PeerTube')
593 this.metaService.setTag('og:url', window.location.href)
594 this.metaService.setTag('url', window.location.href)
597 private isAutoplay () {
598 // We'll jump to the thread id, so do not play the video
599 if (this.route.snapshot.params['threadId']) return false
601 // Otherwise true by default
602 if (!this.user) return true
604 // Be sure the autoPlay is set to false
605 return this.user.autoPlayVideo !== false
608 private flushPlayer () {
609 // Remove player if it exists
612 this.player.dispose()
613 this.player = undefined
615 console.error('Cannot dispose player.', err)
620 private initHotkeys () {
622 new Hotkey('shift+l', () => {
625 }, undefined, this.i18n('Like the video')),
627 new Hotkey('shift+d', () => {
630 }, undefined, this.i18n('Dislike the video')),
632 new Hotkey('shift+s', () => {
633 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
635 }, undefined, this.i18n('Subscribe to the account'))
637 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
640 private pausePlayer () {
641 if (!this.player) return