]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/+videos/+video-watch/video-watch.component.ts
Hide playback rate for lives
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-watch / video-watch.component.ts
CommitLineData
67ed6552 1import { Hotkey, HotkeysService } from 'angular2-hotkeys'
f443a746 2import { forkJoin, map, Observable, of, Subscription, switchMap } from 'rxjs'
57d65032 3import { VideoJsPlayer } from 'video.js'
67ed6552 4import { PlatformLocation } from '@angular/common'
c894a1ea 5import { Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
df98563e 6import { ActivatedRoute, Router } from '@angular/router'
a5cf76af
C
7import {
8 AuthService,
9 AuthUser,
10 ConfirmService,
0f01a8ba 11 MetaService,
a5cf76af
C
12 Notifier,
13 PeerTubeSocket,
72f611ca 14 PluginService,
a5cf76af 15 RestExtractor,
2666fd7c 16 ScreenService,
a5cf76af 17 ServerService,
a9bfa85d 18 User,
a5cf76af
C
19 UserService
20} from '@app/core'
67ed6552 21import { HooksService } from '@app/core/plugins/hooks.service'
4504f09f 22import { isXPercentInViewport, scrollToTop } from '@app/helpers'
3545e72c 23import { Video, VideoCaptionService, VideoDetails, VideoFileTokenService, VideoService } from '@app/shared/shared-main'
67ed6552 24import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
f443a746 25import { LiveVideoService } from '@app/shared/shared-video-live'
67ed6552 26import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
42b40636 27import { logger } from '@root-helpers/logger'
3545e72c 28import { isP2PEnabled, videoRequiresAuth } from '@root-helpers/video'
15a7eafb 29import { timeToInt } from '@shared/core-utils'
c0e8b12e
C
30import {
31 HTMLServerConfig,
32 HttpStatusCode,
f443a746 33 LiveVideo,
c0e8b12e
C
34 PeerTubeProblemDocument,
35 ServerErrorCode,
36 VideoCaption,
37 VideoPrivacy,
38 VideoState
39} from '@shared/models'
6ec0b75b 40import {
5efab546 41 CustomizationOptions,
6ec0b75b
C
42 P2PMediaLoaderOptions,
43 PeertubePlayerManager,
44 PeertubePlayerManagerOptions,
67ed6552
C
45 PlayerMode,
46 videojs
c4207f97
C
47} from '../../../assets/player'
48import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage'
67ed6552 49import { environment } from '../../../environments/environment'
911186da 50import { VideoWatchPlaylistComponent } from './shared'
dc8bc31b 51
a5cf76af
C
52type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
53
dc8bc31b
C
54@Component({
55 selector: 'my-video-watch',
ec8d8440
C
56 templateUrl: './video-watch.component.html',
57 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 58})
0629423c 59export class VideoWatchComponent implements OnInit, OnDestroy {
f36da21e 60 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
2f5d2ec5 61 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
df98563e 62
57d65032 63 player: VideoJsPlayer
0826c92d 64 playerElement: HTMLVideoElement
c15d61f5 65 playerPlaceholderImgSrc: string
c894a1ea 66 theaterEnabled = false
2de96f4d 67
2f4c784a
C
68 video: VideoDetails = null
69 videoCaptions: VideoCaption[] = []
f443a746 70 liveVideo: LiveVideo
2f4c784a 71
d142c7b9 72 playlistPosition: number
e2f01c47 73 playlist: VideoPlaylist = null
e2f01c47 74
6d88de72 75 remoteServerDown = false
5a2f775a 76 noPlaylistVideoFound = false
c15d61f5 77
c894a1ea 78 private nextVideoUUID = ''
3bcb4fd7 79 private nextVideoTitle = ''
c894a1ea 80
3545e72c
C
81 private videoFileToken: string
82
f0a39880 83 private currentTime: number
c894a1ea 84
df98563e 85 private paramsSub: Subscription
e2f01c47 86 private queryParamsSub: Subscription
31b6ddf8 87 private configSub: Subscription
a5cf76af 88 private liveVideosSub: Subscription
df98563e 89
2989628b 90 private serverConfig: HTMLServerConfig
ba430d75 91
6ea59f41
C
92 private hotkeys: Hotkey[] = []
93
df98563e 94 constructor (
4fd8aa32 95 private elementRef: ElementRef,
0629423c 96 private route: ActivatedRoute,
92fb909c 97 private router: Router,
d3ef341a 98 private videoService: VideoService,
e2f01c47 99 private playlistService: VideoPlaylistService,
f443a746 100 private liveVideoService: LiveVideoService,
92fb909c 101 private confirmService: ConfirmService,
3ec343a4 102 private metaService: MetaService,
7ddd02c9 103 private authService: AuthService,
d3217560 104 private userService: UserService,
0883b324 105 private serverService: ServerService,
a51bad1a 106 private restExtractor: RestExtractor,
f8b2c1b4 107 private notifier: Notifier,
901637bb 108 private zone: NgZone,
16f7022b 109 private videoCaptionService: VideoCaptionService,
20d21199 110 private hotkeysService: HotkeysService,
93cae479 111 private hooks: HooksService,
72f611ca 112 private pluginService: PluginService,
a5cf76af 113 private peertubeSocket: PeerTubeSocket,
2666fd7c 114 private screenService: ScreenService,
3545e72c 115 private videoFileTokenService: VideoFileTokenService,
60c2bc80 116 private location: PlatformLocation,
e945b184 117 @Inject(LOCALE_ID) private localeId: string
2666fd7c 118 ) { }
dc8bc31b 119
b2731bff
C
120 get user () {
121 return this.authService.getUser()
122 }
123
d3217560
RK
124 get anonymousUser () {
125 return this.userService.getAnonymousUser()
126 }
127
98ab5dc8 128 ngOnInit () {
6ebdd12f
C
129 this.serverConfig = this.serverService.getHTMLConfig()
130
1a568b6f
C
131 PeertubePlayerManager.initState()
132
c894a1ea
C
133 this.loadRouteParams()
134 this.loadRouteQuery()
20d21199 135
1c8ddbfa 136 this.initHotkeys()
011e1e6b
C
137
138 this.theaterEnabled = getStoredTheater()
18a6f04c 139
c9e3eeed 140 this.hooks.runAction('action:video-watch.init', 'video-watch')
58b9ce30 141
142 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
d1992b93
C
143 }
144
df98563e 145 ngOnDestroy () {
09edde40 146 this.flushPlayer()
067e3f84 147
13fc89f4 148 // Unsubscribe subscriptions
e2f01c47
C
149 if (this.paramsSub) this.paramsSub.unsubscribe()
150 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
5abc96fc 151 if (this.configSub) this.configSub.unsubscribe()
a5cf76af 152 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
20d21199
RK
153
154 // Unbind hotkeys
3d216ea0 155 this.hotkeysService.remove(this.hotkeys)
dc8bc31b 156 }
98b01bac 157
06a55579
C
158 getCurrentTime () {
159 return this.currentTime
6863f814
RK
160 }
161
06a55579
C
162 getCurrentPlaylistPosition () {
163 return this.videoWatchPlaylist.currentPlaylistPosition
99cc4f49
C
164 }
165
6aa54148 166 onRecommendations (videos: Video[]) {
c894a1ea 167 if (videos.length === 0) return
6aa54148 168
c894a1ea
C
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
b29bf61d
RK
173 }
174
175 handleTimestampClicked (timestamp: number) {
18429d01
C
176 if (!this.player || this.video.isLive) return
177
178 this.player.currentTime(timestamp)
b29bf61d 179 scrollToTop()
706c5a47
RK
180 }
181
c894a1ea 182 onPlaylistVideoFound (videoId: string) {
59a643aa 183 this.loadVideo({ videoId, forceAutoplay: false })
c894a1ea
C
184 }
185
5a2f775a
C
186 onPlaylistNoVideoFound () {
187 this.noPlaylistVideoFound = true
188 }
189
c894a1ea
C
190 isUserLoggedIn () {
191 return this.authService.isLoggedIn()
192 }
193
194 isVideoBlur (video: Video) {
195 return video.isVideoNSFWForUser(this.user, this.serverConfig)
706c5a47
RK
196 }
197
b40a2193
K
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
0f7407d9
C
207 displayOtherVideosAsRow () {
208 // Use the same value as in the SASS file
209 return this.screenService.getWindowInnerWidth() <= 1100
210 }
211
c894a1ea
C
212 private loadRouteParams () {
213 this.paramsSub = this.route.params.subscribe(routeParams => {
9df52d66 214 const videoId = routeParams['videoId']
59a643aa 215 if (videoId) return this.loadVideo({ videoId, forceAutoplay: false })
c894a1ea 216
9df52d66 217 const playlistId = routeParams['playlistId']
c894a1ea
C
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
9df52d66 225 const positionParam = queryParams['playlistPosition'] ?? 1
c894a1ea
C
226
227 this.playlistPosition = positionParam === 'last'
228 ? -1 // Handle the "last" index
229 : parseInt(positionParam + '', 10)
230
231 if (isNaN(this.playlistPosition)) {
42b40636 232 logger.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
c894a1ea
C
233 this.playlistPosition = 1
234 }
235
236 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
237
9df52d66 238 const start = queryParams['start']
c894a1ea
C
239 if (this.player && start) this.player.currentTime(parseInt(start, 10))
240 })
241 }
242
59a643aa
C
243 private loadVideo (options: {
244 videoId: string
245 forceAutoplay: boolean
246 }) {
247 const { videoId, forceAutoplay } = options
248
c894a1ea 249 if (this.isSameElement(this.video, videoId)) return
e2f01c47
C
250
251 if (this.player) this.player.pause()
252
5a9a56b7
C
253 this.video = undefined
254
93cae479
C
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
3545e72c 263 const videoAndLiveObs: Observable<{ video: VideoDetails, live?: LiveVideo, videoFileToken?: string }> = videoObs.pipe(
f443a746 264 switchMap(video => {
3545e72c 265 if (!video.isLive) return of({ video, live: undefined })
f443a746
C
266
267 return this.liveVideoService.getVideoLive(video.uuid)
268 .pipe(map(live => ({ live, video })))
3545e72c
C
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 })))
f443a746
C
276 })
277 )
278
a9bfa85d 279 forkJoin([
f443a746 280 videoAndLiveObs,
a9bfa85d
C
281 this.videoCaptionService.listCaptions(videoId),
282 this.userService.getAnonymousOrLoggedUser()
283 ]).subscribe({
3545e72c 284 next: ([ { video, live, videoFileToken }, captionsResult, loggedInOrAnonymousUser ]) => {
a9bfa85d 285 const queryParams = this.route.snapshot.queryParams
e6abf95e 286
a9bfa85d
C
287 const urlOptions = {
288 resume: queryParams.resume,
e2f01c47 289
a9bfa85d
C
290 startTime: queryParams.start,
291 stopTime: queryParams.stop,
3c6a44a1 292
a9bfa85d
C
293 muted: queryParams.muted,
294 loop: queryParams.loop,
295 subtitle: queryParams.subtitle,
5efab546 296
a9bfa85d 297 playerMode: queryParams.mode,
0e08a5e7 298 playbackRate: queryParams.playbackRate,
a9bfa85d
C
299 peertubeLink: false
300 }
5efab546 301
59a643aa
C
302 this.onVideoFetched({
303 video,
304 live,
305 videoCaptions: captionsResult.data,
306 videoFileToken,
307 loggedInOrAnonymousUser,
308 urlOptions,
309 forceAutoplay
310 }).catch(err => this.handleGlobalError(err))
a9bfa85d 311 },
4c72c1cd 312
a9bfa85d
C
313 error: err => this.handleRequestError(err)
314 })
e2f01c47
C
315 }
316
317 private loadPlaylist (playlistId: string) {
c894a1ea 318 if (this.isSameElement(this.playlist, playlistId)) return
e2f01c47 319
5a2f775a
C
320 this.noPlaylistVideoFound = false
321
e2f01c47 322 this.playlistService.getVideoPlaylist(playlistId)
1378c0d3
C
323 .subscribe({
324 next: playlist => {
c894a1ea
C
325 this.playlist = playlist
326
327 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
328 },
329
1378c0d3
C
330 error: err => this.handleRequestError(err)
331 })
c894a1ea 332 }
e2f01c47 333
c894a1ea
C
334 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
335 if (!element) return false
336
337 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
338 }
339
340 private async handleRequestError (err: any) {
341 const errorBody = err.body as PeerTubeProblemDocument
342
231ff4af 343 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
c894a1ea
C
344 const originUrl = errorBody.originUrl + (window.location.search ?? '')
345
346 const res = await this.confirmService.confirm(
9df52d66 347 // eslint-disable-next-line max-len
c894a1ea
C
348 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
349 $localize`Redirection`
350 )
351
352 if (res === true) return window.location.href = originUrl
353 }
354
355 // If 400, 403 or 404, the video is private or blocked so redirect to 404
356 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
357 HttpStatusCode.BAD_REQUEST_400,
358 HttpStatusCode.FORBIDDEN_403,
359 HttpStatusCode.NOT_FOUND_404
360 ])
e2f01c47
C
361 }
362
c894a1ea 363 private handleGlobalError (err: any) {
0c31c33d 364 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
365 if (!errorMessage) return
366
6d88de72 367 // Display a message in the video player instead of a notification
9df52d66 368 if (errorMessage.includes('from xs param')) {
6d88de72
C
369 this.flushPlayer()
370 this.remoteServerDown = true
3b492bff 371
6d88de72 372 return
0c31c33d
C
373 }
374
f8b2c1b4 375 this.notifier.error(errorMessage)
0c31c33d
C
376 }
377
a9bfa85d
C
378 private async onVideoFetched (options: {
379 video: VideoDetails
f443a746 380 live: LiveVideo
a9bfa85d 381 videoCaptions: VideoCaption[]
3545e72c
C
382 videoFileToken: string
383
a5cf76af 384 urlOptions: URLOptions
a9bfa85d 385 loggedInOrAnonymousUser: User
59a643aa 386 forceAutoplay: boolean
a9bfa85d 387 }) {
59a643aa 388 const { video, live, videoCaptions, urlOptions, videoFileToken, loggedInOrAnonymousUser, forceAutoplay } = options
a9bfa85d 389
a5cf76af
C
390 this.subscribeToLiveEventsIfNeeded(this.video, video)
391
df98563e 392 this.video = video
2f4c784a 393 this.videoCaptions = videoCaptions
f443a746 394 this.liveVideo = live
3545e72c 395 this.videoFileToken = videoFileToken
92fb909c 396
c448d412 397 // Re init attributes
c15d61f5 398 this.playerPlaceholderImgSrc = undefined
6d88de72 399 this.remoteServerDown = false
f0a39880 400 this.currentTime = undefined
c448d412 401
e2f01c47 402 if (this.isVideoBlur(this.video)) {
22b59e80 403 const res = await this.confirmService.confirm(
66357162
C
404 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
405 $localize`Mature or explicit content`
d6e32a2e 406 )
60c2bc80 407 if (res === false) return this.location.back()
92fb909c
C
408 }
409
59a643aa 410 this.buildPlayer({ urlOptions, loggedInOrAnonymousUser, forceAutoplay })
42b40636 411 .catch(err => logger.error('Cannot build the player', err))
0a6817f0 412
0a6817f0 413 this.setOpenGraphTags()
0a6817f0 414
55b84d53
C
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)
0a6817f0
C
421 }
422
59a643aa
C
423 private async buildPlayer (options: {
424 urlOptions: URLOptions
425 loggedInOrAnonymousUser: User
426 forceAutoplay: boolean
427 }) {
428 const { urlOptions, loggedInOrAnonymousUser, forceAutoplay } = options
429
09edde40
C
430 // Flush old player if needed
431 this.flushPlayer()
b891f9bc 432
c15d61f5
C
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
60c2bc80 439 // Build video element, because videojs removes it on dispose
e2f01c47 440 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
441 this.playerElement = document.createElement('video')
442 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 443 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
444 playerElementWrapper.appendChild(this.playerElement)
445
3d9a63d3
C
446 const params = {
447 video: this.video,
0a6817f0 448 videoCaptions: this.videoCaptions,
f443a746 449 liveVideo: this.liveVideo,
3545e72c 450 videoFileToken: this.videoFileToken,
3d9a63d3 451 urlOptions,
a9bfa85d 452 loggedInOrAnonymousUser,
59a643aa 453 forceAutoplay,
3d9a63d3 454 user: this.user
e945b184 455 }
3d9a63d3
C
456 const { playerMode, playerOptions } = await this.hooks.wrapFun(
457 this.buildPlayerManagerOptions.bind(this),
458 params,
c2023a9f
C
459 'video-watch',
460 'filter:internal.video-watch.player.build-options.params',
3d9a63d3
C
461 'filter:internal.video-watch.player.build-options.result'
462 )
e945b184 463
e945b184 464 this.zone.runOutsideAngular(async () => {
3d9a63d3 465 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
9a18a625 466
57d65032
C
467 this.player.on('customError', (_e, data: any) => {
468 this.zone.run(() => this.handleGlobalError(data.err))
c894a1ea 469 })
f0a39880
C
470
471 this.player.on('timeupdate', () => {
c894a1ea 472 // Don't need to trigger angular change for this variable, that is sent to children components on click
f0a39880
C
473 this.currentTime = Math.floor(this.player.currentTime())
474 })
e2f01c47 475
3bcb4fd7 476 /**
c894a1ea
C
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.
3bcb4fd7
RK
482 */
483 this.player.upnext({
c894a1ea
C
484 timeout: 5000, // 5s
485
66357162
C
486 headText: $localize`Up Next`,
487 cancelText: $localize`Cancel`,
488 suspendedText: $localize`Autoplay is suspended`,
c894a1ea 489
3bcb4fd7 490 getTitle: () => this.nextVideoTitle,
c894a1ea
C
491
492 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
3bcb4fd7 493 condition: () => {
c894a1ea
C
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
3bcb4fd7 500 }
c894a1ea
C
501
502 return false
223b24e6 503 },
c894a1ea 504
223b24e6
RK
505 suspended: () => {
506 return (
57d65032 507 !isXPercentInViewport(this.player.el() as HTMLElement, 80) ||
223b24e6
RK
508 !document.getElementById('content').contains(document.activeElement)
509 )
e2f01c47
C
510 }
511 })
512
513 this.player.one('stopped', () => {
c894a1ea
C
514 if (this.playlist && this.isPlaylistAutoPlayNext()) {
515 this.playNextVideoInAngularZone()
e2f01c47
C
516 }
517 })
9a18a625 518
e772bdf1
C
519 this.player.one('ended', () => {
520 if (this.video.isLive) {
ceb8f322 521 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
e772bdf1
C
522 }
523 })
524
9a18a625
C
525 this.player.on('theaterChange', (_: any, enabled: boolean) => {
526 this.zone.run(() => this.theaterEnabled = enabled)
527 })
5f85f8aa 528
c3bb0441 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 })
b891f9bc 536 })
92fb909c
C
537 }
538
a5a79d15
C
539 private hasNextVideo () {
540 if (this.playlist) {
541 return this.videoWatchPlaylist.hasNextVideo()
542 }
543
544 return true
545 }
546
c894a1ea 547 private playNextVideoInAngularZone () {
6dd873d6
RK
548 if (this.playlist) {
549 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
c894a1ea 550 return
6aa54148 551 }
3ec343a4 552
c894a1ea
C
553 if (this.nextVideoUUID) {
554 this.router.navigate([ '/w', this.nextVideoUUID ])
c894a1ea 555 }
3ec343a4 556 }
1f3e9fec 557
d4c6a3b9 558 private isAutoplay () {
bf079b7b
C
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
d4c6a3b9
C
563 if (!this.user) return true
564
565 // Be sure the autoPlay is set to false
566 return this.user.autoPlayVideo !== false
567 }
09edde40 568
c894a1ea
C
569 private isAutoPlayNext () {
570 return (
9df52d66 571 (this.user?.autoPlayNextVideo) ||
c894a1ea
C
572 this.anonymousUser.autoPlayNextVideo
573 )
574 }
575
576 private isPlaylistAutoPlayNext () {
577 return (
9df52d66 578 (this.user?.autoPlayNextVideoPlaylist) ||
c894a1ea
C
579 this.anonymousUser.autoPlayNextVideoPlaylist
580 )
581 }
582
09edde40
C
583 private flushPlayer () {
584 // Remove player if it exists
d4a8e7a6
C
585 if (!this.player) return
586
587 try {
588 this.player.dispose()
589 this.player = undefined
590 } catch (err) {
42b40636 591 logger.error('Cannot dispose player.', err)
09edde40
C
592 }
593 }
1c8ddbfa 594
3d9a63d3 595 private buildPlayerManagerOptions (params: {
9df52d66 596 video: VideoDetails
f443a746 597 liveVideo: LiveVideo
9df52d66 598 videoCaptions: VideoCaption[]
3545e72c
C
599
600 videoFileToken: string
601
9df52d66 602 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
3545e72c 603
a9bfa85d 604 loggedInOrAnonymousUser: User
59a643aa 605 forceAutoplay: boolean
384ba8b7 606 user?: AuthUser // Keep for plugins
3d9a63d3 607 }) {
59a643aa 608 const { video, liveVideo, videoCaptions, videoFileToken, urlOptions, loggedInOrAnonymousUser, forceAutoplay } = params
c894a1ea 609
706c5a47
RK
610 const getStartTime = () => {
611 const byUrl = urlOptions.startTime !== undefined
96f6278f 612 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
58b9ce30 613 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
706c5a47 614
3c6a44a1
C
615 if (byUrl) return timeToInt(urlOptions.startTime)
616 if (byHistory) return video.userHistory.currentTime
58b9ce30 617 if (byLocalStorage) return byLocalStorage.duration
3c6a44a1
C
618
619 return 0
706c5a47 620 }
3d9a63d3 621
706c5a47 622 let startTime = getStartTime()
3c6a44a1 623
3d9a63d3
C
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
f443a746
C
633 const liveOptions = video.isLive
634 ? { latencyMode: liveVideo.latencyMode }
635 : undefined
636
3d9a63d3
C
637 const options: PeertubePlayerManagerOptions = {
638 common: {
639 autoplay: this.isAutoplay(),
59a643aa 640 forceAutoplay,
a9bfa85d
C
641 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
642
a5a79d15 643 hasNextVideo: () => this.hasNextVideo(),
c894a1ea 644 nextVideo: () => this.playNextVideoInAngularZone(),
3d9a63d3
C
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,
60f013e1 656 controlBar: urlOptions.controlBar,
3d9a63d3
C
657 controls: urlOptions.controls,
658 muted: urlOptions.muted,
659 loop: urlOptions.loop,
660 subtitle: urlOptions.subtitle,
0e08a5e7 661 playbackRate: urlOptions.playbackRate,
3d9a63d3
C
662
663 peertubeLink: urlOptions.peertubeLink,
664
665 theaterButton: true,
666 captions: videoCaptions.length !== 0,
667
3d9a63d3 668 embedUrl: video.embedUrl,
4097c6d6 669 embedTitle: video.name,
bd2b51be 670 instanceName: this.serverConfig.instance.name,
3d9a63d3 671
25b7c847 672 isLive: video.isLive,
f443a746 673 liveOptions,
25b7c847 674
3d9a63d3
C
675 language: this.localeId,
676
3545e72c
C
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
2e3b0825 684 serverUrl: environment.originServerUrl || window.location.origin,
3545e72c
C
685
686 videoFileToken: () => videoFileToken,
687 requiresAuth: videoRequiresAuth(video),
3d9a63d3 688
58b9ce30 689 videoCaptions: playerCaptions,
690
9162fdd3 691 videoShortUUID: video.shortUUID,
c4207f97
C
692 videoUUID: video.uuid,
693
694 errorNotifier: (message: string) => this.notifier.error(message)
3d9a63d3
C
695 },
696
697 webtorrent: {
698 videoFiles: video.files
72f611ca 699 },
700
701 pluginsManager: this.pluginService.getPluginsManager()
3d9a63d3
C
702 }
703
dfdcbb94 704 // Only set this if we're in a playlist
5bb2ed6b 705 if (this.playlist) {
a5a79d15
C
706 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
707
5bb2ed6b
P
708 options.common.previousVideo = () => {
709 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
710 }
dfdcbb94
P
711 }
712
3d9a63d3
C
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
c894a1ea 723 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
089af69b
C
724 if (typeof TextEncoder === 'undefined') {
725 mode = 'webtorrent'
726 }
727
3d9a63d3
C
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
a5cf76af
C
745 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
746 if (!this.liveVideosSub) {
a800dbf3 747 this.liveVideosSub = this.buildLiveEventsSubscription()
a5cf76af
C
748 }
749
750 if (oldVideo && oldVideo.id !== newVideo.id) {
98ab5dc8 751 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
a5cf76af
C
752 }
753
754 if (!newVideo.isLive) return
755
756 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
757 }
758
a800dbf3
C
759 private buildLiveEventsSubscription () {
760 return this.peertubeSocket.getLiveVideosObservable()
761 .subscribe(({ type, payload }) => {
762 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
51353d9a 763 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
a800dbf3
C
764 })
765 }
766
767 private handleLiveStateChange (newState: VideoState) {
768 if (newState !== VideoState.PUBLISHED) return
769
42b40636 770 logger.info('Loading video after live update.')
a800dbf3
C
771
772 const videoUUID = this.video.uuid
773
c894a1ea 774 // Reset to force refresh the video
a800dbf3 775 this.video = undefined
59a643aa 776 this.loadVideo({ videoId: videoUUID, forceAutoplay: true })
a800dbf3
C
777 }
778
51353d9a 779 private handleLiveViewsChange (newViewers: number) {
a800dbf3 780 if (!this.video) {
42b40636 781 logger.error('Cannot update video live views because video is no defined.')
a800dbf3
C
782 return
783 }
784
42b40636 785 logger.info('Updating live views.')
e43b5a3f 786
51353d9a 787 this.video.viewers = newViewers
a800dbf3
C
788 }
789
941c5eac
C
790 private initHotkeys () {
791 this.hotkeys = [
941c5eac 792 // These hotkeys are managed by the player
fc3412fd
C
793 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
794 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
795 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
941c5eac 796
fc3412fd 797 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
941c5eac 798
fc3412fd
C
799 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
800 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
941c5eac 801
fc3412fd
C
802 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
803 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
941c5eac 804
fc3412fd
C
805 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
806 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
941c5eac 807
fc3412fd
C
808 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
809 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
810
811 new Hotkey('t', e => {
812 this.theaterEnabled = !this.theaterEnabled
813 return false
814 }, undefined, $localize`Toggle theater mode`)
941c5eac 815 ]
3d216ea0
C
816
817 if (this.isUserLoggedIn()) {
818 this.hotkeys = this.hotkeys.concat([
3d216ea0 819 new Hotkey('shift+s', () => {
9df52d66
C
820 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
821 else this.subscribeButton.subscribe()
77d873c5 822
3d216ea0 823 return false
66357162 824 }, undefined, $localize`Subscribe to the account`)
3d216ea0
C
825 ])
826 }
827
828 this.hotkeysService.add(this.hotkeys)
941c5eac 829 }
c894a1ea
C
830
831 private setOpenGraphTags () {
832 this.metaService.setTitle(this.video.name)
833
834 this.metaService.setTag('og:type', 'video')
835
836 this.metaService.setTag('og:title', this.video.name)
837 this.metaService.setTag('name', this.video.name)
838
839 this.metaService.setTag('og:description', this.video.description)
840 this.metaService.setTag('description', this.video.description)
841
842 this.metaService.setTag('og:image', this.video.previewPath)
843
844 this.metaService.setTag('og:duration', this.video.duration.toString())
845
846 this.metaService.setTag('og:site_name', 'PeerTube')
847
848 this.metaService.setTag('og:url', window.location.href)
849 this.metaService.setTag('url', window.location.href)
850 }
dc8bc31b 851}