51e48427501e1510a8676dda93d19345777b6eae
[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-web-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 { ServerConfig, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
12 import { AuthService, ConfirmService } from '../../core'
13 import { RestExtractor, UserService } 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 { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
36 import { HooksService } from '@app/core/plugins/hooks.service'
37 import { PlatformLocation } from '@angular/common'
38 import { scrollToTop, isXPercentInViewport } from '@app/shared/misc/utils'
39
40 @Component({
41   selector: 'my-video-watch',
42   templateUrl: './video-watch.component.html',
43   styleUrls: [ './video-watch.component.scss' ]
44 })
45 export class VideoWatchComponent implements OnInit, OnDestroy {
46   private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
47
48   @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
49   @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
50   @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
51   @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
52
53   player: any
54   playerElement: HTMLVideoElement
55   theaterEnabled = false
56   userRating: UserVideoRateType = null
57   descriptionLoading = false
58
59   video: VideoDetails = null
60   videoCaptions: VideoCaption[] = []
61
62   playlist: VideoPlaylist = null
63
64   completeDescriptionShown = false
65   completeVideoDescription: string
66   shortVideoDescription: string
67   videoHTMLDescription = ''
68   likesBarTooltipText = ''
69   hasAlreadyAcceptedPrivacyConcern = false
70   remoteServerDown = false
71   hotkeys: Hotkey[] = []
72
73   tooltipLike = ''
74   tooltipDislike = ''
75   tooltipSupport = ''
76   tooltipSaveToPlaylist = ''
77
78   private nextVideoUuid = ''
79   private nextVideoTitle = ''
80   private currentTime: number
81   private paramsSub: Subscription
82   private queryParamsSub: Subscription
83   private configSub: Subscription
84
85   private serverConfig: ServerConfig
86
87   constructor (
88     private elementRef: ElementRef,
89     private changeDetector: ChangeDetectorRef,
90     private route: ActivatedRoute,
91     private router: Router,
92     private videoService: VideoService,
93     private playlistService: VideoPlaylistService,
94     private confirmService: ConfirmService,
95     private metaService: MetaService,
96     private authService: AuthService,
97     private userService: UserService,
98     private serverService: ServerService,
99     private restExtractor: RestExtractor,
100     private notifier: Notifier,
101     private markdownService: MarkdownService,
102     private zone: NgZone,
103     private redirectService: RedirectService,
104     private videoCaptionService: VideoCaptionService,
105     private i18n: I18n,
106     private hotkeysService: HotkeysService,
107     private hooks: HooksService,
108     private location: PlatformLocation,
109     @Inject(LOCALE_ID) private localeId: string
110   ) {
111     this.tooltipLike = this.i18n('Like this video')
112     this.tooltipDislike = this.i18n('Dislike this video')
113     this.tooltipSupport = this.i18n('Support options for this video')
114     this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
115   }
116
117   get user () {
118     return this.authService.getUser()
119   }
120
121   get anonymousUser () {
122     return this.userService.getAnonymousUser()
123   }
124
125   async ngOnInit () {
126     this.serverConfig = this.serverService.getTmpConfig()
127
128     this.configSub = this.serverService.getConfig()
129         .subscribe(config => {
130           this.serverConfig = config
131
132           if (
133             isWebRTCDisabled() ||
134             this.serverConfig.tracker.enabled === false ||
135             getStoredP2PEnabled() === false ||
136             peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
137           ) {
138             this.hasAlreadyAcceptedPrivacyConcern = true
139           }
140         })
141
142     this.paramsSub = this.route.params.subscribe(routeParams => {
143       const videoId = routeParams[ 'videoId' ]
144       if (videoId) this.loadVideo(videoId)
145
146       const playlistId = routeParams[ 'playlistId' ]
147       if (playlistId) this.loadPlaylist(playlistId)
148     })
149
150     this.queryParamsSub = this.route.queryParams.subscribe(async queryParams => {
151       const videoId = queryParams[ 'videoId' ]
152       if (videoId) this.loadVideo(videoId)
153
154       const start = queryParams[ 'start' ]
155       if (this.player && start) this.player.currentTime(parseInt(start, 10))
156     })
157
158     this.initHotkeys()
159
160     this.theaterEnabled = getStoredTheater()
161
162     this.hooks.runAction('action:video-watch.init', 'video-watch')
163   }
164
165   ngOnDestroy () {
166     this.flushPlayer()
167
168     // Unsubscribe subscriptions
169     if (this.paramsSub) this.paramsSub.unsubscribe()
170     if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
171
172     // Unbind hotkeys
173     this.hotkeysService.remove(this.hotkeys)
174   }
175
176   setLike () {
177     if (this.isUserLoggedIn() === false) return
178
179     // Already liked this video
180     if (this.userRating === 'like') this.setRating('none')
181     else this.setRating('like')
182   }
183
184   setDislike () {
185     if (this.isUserLoggedIn() === false) return
186
187     // Already disliked this video
188     if (this.userRating === 'dislike') this.setRating('none')
189     else this.setRating('dislike')
190   }
191
192   getRatePopoverText () {
193     if (this.isUserLoggedIn()) return undefined
194
195     return this.i18n('You need to be connected to rate this content.')
196   }
197
198   showMoreDescription () {
199     if (this.completeVideoDescription === undefined) {
200       return this.loadCompleteDescription()
201     }
202
203     this.updateVideoDescription(this.completeVideoDescription)
204     this.completeDescriptionShown = true
205   }
206
207   showLessDescription () {
208     this.updateVideoDescription(this.shortVideoDescription)
209     this.completeDescriptionShown = false
210   }
211
212   loadCompleteDescription () {
213     this.descriptionLoading = true
214
215     this.videoService.loadCompleteDescription(this.video.descriptionPath)
216         .subscribe(
217           description => {
218             this.completeDescriptionShown = true
219             this.descriptionLoading = false
220
221             this.shortVideoDescription = this.video.description
222             this.completeVideoDescription = description
223
224             this.updateVideoDescription(this.completeVideoDescription)
225           },
226
227           error => {
228             this.descriptionLoading = false
229             this.notifier.error(error.message)
230           }
231         )
232   }
233
234   showSupportModal () {
235     this.pausePlayer()
236
237     this.videoSupportModal.show()
238   }
239
240   showShareModal () {
241     this.pausePlayer()
242
243     this.videoShareModal.show(this.currentTime)
244   }
245
246   isUserLoggedIn () {
247     return this.authService.isLoggedIn()
248   }
249
250   getVideoTags () {
251     if (!this.video || Array.isArray(this.video.tags) === false) return []
252
253     return this.video.tags
254   }
255
256   onRecommendations (videos: Video[]) {
257     if (videos.length > 0) {
258       // The recommended videos's first element should be the next video
259       const video = videos[0]
260       this.nextVideoUuid = video.uuid
261       this.nextVideoTitle = video.name
262     }
263   }
264
265   onModalOpened () {
266     this.pausePlayer()
267   }
268
269   onVideoRemoved () {
270     this.redirectService.redirectToHomepage()
271   }
272
273   declinedPrivacyConcern () {
274     peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
275     this.hasAlreadyAcceptedPrivacyConcern = false
276   }
277
278   acceptedPrivacyConcern () {
279     peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
280     this.hasAlreadyAcceptedPrivacyConcern = true
281   }
282
283   isVideoToTranscode () {
284     return this.video && this.video.state.id === VideoState.TO_TRANSCODE
285   }
286
287   isVideoToImport () {
288     return this.video && this.video.state.id === VideoState.TO_IMPORT
289   }
290
291   hasVideoScheduledPublication () {
292     return this.video && this.video.scheduledUpdate !== undefined
293   }
294
295   isVideoBlur (video: Video) {
296     return video.isVideoNSFWForUser(this.user, this.serverConfig)
297   }
298
299   isAutoPlayEnabled () {
300     return (
301       (this.user && this.user.autoPlayNextVideo) ||
302       this.anonymousUser.autoPlayNextVideo
303     )
304   }
305
306   handleTimestampClicked (timestamp: number) {
307     if (this.player) this.player.currentTime(timestamp)
308     scrollToTop()
309   }
310
311   isPlaylistAutoPlayEnabled () {
312     return (
313       (this.user && this.user.autoPlayNextVideoPlaylist) ||
314       this.anonymousUser.autoPlayNextVideoPlaylist
315     )
316   }
317
318   private loadVideo (videoId: string) {
319     // Video did not change
320     if (this.video && this.video.uuid === videoId) return
321
322     if (this.player) this.player.pause()
323
324     const videoObs = this.hooks.wrapObsFun(
325       this.videoService.getVideo.bind(this.videoService),
326       { videoId },
327       'video-watch',
328       'filter:api.video-watch.video.get.params',
329       'filter:api.video-watch.video.get.result'
330     )
331
332     // Video did change
333     forkJoin([
334       videoObs,
335       this.videoCaptionService.listCaptions(videoId)
336     ])
337       .pipe(
338         // If 401, the video is private or blacklisted so redirect to 404
339         catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
340       )
341       .subscribe(([ video, captionsResult ]) => {
342         const queryParams = this.route.snapshot.queryParams
343
344         const urlOptions = {
345           startTime: queryParams.start,
346           stopTime: queryParams.stop,
347
348           muted: queryParams.muted,
349           loop: queryParams.loop,
350           subtitle: queryParams.subtitle,
351
352           playerMode: queryParams.mode,
353           peertubeLink: false
354         }
355
356         this.onVideoFetched(video, captionsResult.data, urlOptions)
357             .catch(err => this.handleError(err))
358       })
359   }
360
361   private loadPlaylist (playlistId: string) {
362     // Playlist did not change
363     if (this.playlist && this.playlist.uuid === playlistId) return
364
365     this.playlistService.getVideoPlaylist(playlistId)
366       .pipe(
367         // If 401, the video is private or blacklisted so redirect to 404
368         catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
369       )
370       .subscribe(playlist => {
371         this.playlist = playlist
372
373         const videoId = this.route.snapshot.queryParams['videoId']
374         this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
375       })
376   }
377
378   private updateVideoDescription (description: string) {
379     this.video.description = description
380     this.setVideoDescriptionHTML()
381       .catch(err => console.error(err))
382   }
383
384   private async setVideoDescriptionHTML () {
385     const html = await this.markdownService.textMarkdownToHTML(this.video.description)
386     this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
387   }
388
389   private setVideoLikesBarTooltipText () {
390     this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
391       likesNumber: this.video.likes,
392       dislikesNumber: this.video.dislikes
393     })
394   }
395
396   private handleError (err: any) {
397     const errorMessage: string = typeof err === 'string' ? err : err.message
398     if (!errorMessage) return
399
400     // Display a message in the video player instead of a notification
401     if (errorMessage.indexOf('from xs param') !== -1) {
402       this.flushPlayer()
403       this.remoteServerDown = true
404       this.changeDetector.detectChanges()
405
406       return
407     }
408
409     this.notifier.error(errorMessage)
410   }
411
412   private checkUserRating () {
413     // Unlogged users do not have ratings
414     if (this.isUserLoggedIn() === false) return
415
416     this.videoService.getUserVideoRating(this.video.id)
417         .subscribe(
418           ratingObject => {
419             if (ratingObject) {
420               this.userRating = ratingObject.rating
421             }
422           },
423
424           err => this.notifier.error(err.message)
425         )
426   }
427
428   private async onVideoFetched (
429     video: VideoDetails,
430     videoCaptions: VideoCaption[],
431     urlOptions: CustomizationOptions & { playerMode: PlayerMode }
432   ) {
433     this.video = video
434     this.videoCaptions = videoCaptions
435
436     // Re init attributes
437     this.descriptionLoading = false
438     this.completeDescriptionShown = false
439     this.remoteServerDown = false
440     this.currentTime = undefined
441
442     this.videoWatchPlaylist.updatePlaylistIndex(video)
443
444     if (this.isVideoBlur(this.video)) {
445       const res = await this.confirmService.confirm(
446         this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
447         this.i18n('Mature or explicit content')
448       )
449       if (res === false) return this.location.back()
450     }
451
452     // Flush old player if needed
453     this.flushPlayer()
454
455     // Build video element, because videojs removes it on dispose
456     const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
457     this.playerElement = document.createElement('video')
458     this.playerElement.className = 'video-js vjs-peertube-skin'
459     this.playerElement.setAttribute('playsinline', 'true')
460     playerElementWrapper.appendChild(this.playerElement)
461
462     const params = {
463       video: this.video,
464       videoCaptions,
465       urlOptions,
466       user: this.user
467     }
468     const { playerMode, playerOptions } = await this.hooks.wrapFun(
469       this.buildPlayerManagerOptions.bind(this),
470       params,
471       'video-watch',
472       'filter:internal.video-watch.player.build-options.params',
473       'filter:internal.video-watch.player.build-options.result'
474     )
475
476     this.zone.runOutsideAngular(async () => {
477       this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
478       this.player.focus()
479
480       this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
481
482       this.player.on('timeupdate', () => {
483         this.currentTime = Math.floor(this.player.currentTime())
484       })
485
486       /**
487        * replaces this.player.one('ended')
488        * 'condition()': true to make the upnext functionality trigger,
489        *                false to disable the upnext functionality
490        * go to the next video in 'condition()' if you don't want of the timer.
491        * 'next': function triggered at the end of the timer.
492        * 'suspended': function used at each clic of the timer checking if we need
493        * to reset progress and wait until 'suspended' becomes truthy again.
494        */
495       this.player.upnext({
496         timeout: 10000, // 10s
497         headText: this.i18n('Up Next'),
498         cancelText: this.i18n('Cancel'),
499         suspendedText: this.i18n('Autoplay is suspended'),
500         getTitle: () => this.nextVideoTitle,
501         next: () => this.zone.run(() => this.autoplayNext()),
502         condition: () => {
503           if (this.playlist) {
504             if (this.isPlaylistAutoPlayEnabled()) {
505               // upnext will not trigger, and instead the next video will play immediately
506               this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
507             }
508           } else if (this.isAutoPlayEnabled()) {
509             return true // upnext will trigger
510           }
511           return false // upnext will not trigger, and instead leave the video stopping
512         },
513         suspended: () => {
514           return (
515             !isXPercentInViewport(this.player.el(), 80) ||
516             !document.getElementById('content').contains(document.activeElement)
517           )
518         }
519       })
520
521       this.player.one('stopped', () => {
522         if (this.playlist) {
523           if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
524         }
525       })
526
527       this.player.on('theaterChange', (_: any, enabled: boolean) => {
528         this.zone.run(() => this.theaterEnabled = enabled)
529       })
530
531       this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
532     })
533
534     this.setVideoDescriptionHTML()
535     this.setVideoLikesBarTooltipText()
536
537     this.setOpenGraphTags()
538     this.checkUserRating()
539
540     this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
541   }
542
543   private autoplayNext () {
544     if (this.playlist) {
545       this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
546     } else if (this.nextVideoUuid) {
547       this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
548     }
549   }
550
551   private setRating (nextRating: UserVideoRateType) {
552     const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
553       like: this.videoService.setVideoLike,
554       dislike: this.videoService.setVideoDislike,
555       none: this.videoService.unsetVideoLike
556     }
557
558     ratingMethods[nextRating].call(this.videoService, this.video.id)
559           .subscribe(
560             () => {
561               // Update the video like attribute
562               this.updateVideoRating(this.userRating, nextRating)
563               this.userRating = nextRating
564             },
565
566             (err: { message: string }) => this.notifier.error(err.message)
567           )
568   }
569
570   private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
571     let likesToIncrement = 0
572     let dislikesToIncrement = 0
573
574     if (oldRating) {
575       if (oldRating === 'like') likesToIncrement--
576       if (oldRating === 'dislike') dislikesToIncrement--
577     }
578
579     if (newRating === 'like') likesToIncrement++
580     if (newRating === 'dislike') dislikesToIncrement++
581
582     this.video.likes += likesToIncrement
583     this.video.dislikes += dislikesToIncrement
584
585     this.video.buildLikeAndDislikePercents()
586     this.setVideoLikesBarTooltipText()
587   }
588
589   private setOpenGraphTags () {
590     this.metaService.setTitle(this.video.name)
591
592     this.metaService.setTag('og:type', 'video')
593
594     this.metaService.setTag('og:title', this.video.name)
595     this.metaService.setTag('name', this.video.name)
596
597     this.metaService.setTag('og:description', this.video.description)
598     this.metaService.setTag('description', this.video.description)
599
600     this.metaService.setTag('og:image', this.video.previewPath)
601
602     this.metaService.setTag('og:duration', this.video.duration.toString())
603
604     this.metaService.setTag('og:site_name', 'PeerTube')
605
606     this.metaService.setTag('og:url', window.location.href)
607     this.metaService.setTag('url', window.location.href)
608   }
609
610   private isAutoplay () {
611     // We'll jump to the thread id, so do not play the video
612     if (this.route.snapshot.params['threadId']) return false
613
614     // Otherwise true by default
615     if (!this.user) return true
616
617     // Be sure the autoPlay is set to false
618     return this.user.autoPlayVideo !== false
619   }
620
621   private flushPlayer () {
622     // Remove player if it exists
623     if (this.player) {
624       try {
625         this.player.dispose()
626         this.player = undefined
627       } catch (err) {
628         console.error('Cannot dispose player.', err)
629       }
630     }
631   }
632
633   private buildPlayerManagerOptions (params: {
634     video: VideoDetails,
635     videoCaptions: VideoCaption[],
636     urlOptions: CustomizationOptions & { playerMode: PlayerMode },
637     user?: AuthUser
638   }) {
639     const { video, videoCaptions, urlOptions, user } = params
640     const getStartTime = () => {
641       const byUrl = urlOptions.startTime !== undefined
642       const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
643
644       if (byUrl) {
645         return timeToInt(urlOptions.startTime)
646       } else if (byHistory) {
647         return video.userHistory.currentTime
648       } else {
649         return 0
650       }
651     }
652
653     let startTime = getStartTime()
654     // If we are at the end of the video, reset the timer
655     if (video.duration - startTime <= 1) startTime = 0
656
657     const playerCaptions = videoCaptions.map(c => ({
658       label: c.language.label,
659       language: c.language.id,
660       src: environment.apiUrl + c.captionPath
661     }))
662
663     const options: PeertubePlayerManagerOptions = {
664       common: {
665         autoplay: this.isAutoplay(),
666         nextVideo: () => this.zone.run(() => this.autoplayNext()),
667
668         playerElement: this.playerElement,
669         onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
670
671         videoDuration: video.duration,
672         enableHotkeys: true,
673         inactivityTimeout: 2500,
674         poster: video.previewUrl,
675
676         startTime,
677         stopTime: urlOptions.stopTime,
678         controls: urlOptions.controls,
679         muted: urlOptions.muted,
680         loop: urlOptions.loop,
681         subtitle: urlOptions.subtitle,
682
683         peertubeLink: urlOptions.peertubeLink,
684
685         theaterButton: true,
686         captions: videoCaptions.length !== 0,
687
688         videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
689           ? this.videoService.getVideoViewUrl(video.uuid)
690           : null,
691         embedUrl: video.embedUrl,
692
693         language: this.localeId,
694
695         userWatching: user && user.videosHistoryEnabled === true ? {
696           url: this.videoService.getUserWatchingVideoUrl(video.uuid),
697           authorizationHeader: this.authService.getRequestHeaderValue()
698         } : undefined,
699
700         serverUrl: environment.apiUrl,
701
702         videoCaptions: playerCaptions
703       },
704
705       webtorrent: {
706         videoFiles: video.files
707       }
708     }
709
710     let mode: PlayerMode
711
712     if (urlOptions.playerMode) {
713       if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
714       else mode = 'webtorrent'
715     } else {
716       if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
717       else mode = 'webtorrent'
718     }
719
720     if (mode === 'p2p-media-loader') {
721       const hlsPlaylist = video.getHlsPlaylist()
722
723       const p2pMediaLoader = {
724         playlistUrl: hlsPlaylist.playlistUrl,
725         segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
726         redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
727         trackerAnnounce: video.trackerUrls,
728         videoFiles: hlsPlaylist.files
729       } as P2PMediaLoaderOptions
730
731       Object.assign(options, { p2pMediaLoader })
732     }
733
734     return { playerMode: mode, playerOptions: options }
735   }
736
737   private pausePlayer () {
738     if (!this.player) return
739
740     this.player.pause()
741   }
742
743   private initHotkeys () {
744     this.hotkeys = [
745       // These hotkeys are managed by the player
746       new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
747       new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
748       new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
749
750       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)')),
751
752       new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
753       new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
754
755       new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
756       new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
757
758       new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
759       new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
760
761       new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
762     ]
763
764     if (this.isUserLoggedIn()) {
765       this.hotkeys = this.hotkeys.concat([
766         new Hotkey('shift+l', () => {
767           this.setLike()
768           return false
769         }, undefined, this.i18n('Like the video')),
770
771         new Hotkey('shift+d', () => {
772           this.setDislike()
773           return false
774         }, undefined, this.i18n('Dislike the video')),
775
776         new Hotkey('shift+s', () => {
777           this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
778           return false
779         }, undefined, this.i18n('Subscribe to the account'))
780       ])
781     }
782
783     this.hotkeysService.add(this.hotkeys)
784   }
785 }