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