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