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'
24 P2PMediaLoaderOptions,
25 PeertubePlayerManager,
26 PeertubePlayerManagerOptions,
28 } from '../../../assets/player/peertube-player-manager'
29 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
30 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
31 import { Video } from '@app/shared/video/video.model'
32 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
33 import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
34 import { getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
35 import { PluginService } from '@app/core/plugins/plugin.service'
36 import { HooksService } from '@app/core/plugins/hooks.service'
37 import { PlatformLocation } from '@angular/common'
38 import { randomInt } from '@shared/core-utils/miscs/miscs'
41 selector: 'my-video-watch',
42 templateUrl: './video-watch.component.html',
43 styleUrls: [ './video-watch.component.scss' ]
45 export class VideoWatchComponent implements OnInit, OnDestroy {
46 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
48 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
49 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
50 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
51 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
54 playerElement: HTMLVideoElement
55 theaterEnabled = false
56 userRating: UserVideoRateType = null
57 descriptionLoading = false
59 video: VideoDetails = null
60 videoCaptions: VideoCaption[] = []
62 playlist: VideoPlaylist = null
64 completeDescriptionShown = false
65 completeVideoDescription: string
66 shortVideoDescription: string
67 videoHTMLDescription = ''
68 likesBarTooltipText = ''
69 hasAlreadyAcceptedPrivacyConcern = false
70 remoteServerDown = false
73 private nextVideoUuid = ''
74 private currentTime: number
75 private paramsSub: Subscription
76 private queryParamsSub: Subscription
77 private configSub: Subscription
80 private elementRef: ElementRef,
81 private changeDetector: ChangeDetectorRef,
82 private route: ActivatedRoute,
83 private router: Router,
84 private videoService: VideoService,
85 private playlistService: VideoPlaylistService,
86 private videoBlacklistService: VideoBlacklistService,
87 private confirmService: ConfirmService,
88 private metaService: MetaService,
89 private authService: AuthService,
90 private serverService: ServerService,
91 private restExtractor: RestExtractor,
92 private notifier: Notifier,
93 private pluginService: PluginService,
94 private markdownService: MarkdownService,
96 private redirectService: RedirectService,
97 private videoCaptionService: VideoCaptionService,
99 private hotkeysService: HotkeysService,
100 private hooks: HooksService,
101 private location: PlatformLocation,
102 @Inject(LOCALE_ID) private localeId: string
106 return this.authService.getUser()
110 this.configSub = this.serverService.configLoaded
113 isWebRTCDisabled() ||
114 this.serverService.getConfig().tracker.enabled === false ||
115 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
117 this.hasAlreadyAcceptedPrivacyConcern = true
121 this.paramsSub = this.route.params.subscribe(routeParams => {
122 const videoId = routeParams[ 'videoId' ]
123 if (videoId) this.loadVideo(videoId)
125 const playlistId = routeParams[ 'playlistId' ]
126 if (playlistId) this.loadPlaylist(playlistId)
129 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
130 const videoId = queryParams[ 'videoId' ]
131 if (videoId) this.loadVideo(videoId)
136 this.theaterEnabled = getStoredTheater()
138 this.hooks.runAction('action:video-watch.init', 'video-watch')
144 // Unsubscribe subscriptions
145 if (this.paramsSub) this.paramsSub.unsubscribe()
146 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
149 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
153 if (this.isUserLoggedIn() === false) return
155 // Already liked this video
156 if (this.userRating === 'like') this.setRating('none')
157 else this.setRating('like')
161 if (this.isUserLoggedIn() === false) return
163 // Already disliked this video
164 if (this.userRating === 'dislike') this.setRating('none')
165 else this.setRating('dislike')
168 showMoreDescription () {
169 if (this.completeVideoDescription === undefined) {
170 return this.loadCompleteDescription()
173 this.updateVideoDescription(this.completeVideoDescription)
174 this.completeDescriptionShown = true
177 showLessDescription () {
178 this.updateVideoDescription(this.shortVideoDescription)
179 this.completeDescriptionShown = false
182 loadCompleteDescription () {
183 this.descriptionLoading = true
185 this.videoService.loadCompleteDescription(this.video.descriptionPath)
188 this.completeDescriptionShown = true
189 this.descriptionLoading = false
191 this.shortVideoDescription = this.video.description
192 this.completeVideoDescription = description
194 this.updateVideoDescription(this.completeVideoDescription)
198 this.descriptionLoading = false
199 this.notifier.error(error.message)
204 showSupportModal () {
205 this.videoSupportModal.show()
209 this.videoShareModal.show(this.currentTime)
213 return this.authService.isLoggedIn()
217 if (!this.video || Array.isArray(this.video.tags) === false) return []
219 return this.video.tags
222 onRecommendations (videos: Video[]) {
223 if (videos.length > 0) {
224 // Pick a random video until the recommendations are improved
225 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
230 this.redirectService.redirectToHomepage()
233 acceptedPrivacyConcern () {
234 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
235 this.hasAlreadyAcceptedPrivacyConcern = true
238 isVideoToTranscode () {
239 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
243 return this.video && this.video.state.id === VideoState.TO_IMPORT
246 hasVideoScheduledPublication () {
247 return this.video && this.video.scheduledUpdate !== undefined
250 isVideoBlur (video: Video) {
251 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
254 private loadVideo (videoId: string) {
255 // Video did not change
256 if (this.video && this.video.uuid === videoId) return
258 if (this.player) this.player.pause()
260 const videoObs = this.hooks.wrapObsFun(
261 this.videoService.getVideo.bind(this.videoService),
264 'filter:api.video-watch.video.get.params',
265 'filter:api.video-watch.video.get.result'
271 this.videoCaptionService.listCaptions(videoId)
274 // If 401, the video is private or blacklisted so redirect to 404
275 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
277 .subscribe(([ video, captionsResult ]) => {
278 const queryParams = this.route.snapshot.queryParams
281 startTime: queryParams.start,
282 stopTime: queryParams.stop,
284 muted: queryParams.muted,
285 loop: queryParams.loop,
286 subtitle: queryParams.subtitle,
288 playerMode: queryParams.mode,
292 this.onVideoFetched(video, captionsResult.data, urlOptions)
293 .catch(err => this.handleError(err))
297 private loadPlaylist (playlistId: string) {
298 // Playlist did not change
299 if (this.playlist && this.playlist.uuid === playlistId) return
301 this.playlistService.getVideoPlaylist(playlistId)
303 // If 401, the video is private or blacklisted so redirect to 404
304 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
306 .subscribe(playlist => {
307 this.playlist = playlist
309 const videoId = this.route.snapshot.queryParams['videoId']
310 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
314 private updateVideoDescription (description: string) {
315 this.video.description = description
316 this.setVideoDescriptionHTML()
317 .catch(err => console.error(err))
320 private async setVideoDescriptionHTML () {
321 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
324 private setVideoLikesBarTooltipText () {
325 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
326 likesNumber: this.video.likes,
327 dislikesNumber: this.video.dislikes
331 private handleError (err: any) {
332 const errorMessage: string = typeof err === 'string' ? err : err.message
333 if (!errorMessage) return
335 // Display a message in the video player instead of a notification
336 if (errorMessage.indexOf('from xs param') !== -1) {
338 this.remoteServerDown = true
339 this.changeDetector.detectChanges()
344 this.notifier.error(errorMessage)
347 private checkUserRating () {
348 // Unlogged users do not have ratings
349 if (this.isUserLoggedIn() === false) return
351 this.videoService.getUserVideoRating(this.video.id)
355 this.userRating = ratingObject.rating
359 err => this.notifier.error(err.message)
363 private async onVideoFetched (
365 videoCaptions: VideoCaption[],
366 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
369 this.videoCaptions = videoCaptions
371 // Re init attributes
372 this.descriptionLoading = false
373 this.completeDescriptionShown = false
374 this.remoteServerDown = false
375 this.currentTime = undefined
377 this.videoWatchPlaylist.updatePlaylistIndex(video)
379 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
380 // If we are at the end of the video, reset the timer
381 if (this.video.duration - startTime <= 1) startTime = 0
383 if (this.isVideoBlur(this.video)) {
384 const res = await this.confirmService.confirm(
385 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
386 this.i18n('Mature or explicit content')
388 if (res === false) return this.location.back()
391 // Flush old player if needed
394 // Build video element, because videojs removes it on dispose
395 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
396 this.playerElement = document.createElement('video')
397 this.playerElement.className = 'video-js vjs-peertube-skin'
398 this.playerElement.setAttribute('playsinline', 'true')
399 playerElementWrapper.appendChild(this.playerElement)
401 const playerCaptions = videoCaptions.map(c => ({
402 label: c.language.label,
403 language: c.language.id,
404 src: environment.apiUrl + c.captionPath
407 const options: PeertubePlayerManagerOptions = {
409 autoplay: this.isAutoplay(),
411 playerElement: this.playerElement,
412 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
414 videoDuration: this.video.duration,
416 inactivityTimeout: 2500,
417 poster: this.video.previewUrl,
420 stopTime: urlOptions.stopTime,
421 controls: urlOptions.controls,
422 muted: urlOptions.muted,
423 loop: urlOptions.loop,
424 subtitle: urlOptions.subtitle,
426 peertubeLink: urlOptions.peertubeLink,
429 captions: videoCaptions.length !== 0,
431 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
432 ? this.videoService.getVideoViewUrl(this.video.uuid)
434 embedUrl: this.video.embedUrl,
436 language: this.localeId,
438 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
439 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
440 authorizationHeader: this.authService.getRequestHeaderValue()
443 serverUrl: environment.apiUrl,
445 videoCaptions: playerCaptions
449 videoFiles: this.video.files
455 if (urlOptions.playerMode) {
456 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
457 else mode = 'webtorrent'
459 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
460 else mode = 'webtorrent'
463 if (mode === 'p2p-media-loader') {
464 const hlsPlaylist = this.video.getHlsPlaylist()
466 const p2pMediaLoader = {
467 playlistUrl: hlsPlaylist.playlistUrl,
468 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
469 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
470 trackerAnnounce: this.video.trackerUrls,
471 videoFiles: this.video.files
472 } as P2PMediaLoaderOptions
474 Object.assign(options, { p2pMediaLoader })
477 this.zone.runOutsideAngular(async () => {
478 this.player = await PeertubePlayerManager.initialize(mode, options, player => this.player = player)
480 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
482 this.player.on('timeupdate', () => {
483 this.currentTime = Math.floor(this.player.currentTime())
486 this.player.one('ended', () => {
488 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
489 } else if (this.user && this.user.autoPlayNextVideo) {
490 this.zone.run(() => this.autoplayNext())
494 this.player.one('stopped', () => {
496 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
500 this.player.on('theaterChange', (_: any, enabled: boolean) => {
501 this.zone.run(() => this.theaterEnabled = enabled)
505 this.setVideoDescriptionHTML()
506 this.setVideoLikesBarTooltipText()
508 this.setOpenGraphTags()
509 this.checkUserRating()
511 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch')
514 private autoplayNext () {
515 if (this.nextVideoUuid) {
516 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
520 private setRating (nextRating: UserVideoRateType) {
521 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
522 like: this.videoService.setVideoLike,
523 dislike: this.videoService.setVideoDislike,
524 none: this.videoService.unsetVideoLike
527 ratingMethods[nextRating].call(this.videoService, this.video.id)
530 // Update the video like attribute
531 this.updateVideoRating(this.userRating, nextRating)
532 this.userRating = nextRating
535 (err: { message: string }) => this.notifier.error(err.message)
539 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
540 let likesToIncrement = 0
541 let dislikesToIncrement = 0
544 if (oldRating === 'like') likesToIncrement--
545 if (oldRating === 'dislike') dislikesToIncrement--
548 if (newRating === 'like') likesToIncrement++
549 if (newRating === 'dislike') dislikesToIncrement++
551 this.video.likes += likesToIncrement
552 this.video.dislikes += dislikesToIncrement
554 this.video.buildLikeAndDislikePercents()
555 this.setVideoLikesBarTooltipText()
558 private setOpenGraphTags () {
559 this.metaService.setTitle(this.video.name)
561 this.metaService.setTag('og:type', 'video')
563 this.metaService.setTag('og:title', this.video.name)
564 this.metaService.setTag('name', this.video.name)
566 this.metaService.setTag('og:description', this.video.description)
567 this.metaService.setTag('description', this.video.description)
569 this.metaService.setTag('og:image', this.video.previewPath)
571 this.metaService.setTag('og:duration', this.video.duration.toString())
573 this.metaService.setTag('og:site_name', 'PeerTube')
575 this.metaService.setTag('og:url', window.location.href)
576 this.metaService.setTag('url', window.location.href)
579 private isAutoplay () {
580 // We'll jump to the thread id, so do not play the video
581 if (this.route.snapshot.params['threadId']) return false
583 // Otherwise true by default
584 if (!this.user) return true
586 // Be sure the autoPlay is set to false
587 return this.user.autoPlayVideo !== false
590 private flushPlayer () {
591 // Remove player if it exists
594 this.player.dispose()
595 this.player = undefined
597 console.error('Cannot dispose player.', err)
602 private initHotkeys () {
604 new Hotkey('shift+l', () => {
607 }, undefined, this.i18n('Like the video')),
609 new Hotkey('shift+d', () => {
612 }, undefined, this.i18n('Dislike the video')),
614 new Hotkey('shift+s', () => {
615 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
617 }, undefined, this.i18n('Subscribe to the account'))
619 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)