Add video miniature dropdown
[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 { Notifier, ServerService } from '@app/core'
9 import { forkJoin, Subscription } from 'rxjs'
10 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
11 import { UserVideoRateType, VideoCaption, VideoPlaylistPrivacy, 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   P2PMediaLoaderOptions,
24   PeertubePlayerManager,
25   PeertubePlayerManagerOptions,
26   PlayerMode
27 } from '../../../assets/player/peertube-player-manager'
28 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
29 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
30 import { ComponentPagination } from '@app/shared/rest/component-pagination.model'
31 import { Video } from '@app/shared/video/video.model'
32 import { VideoActionsDisplayType } from '@app/shared/video/video-actions-dropdown.component'
33
34 @Component({
35   selector: 'my-video-watch',
36   templateUrl: './video-watch.component.html',
37   styleUrls: [ './video-watch.component.scss' ]
38 })
39 export class VideoWatchComponent implements OnInit, OnDestroy {
40   private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
41
42   @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
43   @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
44   @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
45
46   player: any
47   playerElement: HTMLVideoElement
48   theaterEnabled = false
49   userRating: UserVideoRateType = null
50   video: VideoDetails = null
51   descriptionLoading = false
52
53   playlist: VideoPlaylist = null
54   playlistVideos: Video[] = []
55   playlistPagination: ComponentPagination = {
56     currentPage: 1,
57     itemsPerPage: 30,
58     totalItems: null
59   }
60   noPlaylistVideos = false
61   currentPlaylistPosition = 1
62
63   completeDescriptionShown = false
64   completeVideoDescription: string
65   shortVideoDescription: string
66   videoHTMLDescription = ''
67   likesBarTooltipText = ''
68   hasAlreadyAcceptedPrivacyConcern = false
69   remoteServerDown = false
70   hotkeys: Hotkey[]
71
72   private currentTime: number
73   private paramsSub: Subscription
74   private queryParamsSub: Subscription
75
76   constructor (
77     private elementRef: ElementRef,
78     private changeDetector: ChangeDetectorRef,
79     private route: ActivatedRoute,
80     private router: Router,
81     private videoService: VideoService,
82     private playlistService: VideoPlaylistService,
83     private videoBlacklistService: VideoBlacklistService,
84     private confirmService: ConfirmService,
85     private metaService: MetaService,
86     private authService: AuthService,
87     private serverService: ServerService,
88     private restExtractor: RestExtractor,
89     private notifier: Notifier,
90     private markdownService: MarkdownService,
91     private zone: NgZone,
92     private redirectService: RedirectService,
93     private videoCaptionService: VideoCaptionService,
94     private i18n: I18n,
95     private hotkeysService: HotkeysService,
96     @Inject(LOCALE_ID) private localeId: string
97   ) {}
98
99   get user () {
100     return this.authService.getUser()
101   }
102
103   ngOnInit () {
104     if (
105       !!((window as any).RTCPeerConnection || (window as any).mozRTCPeerConnection || (window as any).webkitRTCPeerConnection) === false ||
106       peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
107     ) {
108       this.hasAlreadyAcceptedPrivacyConcern = true
109     }
110
111     this.paramsSub = this.route.params.subscribe(routeParams => {
112       const videoId = routeParams[ 'videoId' ]
113       if (videoId) this.loadVideo(videoId)
114
115       const playlistId = routeParams[ 'playlistId' ]
116       if (playlistId) this.loadPlaylist(playlistId)
117     })
118
119     this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
120       const videoId = queryParams[ 'videoId' ]
121       if (videoId) this.loadVideo(videoId)
122     })
123
124     this.hotkeys = [
125       new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
126         this.setLike()
127         return false
128       }, undefined, this.i18n('Like the video')),
129       new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
130         this.setDislike()
131         return false
132       }, undefined, this.i18n('Dislike the video')),
133       new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
134         this.subscribeButton.subscribed ?
135           this.subscribeButton.unsubscribe() :
136           this.subscribeButton.subscribe()
137         return false
138       }, undefined, this.i18n('Subscribe to the account'))
139     ]
140     if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
141   }
142
143   ngOnDestroy () {
144     this.flushPlayer()
145
146     // Unsubscribe subscriptions
147     if (this.paramsSub) this.paramsSub.unsubscribe()
148     if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
149
150     // Unbind hotkeys
151     if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
152   }
153
154   setLike () {
155     if (this.isUserLoggedIn() === false) return
156     if (this.userRating === 'like') {
157       // Already liked this video
158       this.setRating('none')
159     } else {
160       this.setRating('like')
161     }
162   }
163
164   setDislike () {
165     if (this.isUserLoggedIn() === false) return
166     if (this.userRating === 'dislike') {
167       // Already disliked this video
168       this.setRating('none')
169     } else {
170       this.setRating('dislike')
171     }
172   }
173
174   showMoreDescription () {
175     if (this.completeVideoDescription === undefined) {
176       return this.loadCompleteDescription()
177     }
178
179     this.updateVideoDescription(this.completeVideoDescription)
180     this.completeDescriptionShown = true
181   }
182
183   showLessDescription () {
184     this.updateVideoDescription(this.shortVideoDescription)
185     this.completeDescriptionShown = false
186   }
187
188   loadCompleteDescription () {
189     this.descriptionLoading = true
190
191     this.videoService.loadCompleteDescription(this.video.descriptionPath)
192         .subscribe(
193           description => {
194             this.completeDescriptionShown = true
195             this.descriptionLoading = false
196
197             this.shortVideoDescription = this.video.description
198             this.completeVideoDescription = description
199
200             this.updateVideoDescription(this.completeVideoDescription)
201           },
202
203           error => {
204             this.descriptionLoading = false
205             this.notifier.error(error.message)
206           }
207         )
208   }
209
210   showSupportModal () {
211     this.videoSupportModal.show()
212   }
213
214   showShareModal () {
215     this.videoShareModal.show(this.currentTime)
216   }
217
218   isUserLoggedIn () {
219     return this.authService.isLoggedIn()
220   }
221
222   getVideoTags () {
223     if (!this.video || Array.isArray(this.video.tags) === false) return []
224
225     return this.video.tags
226   }
227
228   isVideoRemovable () {
229     return this.video.isRemovableBy(this.authService.getUser())
230   }
231
232   onVideoRemoved () {
233     this.redirectService.redirectToHomepage()
234   }
235
236   acceptedPrivacyConcern () {
237     peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
238     this.hasAlreadyAcceptedPrivacyConcern = true
239   }
240
241   isVideoToTranscode () {
242     return this.video && this.video.state.id === VideoState.TO_TRANSCODE
243   }
244
245   isVideoDownloadable () {
246     return this.video && this.video.downloadEnabled
247   }
248
249   isVideoToImport () {
250     return this.video && this.video.state.id === VideoState.TO_IMPORT
251   }
252
253   hasVideoScheduledPublication () {
254     return this.video && this.video.scheduledUpdate !== undefined
255   }
256
257   isVideoBlur (video: Video) {
258     return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
259   }
260
261   isPlaylistOwned () {
262     return this.playlist.isLocal === true && this.playlist.ownerAccount.name === this.user.username
263   }
264
265   isUnlistedPlaylist () {
266     return this.playlist.privacy.id === VideoPlaylistPrivacy.UNLISTED
267   }
268
269   isPrivatePlaylist () {
270     return this.playlist.privacy.id === VideoPlaylistPrivacy.PRIVATE
271   }
272
273   isPublicPlaylist () {
274     return this.playlist.privacy.id === VideoPlaylistPrivacy.PUBLIC
275   }
276
277   onPlaylistVideosNearOfBottom () {
278     // Last page
279     if (this.playlistPagination.totalItems <= (this.playlistPagination.currentPage * this.playlistPagination.itemsPerPage)) return
280
281     this.playlistPagination.currentPage += 1
282     this.loadPlaylistElements(false)
283   }
284
285   onElementRemoved (video: Video) {
286     this.playlistVideos = this.playlistVideos.filter(v => v.id !== video.id)
287
288     this.playlistPagination.totalItems--
289   }
290
291   private loadVideo (videoId: string) {
292     // Video did not change
293     if (this.video && this.video.uuid === videoId) return
294
295     if (this.player) this.player.pause()
296
297     // Video did change
298     forkJoin(
299       this.videoService.getVideo(videoId),
300       this.videoCaptionService.listCaptions(videoId)
301     )
302       .pipe(
303         // If 401, the video is private or blacklisted so redirect to 404
304         catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
305       )
306       .subscribe(([ video, captionsResult ]) => {
307         const queryParams = this.route.snapshot.queryParams
308         const startTime = queryParams.start
309         const stopTime = queryParams.stop
310         const subtitle = queryParams.subtitle
311         const playerMode = queryParams.mode
312
313         this.onVideoFetched(video, captionsResult.data, { startTime, stopTime, subtitle, playerMode })
314             .catch(err => this.handleError(err))
315       })
316   }
317
318   private loadPlaylist (playlistId: string) {
319     // Playlist did not change
320     if (this.playlist && this.playlist.uuid === playlistId) return
321
322     this.playlistService.getVideoPlaylist(playlistId)
323       .pipe(
324         // If 401, the video is private or blacklisted so redirect to 404
325         catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
326       )
327       .subscribe(playlist => {
328         this.playlist = playlist
329
330         const videoId = this.route.snapshot.queryParams['videoId']
331         this.loadPlaylistElements(!videoId)
332       })
333   }
334
335   private loadPlaylistElements (redirectToFirst = false) {
336     this.videoService.getPlaylistVideos(this.playlist.uuid, this.playlistPagination)
337         .subscribe(({ totalVideos, videos }) => {
338           this.playlistVideos = this.playlistVideos.concat(videos)
339           this.playlistPagination.totalItems = totalVideos
340
341           if (totalVideos === 0) {
342             this.noPlaylistVideos = true
343             return
344           }
345
346           this.updatePlaylistIndex()
347
348           if (redirectToFirst) {
349             const extras = {
350               queryParams: { videoId: this.playlistVideos[ 0 ].uuid },
351               replaceUrl: true
352             }
353             this.router.navigate([], extras)
354           }
355         })
356   }
357
358   private updateVideoDescription (description: string) {
359     this.video.description = description
360     this.setVideoDescriptionHTML()
361   }
362
363   private async setVideoDescriptionHTML () {
364     this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
365   }
366
367   private setVideoLikesBarTooltipText () {
368     this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
369       likesNumber: this.video.likes,
370       dislikesNumber: this.video.dislikes
371     })
372   }
373
374   private handleError (err: any) {
375     const errorMessage: string = typeof err === 'string' ? err : err.message
376     if (!errorMessage) return
377
378     // Display a message in the video player instead of a notification
379     if (errorMessage.indexOf('from xs param') !== -1) {
380       this.flushPlayer()
381       this.remoteServerDown = true
382       this.changeDetector.detectChanges()
383
384       return
385     }
386
387     this.notifier.error(errorMessage)
388   }
389
390   private checkUserRating () {
391     // Unlogged users do not have ratings
392     if (this.isUserLoggedIn() === false) return
393
394     this.videoService.getUserVideoRating(this.video.id)
395         .subscribe(
396           ratingObject => {
397             if (ratingObject) {
398               this.userRating = ratingObject.rating
399             }
400           },
401
402           err => this.notifier.error(err.message)
403         )
404   }
405
406   private async onVideoFetched (
407     video: VideoDetails,
408     videoCaptions: VideoCaption[],
409     urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
410   ) {
411     this.video = video
412
413     // Re init attributes
414     this.descriptionLoading = false
415     this.completeDescriptionShown = false
416     this.remoteServerDown = false
417     this.currentTime = undefined
418
419     this.updatePlaylistIndex()
420
421     let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
422     // If we are at the end of the video, reset the timer
423     if (this.video.duration - startTime <= 1) startTime = 0
424
425     if (this.isVideoBlur(this.video)) {
426       const res = await this.confirmService.confirm(
427         this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
428         this.i18n('Mature or explicit content')
429       )
430       if (res === false) return this.redirectService.redirectToHomepage()
431     }
432
433     // Flush old player if needed
434     this.flushPlayer()
435
436     // Build video element, because videojs remove it on dispose
437     const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
438     this.playerElement = document.createElement('video')
439     this.playerElement.className = 'video-js vjs-peertube-skin'
440     this.playerElement.setAttribute('playsinline', 'true')
441     playerElementWrapper.appendChild(this.playerElement)
442
443     const playerCaptions = videoCaptions.map(c => ({
444       label: c.language.label,
445       language: c.language.id,
446       src: environment.apiUrl + c.captionPath
447     }))
448
449     const options: PeertubePlayerManagerOptions = {
450       common: {
451         autoplay: this.isAutoplay(),
452
453         playerElement: this.playerElement,
454         onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
455
456         videoDuration: this.video.duration,
457         enableHotkeys: true,
458         inactivityTimeout: 2500,
459         poster: this.video.previewUrl,
460         startTime,
461         stopTime: urlOptions.stopTime,
462
463         theaterMode: true,
464         captions: videoCaptions.length !== 0,
465         peertubeLink: false,
466
467         videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
468         embedUrl: this.video.embedUrl,
469
470         language: this.localeId,
471
472         subtitle: urlOptions.subtitle,
473
474         userWatching: this.user && this.user.videosHistoryEnabled === true ? {
475           url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
476           authorizationHeader: this.authService.getRequestHeaderValue()
477         } : undefined,
478
479         serverUrl: environment.apiUrl,
480
481         videoCaptions: playerCaptions
482       },
483
484       webtorrent: {
485         videoFiles: this.video.files
486       }
487     }
488
489     const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
490
491     if (mode === 'p2p-media-loader') {
492       const hlsPlaylist = this.video.getHlsPlaylist()
493
494       const p2pMediaLoader = {
495         playlistUrl: hlsPlaylist.playlistUrl,
496         segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
497         redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
498         trackerAnnounce: this.video.trackerUrls,
499         videoFiles: this.video.files
500       } as P2PMediaLoaderOptions
501
502       Object.assign(options, { p2pMediaLoader })
503     }
504
505     this.zone.runOutsideAngular(async () => {
506       this.player = await PeertubePlayerManager.initialize(mode, options)
507       this.theaterEnabled = this.player.theaterEnabled
508
509       this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
510
511       this.player.on('timeupdate', () => {
512         this.currentTime = Math.floor(this.player.currentTime())
513       })
514
515       this.player.one('ended', () => {
516         if (this.playlist) {
517           this.zone.run(() => this.navigateToNextPlaylistVideo())
518         }
519       })
520
521       this.player.one('stopped', () => {
522         if (this.playlist) {
523           this.zone.run(() => this.navigateToNextPlaylistVideo())
524         }
525       })
526
527       this.player.on('theaterChange', (_: any, enabled: boolean) => {
528         this.zone.run(() => this.theaterEnabled = enabled)
529       })
530     })
531
532     this.setVideoDescriptionHTML()
533     this.setVideoLikesBarTooltipText()
534
535     this.setOpenGraphTags()
536     this.checkUserRating()
537   }
538
539   private setRating (nextRating: UserVideoRateType) {
540     let method
541     switch (nextRating) {
542       case 'like':
543         method = this.videoService.setVideoLike
544         break
545       case 'dislike':
546         method = this.videoService.setVideoDislike
547         break
548       case 'none':
549         method = this.videoService.unsetVideoLike
550         break
551     }
552
553     method.call(this.videoService, this.video.id)
554           .subscribe(
555             () => {
556               // Update the video like attribute
557               this.updateVideoRating(this.userRating, nextRating)
558               this.userRating = nextRating
559             },
560
561             (err: { message: string }) => this.notifier.error(err.message)
562           )
563   }
564
565   private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
566     let likesToIncrement = 0
567     let dislikesToIncrement = 0
568
569     if (oldRating) {
570       if (oldRating === 'like') likesToIncrement--
571       if (oldRating === 'dislike') dislikesToIncrement--
572     }
573
574     if (newRating === 'like') likesToIncrement++
575     if (newRating === 'dislike') dislikesToIncrement++
576
577     this.video.likes += likesToIncrement
578     this.video.dislikes += dislikesToIncrement
579
580     this.video.buildLikeAndDislikePercents()
581     this.setVideoLikesBarTooltipText()
582   }
583
584   private updatePlaylistIndex () {
585     if (this.playlistVideos.length === 0 || !this.video) return
586
587     for (const video of this.playlistVideos) {
588       if (video.id === this.video.id) {
589         this.currentPlaylistPosition = video.playlistElement.position
590         return
591       }
592     }
593
594     // Load more videos to find our video
595     this.onPlaylistVideosNearOfBottom()
596   }
597
598   private setOpenGraphTags () {
599     this.metaService.setTitle(this.video.name)
600
601     this.metaService.setTag('og:type', 'video')
602
603     this.metaService.setTag('og:title', this.video.name)
604     this.metaService.setTag('name', this.video.name)
605
606     this.metaService.setTag('og:description', this.video.description)
607     this.metaService.setTag('description', this.video.description)
608
609     this.metaService.setTag('og:image', this.video.previewPath)
610
611     this.metaService.setTag('og:duration', this.video.duration.toString())
612
613     this.metaService.setTag('og:site_name', 'PeerTube')
614
615     this.metaService.setTag('og:url', window.location.href)
616     this.metaService.setTag('url', window.location.href)
617   }
618
619   private isAutoplay () {
620     // We'll jump to the thread id, so do not play the video
621     if (this.route.snapshot.params['threadId']) return false
622
623     // Otherwise true by default
624     if (!this.user) return true
625
626     // Be sure the autoPlay is set to false
627     return this.user.autoPlayVideo !== false
628   }
629
630   private flushPlayer () {
631     // Remove player if it exists
632     if (this.player) {
633       this.player.dispose()
634       this.player = undefined
635     }
636   }
637
638   private navigateToNextPlaylistVideo () {
639     if (this.currentPlaylistPosition < this.playlistPagination.totalItems) {
640       const next = this.playlistVideos.find(v => v.playlistElement.position === this.currentPlaylistPosition + 1)
641
642       const start = next.playlistElement.startTimestamp
643       const stop = next.playlistElement.stopTimestamp
644       this.router.navigate([],{ queryParams: { videoId: next.uuid, start, stop } })
645     }
646   }
647 }