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