]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-watch/video-watch.component.ts
Fix fullscreen on ios
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-watch / video-watch.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, Observable, Subscription } from 'rxjs'
3 import { catchError } from 'rxjs/operators'
4 import { PlatformLocation } from '@angular/common'
5 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
6 import { ActivatedRoute, Router } from '@angular/router'
7 import { AuthService, AuthUser, ConfirmService, MarkdownService, Notifier, RestExtractor, ServerService, UserService } from '@app/core'
8 import { HooksService } from '@app/core/plugins/hooks.service'
9 import { RedirectService } from '@app/core/routing/redirect.service'
10 import { isXPercentInViewport, peertubeLocalStorage, scrollToTop } from '@app/helpers'
11 import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
12 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
13 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
14 import { MetaService } from '@ngx-meta/core'
15 import { I18n } from '@ngx-translate/i18n-polyfill'
16 import { ServerConfig, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
17 import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
18 import {
19 CustomizationOptions,
20 P2PMediaLoaderOptions,
21 PeertubePlayerManager,
22 PeertubePlayerManagerOptions,
23 PlayerMode,
24 videojs
25 } from '../../../assets/player/peertube-player-manager'
26 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
27 import { environment } from '../../../environments/environment'
28 import { VideoShareComponent } from './modal/video-share.component'
29 import { VideoSupportComponent } from './modal/video-support.component'
30 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
31
32 @Component({
33 selector: 'my-video-watch',
34 templateUrl: './video-watch.component.html',
35 styleUrls: [ './video-watch.component.scss' ]
36 })
37 export class VideoWatchComponent implements OnInit, OnDestroy {
38 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
39
40 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
41 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
42 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
43 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
44
45 player: any
46 playerElement: HTMLVideoElement
47 theaterEnabled = false
48 userRating: UserVideoRateType = null
49 descriptionLoading = false
50
51 video: VideoDetails = null
52 videoCaptions: VideoCaption[] = []
53
54 playlist: VideoPlaylist = null
55
56 completeDescriptionShown = false
57 completeVideoDescription: string
58 shortVideoDescription: string
59 videoHTMLDescription = ''
60 likesBarTooltipText = ''
61 hasAlreadyAcceptedPrivacyConcern = false
62 remoteServerDown = false
63 hotkeys: Hotkey[] = []
64
65 tooltipLike = ''
66 tooltipDislike = ''
67 tooltipSupport = ''
68 tooltipSaveToPlaylist = ''
69
70 private nextVideoUuid = ''
71 private nextVideoTitle = ''
72 private currentTime: number
73 private paramsSub: Subscription
74 private queryParamsSub: Subscription
75 private configSub: Subscription
76
77 private serverConfig: ServerConfig
78
79 constructor (
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 confirmService: ConfirmService,
87 private metaService: MetaService,
88 private authService: AuthService,
89 private userService: UserService,
90 private serverService: ServerService,
91 private restExtractor: RestExtractor,
92 private notifier: Notifier,
93 private markdownService: MarkdownService,
94 private zone: NgZone,
95 private redirectService: RedirectService,
96 private videoCaptionService: VideoCaptionService,
97 private i18n: I18n,
98 private hotkeysService: HotkeysService,
99 private hooks: HooksService,
100 private location: PlatformLocation,
101 @Inject(LOCALE_ID) private localeId: string
102 ) {
103 this.tooltipLike = this.i18n('Like this video')
104 this.tooltipDislike = this.i18n('Dislike this video')
105 this.tooltipSupport = this.i18n('Support options for this video')
106 this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
107 }
108
109 get user () {
110 return this.authService.getUser()
111 }
112
113 get anonymousUser () {
114 return this.userService.getAnonymousUser()
115 }
116
117 async ngOnInit () {
118 this.serverConfig = this.serverService.getTmpConfig()
119
120 this.configSub = this.serverService.getConfig()
121 .subscribe(config => {
122 this.serverConfig = config
123
124 if (
125 isWebRTCDisabled() ||
126 this.serverConfig.tracker.enabled === false ||
127 getStoredP2PEnabled() === false ||
128 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
129 ) {
130 this.hasAlreadyAcceptedPrivacyConcern = true
131 }
132 })
133
134 this.paramsSub = this.route.params.subscribe(routeParams => {
135 const videoId = routeParams[ 'videoId' ]
136 if (videoId) this.loadVideo(videoId)
137
138 const playlistId = routeParams[ 'playlistId' ]
139 if (playlistId) this.loadPlaylist(playlistId)
140 })
141
142 this.queryParamsSub = this.route.queryParams.subscribe(async queryParams => {
143 const videoId = queryParams[ 'videoId' ]
144 if (videoId) this.loadVideo(videoId)
145
146 const start = queryParams[ 'start' ]
147 if (this.player && start) this.player.currentTime(parseInt(start, 10))
148 })
149
150 this.initHotkeys()
151
152 this.theaterEnabled = getStoredTheater()
153
154 this.hooks.runAction('action:video-watch.init', 'video-watch')
155 }
156
157 ngOnDestroy () {
158 this.flushPlayer()
159
160 // Unsubscribe subscriptions
161 if (this.paramsSub) this.paramsSub.unsubscribe()
162 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
163
164 // Unbind hotkeys
165 this.hotkeysService.remove(this.hotkeys)
166 }
167
168 setLike () {
169 if (this.isUserLoggedIn() === false) return
170
171 // Already liked this video
172 if (this.userRating === 'like') this.setRating('none')
173 else this.setRating('like')
174 }
175
176 setDislike () {
177 if (this.isUserLoggedIn() === false) return
178
179 // Already disliked this video
180 if (this.userRating === 'dislike') this.setRating('none')
181 else this.setRating('dislike')
182 }
183
184 getRatePopoverText () {
185 if (this.isUserLoggedIn()) return undefined
186
187 return this.i18n('You need to be connected to rate this content.')
188 }
189
190 showMoreDescription () {
191 if (this.completeVideoDescription === undefined) {
192 return this.loadCompleteDescription()
193 }
194
195 this.updateVideoDescription(this.completeVideoDescription)
196 this.completeDescriptionShown = true
197 }
198
199 showLessDescription () {
200 this.updateVideoDescription(this.shortVideoDescription)
201 this.completeDescriptionShown = false
202 }
203
204 loadCompleteDescription () {
205 this.descriptionLoading = true
206
207 this.videoService.loadCompleteDescription(this.video.descriptionPath)
208 .subscribe(
209 description => {
210 this.completeDescriptionShown = true
211 this.descriptionLoading = false
212
213 this.shortVideoDescription = this.video.description
214 this.completeVideoDescription = description
215
216 this.updateVideoDescription(this.completeVideoDescription)
217 },
218
219 error => {
220 this.descriptionLoading = false
221 this.notifier.error(error.message)
222 }
223 )
224 }
225
226 showSupportModal () {
227 this.pausePlayer()
228
229 this.videoSupportModal.show()
230 }
231
232 showShareModal () {
233 this.pausePlayer()
234
235 this.videoShareModal.show(this.currentTime)
236 }
237
238 isUserLoggedIn () {
239 return this.authService.isLoggedIn()
240 }
241
242 getVideoTags () {
243 if (!this.video || Array.isArray(this.video.tags) === false) return []
244
245 return this.video.tags
246 }
247
248 onRecommendations (videos: Video[]) {
249 if (videos.length > 0) {
250 // The recommended videos's first element should be the next video
251 const video = videos[0]
252 this.nextVideoUuid = video.uuid
253 this.nextVideoTitle = video.name
254 }
255 }
256
257 onModalOpened () {
258 this.pausePlayer()
259 }
260
261 onVideoRemoved () {
262 this.redirectService.redirectToHomepage()
263 }
264
265 declinedPrivacyConcern () {
266 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
267 this.hasAlreadyAcceptedPrivacyConcern = false
268 }
269
270 acceptedPrivacyConcern () {
271 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
272 this.hasAlreadyAcceptedPrivacyConcern = true
273 }
274
275 isVideoToTranscode () {
276 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
277 }
278
279 isVideoToImport () {
280 return this.video && this.video.state.id === VideoState.TO_IMPORT
281 }
282
283 hasVideoScheduledPublication () {
284 return this.video && this.video.scheduledUpdate !== undefined
285 }
286
287 isVideoBlur (video: Video) {
288 return video.isVideoNSFWForUser(this.user, this.serverConfig)
289 }
290
291 isAutoPlayEnabled () {
292 return (
293 (this.user && this.user.autoPlayNextVideo) ||
294 this.anonymousUser.autoPlayNextVideo
295 )
296 }
297
298 handleTimestampClicked (timestamp: number) {
299 if (this.player) this.player.currentTime(timestamp)
300 scrollToTop()
301 }
302
303 isPlaylistAutoPlayEnabled () {
304 return (
305 (this.user && this.user.autoPlayNextVideoPlaylist) ||
306 this.anonymousUser.autoPlayNextVideoPlaylist
307 )
308 }
309
310 isChannelDisplayNameGeneric () {
311 const genericChannelDisplayName = [
312 `Main ${this.video.channel.ownerAccount.name} channel`,
313 `Default ${this.video.channel.ownerAccount.name} channel`
314 ]
315
316 return genericChannelDisplayName.includes(this.video.channel.displayName)
317 }
318
319 private loadVideo (videoId: string) {
320 // Video did not change
321 if (this.video && this.video.uuid === videoId) return
322
323 if (this.player) this.player.pause()
324
325 const videoObs = this.hooks.wrapObsFun(
326 this.videoService.getVideo.bind(this.videoService),
327 { videoId },
328 'video-watch',
329 'filter:api.video-watch.video.get.params',
330 'filter:api.video-watch.video.get.result'
331 )
332
333 // Video did change
334 forkJoin([
335 videoObs,
336 this.videoCaptionService.listCaptions(videoId)
337 ])
338 .pipe(
339 // If 401, the video is private or blocked so redirect to 404
340 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
341 )
342 .subscribe(([ video, captionsResult ]) => {
343 const queryParams = this.route.snapshot.queryParams
344
345 const urlOptions = {
346 startTime: queryParams.start,
347 stopTime: queryParams.stop,
348
349 muted: queryParams.muted,
350 loop: queryParams.loop,
351 subtitle: queryParams.subtitle,
352
353 playerMode: queryParams.mode,
354 peertubeLink: false
355 }
356
357 this.onVideoFetched(video, captionsResult.data, urlOptions)
358 .catch(err => this.handleError(err))
359 })
360 }
361
362 private loadPlaylist (playlistId: string) {
363 // Playlist did not change
364 if (this.playlist && this.playlist.uuid === playlistId) return
365
366 this.playlistService.getVideoPlaylist(playlistId)
367 .pipe(
368 // If 401, the video is private or blocked so redirect to 404
369 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
370 )
371 .subscribe(playlist => {
372 this.playlist = playlist
373
374 const videoId = this.route.snapshot.queryParams['videoId']
375 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
376 })
377 }
378
379 private updateVideoDescription (description: string) {
380 this.video.description = description
381 this.setVideoDescriptionHTML()
382 .catch(err => console.error(err))
383 }
384
385 private async setVideoDescriptionHTML () {
386 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
387 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
388 }
389
390 private setVideoLikesBarTooltipText () {
391 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
392 likesNumber: this.video.likes,
393 dislikesNumber: this.video.dislikes
394 })
395 }
396
397 private handleError (err: any) {
398 const errorMessage: string = typeof err === 'string' ? err : err.message
399 if (!errorMessage) return
400
401 // Display a message in the video player instead of a notification
402 if (errorMessage.indexOf('from xs param') !== -1) {
403 this.flushPlayer()
404 this.remoteServerDown = true
405 this.changeDetector.detectChanges()
406
407 return
408 }
409
410 this.notifier.error(errorMessage)
411 }
412
413 private checkUserRating () {
414 // Unlogged users do not have ratings
415 if (this.isUserLoggedIn() === false) return
416
417 this.videoService.getUserVideoRating(this.video.id)
418 .subscribe(
419 ratingObject => {
420 if (ratingObject) {
421 this.userRating = ratingObject.rating
422 }
423 },
424
425 err => this.notifier.error(err.message)
426 )
427 }
428
429 private async onVideoFetched (
430 video: VideoDetails,
431 videoCaptions: VideoCaption[],
432 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
433 ) {
434 this.video = video
435 this.videoCaptions = videoCaptions
436
437 // Re init attributes
438 this.descriptionLoading = false
439 this.completeDescriptionShown = false
440 this.remoteServerDown = false
441 this.currentTime = undefined
442
443 this.videoWatchPlaylist.updatePlaylistIndex(video)
444
445 if (this.isVideoBlur(this.video)) {
446 const res = await this.confirmService.confirm(
447 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
448 this.i18n('Mature or explicit content')
449 )
450 if (res === false) return this.location.back()
451 }
452
453 // Flush old player if needed
454 this.flushPlayer()
455
456 // Build video element, because videojs removes it on dispose
457 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
458 this.playerElement = document.createElement('video')
459 this.playerElement.className = 'video-js vjs-peertube-skin'
460 this.playerElement.setAttribute('playsinline', 'true')
461 playerElementWrapper.appendChild(this.playerElement)
462
463 const params = {
464 video: this.video,
465 videoCaptions,
466 urlOptions,
467 user: this.user
468 }
469 const { playerMode, playerOptions } = await this.hooks.wrapFun(
470 this.buildPlayerManagerOptions.bind(this),
471 params,
472 'video-watch',
473 'filter:internal.video-watch.player.build-options.params',
474 'filter:internal.video-watch.player.build-options.result'
475 )
476
477 this.zone.runOutsideAngular(async () => {
478 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
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 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
721 if (typeof TextEncoder === 'undefined') {
722 mode = 'webtorrent'
723 }
724
725 if (mode === 'p2p-media-loader') {
726 const hlsPlaylist = video.getHlsPlaylist()
727
728 const p2pMediaLoader = {
729 playlistUrl: hlsPlaylist.playlistUrl,
730 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
731 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
732 trackerAnnounce: video.trackerUrls,
733 videoFiles: hlsPlaylist.files
734 } as P2PMediaLoaderOptions
735
736 Object.assign(options, { p2pMediaLoader })
737 }
738
739 return { playerMode: mode, playerOptions: options }
740 }
741
742 private pausePlayer () {
743 if (!this.player) return
744
745 this.player.pause()
746 }
747
748 private initHotkeys () {
749 this.hotkeys = [
750 // These hotkeys are managed by the player
751 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
752 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
753 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
754
755 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)')),
756
757 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
758 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
759
760 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
761 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
762
763 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
764 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
765
766 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
767 ]
768
769 if (this.isUserLoggedIn()) {
770 this.hotkeys = this.hotkeys.concat([
771 new Hotkey('shift+l', () => {
772 this.setLike()
773 return false
774 }, undefined, this.i18n('Like the video')),
775
776 new Hotkey('shift+d', () => {
777 this.setDislike()
778 return false
779 }, undefined, this.i18n('Dislike the video')),
780
781 new Hotkey('shift+s', () => {
782 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
783 return false
784 }, undefined, this.i18n('Subscribe to the account'))
785 ])
786 }
787
788 this.hotkeysService.add(this.hotkeys)
789 }
790 }