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