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