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