Fix dropdown on video miniature for unlogged users
[oweals/peertube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
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'
22 import {
23   videojs,
24   CustomizationOptions,
25   P2PMediaLoaderOptions,
26   PeertubePlayerManager,
27   PeertubePlayerManagerOptions,
28   PlayerMode
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
41 @Component({
42   selector: 'my-video-watch',
43   templateUrl: './video-watch.component.html',
44   styleUrls: [ './video-watch.component.scss' ]
45 })
46 export class VideoWatchComponent implements OnInit, OnDestroy {
47   private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
48
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
53
54   player: any
55   playerElement: HTMLVideoElement
56   theaterEnabled = false
57   userRating: UserVideoRateType = null
58   descriptionLoading = false
59
60   video: VideoDetails = null
61   videoCaptions: VideoCaption[] = []
62
63   playlist: VideoPlaylist = null
64
65   completeDescriptionShown = false
66   completeVideoDescription: string
67   shortVideoDescription: string
68   videoHTMLDescription = ''
69   likesBarTooltipText = ''
70   hasAlreadyAcceptedPrivacyConcern = false
71   remoteServerDown = false
72   hotkeys: Hotkey[] = []
73
74   private nextVideoUuid = ''
75   private currentTime: number
76   private paramsSub: Subscription
77   private queryParamsSub: Subscription
78   private configSub: Subscription
79
80   constructor (
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,
96     private zone: NgZone,
97     private redirectService: RedirectService,
98     private videoCaptionService: VideoCaptionService,
99     private i18n: I18n,
100     private hotkeysService: HotkeysService,
101     private hooks: HooksService,
102     private location: PlatformLocation,
103     @Inject(LOCALE_ID) private localeId: string
104   ) {}
105
106   get user () {
107     return this.authService.getUser()
108   }
109
110   async ngOnInit () {
111     this.configSub = this.serverService.configLoaded
112         .subscribe(() => {
113           if (
114             isWebRTCDisabled() ||
115             this.serverService.getConfig().tracker.enabled === false ||
116             peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
117           ) {
118             this.hasAlreadyAcceptedPrivacyConcern = true
119           }
120         })
121
122     this.paramsSub = this.route.params.subscribe(routeParams => {
123       const videoId = routeParams[ 'videoId' ]
124       if (videoId) this.loadVideo(videoId)
125
126       const playlistId = routeParams[ 'playlistId' ]
127       if (playlistId) this.loadPlaylist(playlistId)
128     })
129
130     this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
131       const videoId = queryParams[ 'videoId' ]
132       if (videoId) this.loadVideo(videoId)
133     })
134
135     this.initHotkeys()
136
137     this.theaterEnabled = getStoredTheater()
138
139     this.hooks.runAction('action:video-watch.init', 'video-watch')
140   }
141
142   ngOnDestroy () {
143     this.flushPlayer()
144
145     // Unsubscribe subscriptions
146     if (this.paramsSub) this.paramsSub.unsubscribe()
147     if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
148
149     // Unbind hotkeys
150     this.hotkeysService.remove(this.hotkeys)
151   }
152
153   setLike () {
154     if (this.isUserLoggedIn() === false) return
155
156     // Already liked this video
157     if (this.userRating === 'like') this.setRating('none')
158     else this.setRating('like')
159   }
160
161   setDislike () {
162     if (this.isUserLoggedIn() === false) return
163
164     // Already disliked this video
165     if (this.userRating === 'dislike') this.setRating('none')
166     else this.setRating('dislike')
167   }
168
169   getRatePopoverText () {
170     if (this.isUserLoggedIn()) return undefined
171
172     return this.i18n('You need to be connected to rate this content.')
173   }
174
175   showMoreDescription () {
176     if (this.completeVideoDescription === undefined) {
177       return this.loadCompleteDescription()
178     }
179
180     this.updateVideoDescription(this.completeVideoDescription)
181     this.completeDescriptionShown = true
182   }
183
184   showLessDescription () {
185     this.updateVideoDescription(this.shortVideoDescription)
186     this.completeDescriptionShown = false
187   }
188
189   loadCompleteDescription () {
190     this.descriptionLoading = true
191
192     this.videoService.loadCompleteDescription(this.video.descriptionPath)
193         .subscribe(
194           description => {
195             this.completeDescriptionShown = true
196             this.descriptionLoading = false
197
198             this.shortVideoDescription = this.video.description
199             this.completeVideoDescription = description
200
201             this.updateVideoDescription(this.completeVideoDescription)
202           },
203
204           error => {
205             this.descriptionLoading = false
206             this.notifier.error(error.message)
207           }
208         )
209   }
210
211   showSupportModal () {
212     this.pausePlayer()
213
214     this.videoSupportModal.show()
215   }
216
217   showShareModal () {
218     this.pausePlayer()
219
220     this.videoShareModal.show(this.currentTime)
221   }
222
223   isUserLoggedIn () {
224     return this.authService.isLoggedIn()
225   }
226
227   getVideoTags () {
228     if (!this.video || Array.isArray(this.video.tags) === false) return []
229
230     return this.video.tags
231   }
232
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
237     }
238   }
239
240   onModalOpened () {
241     this.pausePlayer()
242   }
243
244   onVideoRemoved () {
245     this.redirectService.redirectToHomepage()
246   }
247
248   acceptedPrivacyConcern () {
249     peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
250     this.hasAlreadyAcceptedPrivacyConcern = true
251   }
252
253   isVideoToTranscode () {
254     return this.video && this.video.state.id === VideoState.TO_TRANSCODE
255   }
256
257   isVideoToImport () {
258     return this.video && this.video.state.id === VideoState.TO_IMPORT
259   }
260
261   hasVideoScheduledPublication () {
262     return this.video && this.video.scheduledUpdate !== undefined
263   }
264
265   isVideoBlur (video: Video) {
266     return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
267   }
268
269   private loadVideo (videoId: string) {
270     // Video did not change
271     if (this.video && this.video.uuid === videoId) return
272
273     if (this.player) this.player.pause()
274
275     const videoObs = this.hooks.wrapObsFun(
276       this.videoService.getVideo.bind(this.videoService),
277       { videoId },
278       'video-watch',
279       'filter:api.video-watch.video.get.params',
280       'filter:api.video-watch.video.get.result'
281     )
282
283     // Video did change
284     forkJoin([
285       videoObs,
286       this.videoCaptionService.listCaptions(videoId)
287     ])
288       .pipe(
289         // If 401, the video is private or blacklisted so redirect to 404
290         catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
291       )
292       .subscribe(([ video, captionsResult ]) => {
293         const queryParams = this.route.snapshot.queryParams
294
295         const urlOptions = {
296           startTime: queryParams.start,
297           stopTime: queryParams.stop,
298
299           muted: queryParams.muted,
300           loop: queryParams.loop,
301           subtitle: queryParams.subtitle,
302
303           playerMode: queryParams.mode,
304           peertubeLink: false
305         }
306
307         this.onVideoFetched(video, captionsResult.data, urlOptions)
308             .catch(err => this.handleError(err))
309       })
310   }
311
312   private loadPlaylist (playlistId: string) {
313     // Playlist did not change
314     if (this.playlist && this.playlist.uuid === playlistId) return
315
316     this.playlistService.getVideoPlaylist(playlistId)
317       .pipe(
318         // If 401, the video is private or blacklisted so redirect to 404
319         catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
320       )
321       .subscribe(playlist => {
322         this.playlist = playlist
323
324         const videoId = this.route.snapshot.queryParams['videoId']
325         this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
326       })
327   }
328
329   private updateVideoDescription (description: string) {
330     this.video.description = description
331     this.setVideoDescriptionHTML()
332       .catch(err => console.error(err))
333   }
334
335   private async setVideoDescriptionHTML () {
336     this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
337   }
338
339   private setVideoLikesBarTooltipText () {
340     this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
341       likesNumber: this.video.likes,
342       dislikesNumber: this.video.dislikes
343     })
344   }
345
346   private handleError (err: any) {
347     const errorMessage: string = typeof err === 'string' ? err : err.message
348     if (!errorMessage) return
349
350     // Display a message in the video player instead of a notification
351     if (errorMessage.indexOf('from xs param') !== -1) {
352       this.flushPlayer()
353       this.remoteServerDown = true
354       this.changeDetector.detectChanges()
355
356       return
357     }
358
359     this.notifier.error(errorMessage)
360   }
361
362   private checkUserRating () {
363     // Unlogged users do not have ratings
364     if (this.isUserLoggedIn() === false) return
365
366     this.videoService.getUserVideoRating(this.video.id)
367         .subscribe(
368           ratingObject => {
369             if (ratingObject) {
370               this.userRating = ratingObject.rating
371             }
372           },
373
374           err => this.notifier.error(err.message)
375         )
376   }
377
378   private async onVideoFetched (
379     video: VideoDetails,
380     videoCaptions: VideoCaption[],
381     urlOptions: CustomizationOptions & { playerMode: PlayerMode }
382   ) {
383     this.video = video
384     this.videoCaptions = videoCaptions
385
386     // Re init attributes
387     this.descriptionLoading = false
388     this.completeDescriptionShown = false
389     this.remoteServerDown = false
390     this.currentTime = undefined
391
392     this.videoWatchPlaylist.updatePlaylistIndex(video)
393
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')
398       )
399       if (res === false) return this.location.back()
400     }
401
402     // Flush old player if needed
403     this.flushPlayer()
404
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)
411
412     const params = {
413       video: this.video,
414       videoCaptions,
415       urlOptions,
416       user: this.user
417     }
418     const { playerMode, playerOptions } = await this.hooks.wrapFun(
419       this.buildPlayerManagerOptions.bind(this),
420       params,
421       'video-watch',
422       'filter:internal.video-watch.player.build-options.params',
423       'filter:internal.video-watch.player.build-options.result'
424     )
425
426     this.zone.runOutsideAngular(async () => {
427       this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
428       this.player.focus()
429
430       this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
431
432       this.player.on('timeupdate', () => {
433         this.currentTime = Math.floor(this.player.currentTime())
434       })
435
436       this.player.one('ended', () => {
437         if (this.playlist) {
438           this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
439         } else if (this.user && this.user.autoPlayNextVideo) {
440           this.zone.run(() => this.autoplayNext())
441         }
442       })
443
444       this.player.one('stopped', () => {
445         if (this.playlist) {
446           this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
447         }
448       })
449
450       this.player.on('theaterChange', (_: any, enabled: boolean) => {
451         this.zone.run(() => this.theaterEnabled = enabled)
452       })
453
454       this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
455     })
456
457     this.setVideoDescriptionHTML()
458     this.setVideoLikesBarTooltipText()
459
460     this.setOpenGraphTags()
461     this.checkUserRating()
462
463     this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
464   }
465
466   private autoplayNext () {
467     if (this.nextVideoUuid) {
468       this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
469     }
470   }
471
472   private setRating (nextRating: UserVideoRateType) {
473     const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
474       like: this.videoService.setVideoLike,
475       dislike: this.videoService.setVideoDislike,
476       none: this.videoService.unsetVideoLike
477     }
478
479     ratingMethods[nextRating].call(this.videoService, this.video.id)
480           .subscribe(
481             () => {
482               // Update the video like attribute
483               this.updateVideoRating(this.userRating, nextRating)
484               this.userRating = nextRating
485             },
486
487             (err: { message: string }) => this.notifier.error(err.message)
488           )
489   }
490
491   private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
492     let likesToIncrement = 0
493     let dislikesToIncrement = 0
494
495     if (oldRating) {
496       if (oldRating === 'like') likesToIncrement--
497       if (oldRating === 'dislike') dislikesToIncrement--
498     }
499
500     if (newRating === 'like') likesToIncrement++
501     if (newRating === 'dislike') dislikesToIncrement++
502
503     this.video.likes += likesToIncrement
504     this.video.dislikes += dislikesToIncrement
505
506     this.video.buildLikeAndDislikePercents()
507     this.setVideoLikesBarTooltipText()
508   }
509
510   private setOpenGraphTags () {
511     this.metaService.setTitle(this.video.name)
512
513     this.metaService.setTag('og:type', 'video')
514
515     this.metaService.setTag('og:title', this.video.name)
516     this.metaService.setTag('name', this.video.name)
517
518     this.metaService.setTag('og:description', this.video.description)
519     this.metaService.setTag('description', this.video.description)
520
521     this.metaService.setTag('og:image', this.video.previewPath)
522
523     this.metaService.setTag('og:duration', this.video.duration.toString())
524
525     this.metaService.setTag('og:site_name', 'PeerTube')
526
527     this.metaService.setTag('og:url', window.location.href)
528     this.metaService.setTag('url', window.location.href)
529   }
530
531   private isAutoplay () {
532     // We'll jump to the thread id, so do not play the video
533     if (this.route.snapshot.params['threadId']) return false
534
535     // Otherwise true by default
536     if (!this.user) return true
537
538     // Be sure the autoPlay is set to false
539     return this.user.autoPlayVideo !== false
540   }
541
542   private flushPlayer () {
543     // Remove player if it exists
544     if (this.player) {
545       try {
546         this.player.dispose()
547         this.player = undefined
548       } catch (err) {
549         console.error('Cannot dispose player.', err)
550       }
551     }
552   }
553
554   private buildPlayerManagerOptions (params: {
555     video: VideoDetails,
556     videoCaptions: VideoCaption[],
557     urlOptions: CustomizationOptions & { playerMode: PlayerMode },
558     user?: AuthUser
559   }) {
560     const { video, videoCaptions, urlOptions, user } = params
561
562     let startTime = timeToInt(urlOptions.startTime) || (video.userHistory ? video.userHistory.currentTime : 0)
563     // If we are at the end of the video, reset the timer
564     if (video.duration - startTime <= 1) startTime = 0
565
566     const playerCaptions = videoCaptions.map(c => ({
567       label: c.language.label,
568       language: c.language.id,
569       src: environment.apiUrl + c.captionPath
570     }))
571
572     const options: PeertubePlayerManagerOptions = {
573       common: {
574         autoplay: this.isAutoplay(),
575
576         playerElement: this.playerElement,
577         onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
578
579         videoDuration: video.duration,
580         enableHotkeys: true,
581         inactivityTimeout: 2500,
582         poster: video.previewUrl,
583
584         startTime,
585         stopTime: urlOptions.stopTime,
586         controls: urlOptions.controls,
587         muted: urlOptions.muted,
588         loop: urlOptions.loop,
589         subtitle: urlOptions.subtitle,
590
591         peertubeLink: urlOptions.peertubeLink,
592
593         theaterButton: true,
594         captions: videoCaptions.length !== 0,
595
596         videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
597           ? this.videoService.getVideoViewUrl(video.uuid)
598           : null,
599         embedUrl: video.embedUrl,
600
601         language: this.localeId,
602
603         userWatching: user && user.videosHistoryEnabled === true ? {
604           url: this.videoService.getUserWatchingVideoUrl(video.uuid),
605           authorizationHeader: this.authService.getRequestHeaderValue()
606         } : undefined,
607
608         serverUrl: environment.apiUrl,
609
610         videoCaptions: playerCaptions
611       },
612
613       webtorrent: {
614         videoFiles: video.files
615       }
616     }
617
618     let mode: PlayerMode
619
620     if (urlOptions.playerMode) {
621       if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
622       else mode = 'webtorrent'
623     } else {
624       if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
625       else mode = 'webtorrent'
626     }
627
628     if (mode === 'p2p-media-loader') {
629       const hlsPlaylist = video.getHlsPlaylist()
630
631       const p2pMediaLoader = {
632         playlistUrl: hlsPlaylist.playlistUrl,
633         segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
634         redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
635         trackerAnnounce: video.trackerUrls,
636         videoFiles: hlsPlaylist.files
637       } as P2PMediaLoaderOptions
638
639       Object.assign(options, { p2pMediaLoader })
640     }
641
642     return { playerMode: mode, playerOptions: options }
643   }
644
645   private pausePlayer () {
646     if (!this.player) return
647
648     this.player.pause()
649   }
650
651   private initHotkeys () {
652     this.hotkeys = [
653       // These hotkeys are managed by the player
654       new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
655       new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
656       new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
657
658       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)')),
659
660       new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
661       new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
662
663       new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
664       new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
665
666       new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
667       new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
668
669       new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
670     ]
671
672     if (this.isUserLoggedIn()) {
673       this.hotkeys = this.hotkeys.concat([
674         new Hotkey('shift+l', () => {
675           this.setLike()
676           return false
677         }, undefined, this.i18n('Like the video')),
678
679         new Hotkey('shift+d', () => {
680           this.setDislike()
681           return false
682         }, undefined, this.i18n('Dislike the video')),
683
684         new Hotkey('shift+s', () => {
685           this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
686           return false
687         }, undefined, this.i18n('Subscribe to the account'))
688       ])
689     }
690
691     this.hotkeysService.add(this.hotkeys)
692   }
693 }