]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
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
011e1e6b 136 this.theaterEnabled = getStoredTheater()
18a6f04c 137
c9e3eeed 138 this.hooks.runAction('action:video-watch.init', 'video-watch')
58b9ce30 139
140 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
d1992b93
C
141 }
142
df98563e 143 ngOnDestroy () {
09edde40 144 this.flushPlayer()
067e3f84 145
13fc89f4 146 // Unsubscribe subscriptions
e2f01c47
C
147 if (this.paramsSub) this.paramsSub.unsubscribe()
148 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
5abc96fc 149 if (this.configSub) this.configSub.unsubscribe()
a5cf76af 150 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
20d21199
RK
151
152 // Unbind hotkeys
3d216ea0 153 this.hotkeysService.remove(this.hotkeys)
dc8bc31b 154 }
98b01bac 155
06a55579
C
156 getCurrentTime () {
157 return this.currentTime
6863f814
RK
158 }
159
06a55579
C
160 getCurrentPlaylistPosition () {
161 return this.videoWatchPlaylist.currentPlaylistPosition
99cc4f49
C
162 }
163
6aa54148 164 onRecommendations (videos: Video[]) {
c894a1ea 165 if (videos.length === 0) return
6aa54148 166
c894a1ea
C
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
b29bf61d
RK
171 }
172
173 handleTimestampClicked (timestamp: number) {
18429d01
C
174 if (!this.player || this.video.isLive) return
175
176 this.player.currentTime(timestamp)
b29bf61d 177 scrollToTop()
706c5a47
RK
178 }
179
c894a1ea 180 onPlaylistVideoFound (videoId: string) {
59a643aa 181 this.loadVideo({ videoId, forceAutoplay: false })
c894a1ea
C
182 }
183
5a2f775a
C
184 onPlaylistNoVideoFound () {
185 this.noPlaylistVideoFound = true
186 }
187
c894a1ea
C
188 isUserLoggedIn () {
189 return this.authService.isLoggedIn()
190 }
191
192 isVideoBlur (video: Video) {
193 return video.isVideoNSFWForUser(this.user, this.serverConfig)
706c5a47
RK
194 }
195
b40a2193
K
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
0f7407d9
C
205 displayOtherVideosAsRow () {
206 // Use the same value as in the SASS file
207 return this.screenService.getWindowInnerWidth() <= 1100
208 }
209
c894a1ea
C
210 private loadRouteParams () {
211 this.paramsSub = this.route.params.subscribe(routeParams => {
9df52d66 212 const videoId = routeParams['videoId']
59a643aa 213 if (videoId) return this.loadVideo({ videoId, forceAutoplay: false })
c894a1ea 214
9df52d66 215 const playlistId = routeParams['playlistId']
c894a1ea
C
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
9df52d66 223 const positionParam = queryParams['playlistPosition'] ?? 1
c894a1ea
C
224
225 this.playlistPosition = positionParam === 'last'
226 ? -1 // Handle the "last" index
227 : parseInt(positionParam + '', 10)
228
229 if (isNaN(this.playlistPosition)) {
42b40636 230 logger.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
c894a1ea
C
231 this.playlistPosition = 1
232 }
233
234 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
235
9df52d66 236 const start = queryParams['start']
c894a1ea
C
237 if (this.player && start) this.player.currentTime(parseInt(start, 10))
238 })
239 }
240
59a643aa
C
241 private loadVideo (options: {
242 videoId: string
243 forceAutoplay: boolean
244 }) {
245 const { videoId, forceAutoplay } = options
246
c894a1ea 247 if (this.isSameElement(this.video, videoId)) return
e2f01c47
C
248
249 if (this.player) this.player.pause()
250
5a9a56b7
C
251 this.video = undefined
252
93cae479
C
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
3545e72c 261 const videoAndLiveObs: Observable<{ video: VideoDetails, live?: LiveVideo, videoFileToken?: string }> = videoObs.pipe(
f443a746 262 switchMap(video => {
3545e72c 263 if (!video.isLive) return of({ video, live: undefined })
f443a746
C
264
265 return this.liveVideoService.getVideoLive(video.uuid)
266 .pipe(map(live => ({ live, video })))
3545e72c
C
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 })))
f443a746
C
274 })
275 )
276
a9bfa85d 277 forkJoin([
f443a746 278 videoAndLiveObs,
a9bfa85d
C
279 this.videoCaptionService.listCaptions(videoId),
280 this.userService.getAnonymousOrLoggedUser()
281 ]).subscribe({
3545e72c 282 next: ([ { video, live, videoFileToken }, captionsResult, loggedInOrAnonymousUser ]) => {
a9bfa85d 283 const queryParams = this.route.snapshot.queryParams
e6abf95e 284
a9bfa85d
C
285 const urlOptions = {
286 resume: queryParams.resume,
e2f01c47 287
a9bfa85d
C
288 startTime: queryParams.start,
289 stopTime: queryParams.stop,
3c6a44a1 290
a9bfa85d
C
291 muted: queryParams.muted,
292 loop: queryParams.loop,
293 subtitle: queryParams.subtitle,
5efab546 294
a9bfa85d 295 playerMode: queryParams.mode,
0e08a5e7 296 playbackRate: queryParams.playbackRate,
a9bfa85d
C
297 peertubeLink: false
298 }
5efab546 299
59a643aa
C
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))
a9bfa85d 309 },
4c72c1cd 310
a9bfa85d
C
311 error: err => this.handleRequestError(err)
312 })
e2f01c47
C
313 }
314
315 private loadPlaylist (playlistId: string) {
c894a1ea 316 if (this.isSameElement(this.playlist, playlistId)) return
e2f01c47 317
5a2f775a
C
318 this.noPlaylistVideoFound = false
319
e2f01c47 320 this.playlistService.getVideoPlaylist(playlistId)
1378c0d3
C
321 .subscribe({
322 next: playlist => {
c894a1ea
C
323 this.playlist = playlist
324
325 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
326 },
327
1378c0d3
C
328 error: err => this.handleRequestError(err)
329 })
c894a1ea 330 }
e2f01c47 331
c894a1ea
C
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
231ff4af 341 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
c894a1ea
C
342 const originUrl = errorBody.originUrl + (window.location.search ?? '')
343
344 const res = await this.confirmService.confirm(
9df52d66 345 // eslint-disable-next-line max-len
c894a1ea
C
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 ])
e2f01c47
C
359 }
360
c894a1ea 361 private handleGlobalError (err: any) {
0c31c33d 362 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
363 if (!errorMessage) return
364
6d88de72 365 // Display a message in the video player instead of a notification
9df52d66 366 if (errorMessage.includes('from xs param')) {
6d88de72
C
367 this.flushPlayer()
368 this.remoteServerDown = true
3b492bff 369
6d88de72 370 return
0c31c33d
C
371 }
372
f8b2c1b4 373 this.notifier.error(errorMessage)
0c31c33d
C
374 }
375
a9bfa85d
C
376 private async onVideoFetched (options: {
377 video: VideoDetails
f443a746 378 live: LiveVideo
a9bfa85d 379 videoCaptions: VideoCaption[]
3545e72c
C
380 videoFileToken: string
381
a5cf76af 382 urlOptions: URLOptions
a9bfa85d 383 loggedInOrAnonymousUser: User
59a643aa 384 forceAutoplay: boolean
a9bfa85d 385 }) {
59a643aa 386 const { video, live, videoCaptions, urlOptions, videoFileToken, loggedInOrAnonymousUser, forceAutoplay } = options
a9bfa85d 387
a5cf76af
C
388 this.subscribeToLiveEventsIfNeeded(this.video, video)
389
df98563e 390 this.video = video
2f4c784a 391 this.videoCaptions = videoCaptions
f443a746 392 this.liveVideo = live
3545e72c 393 this.videoFileToken = videoFileToken
92fb909c 394
c448d412 395 // Re init attributes
c15d61f5 396 this.playerPlaceholderImgSrc = undefined
6d88de72 397 this.remoteServerDown = false
f0a39880 398 this.currentTime = undefined
c448d412 399
e2f01c47 400 if (this.isVideoBlur(this.video)) {
22b59e80 401 const res = await this.confirmService.confirm(
66357162
C
402 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
403 $localize`Mature or explicit content`
d6e32a2e 404 )
60c2bc80 405 if (res === false) return this.location.back()
92fb909c
C
406 }
407
66b73484
C
408 this.buildHotkeysHelp(video)
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
66b73484
C
790 private buildHotkeysHelp (video: Video) {
791 if (this.hotkeys.length !== 0) {
792 this.hotkeysService.remove(this.hotkeys)
793 }
794
941c5eac 795 this.hotkeys = [
941c5eac 796 // These hotkeys are managed by the player
fc3412fd
C
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`),
941c5eac 800
fc3412fd
C
801 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
802 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
941c5eac 803
fc3412fd
C
804 new Hotkey('t', e => {
805 this.theaterEnabled = !this.theaterEnabled
806 return false
807 }, undefined, $localize`Toggle theater mode`)
941c5eac 808 ]
3d216ea0 809
66b73484
C
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
3d216ea0
C
827 if (this.isUserLoggedIn()) {
828 this.hotkeys = this.hotkeys.concat([
3d216ea0 829 new Hotkey('shift+s', () => {
9df52d66
C
830 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
831 else this.subscribeButton.subscribe()
77d873c5 832
3d216ea0 833 return false
66357162 834 }, undefined, $localize`Subscribe to the account`)
3d216ea0
C
835 ])
836 }
837
838 this.hotkeysService.add(this.hotkeys)
941c5eac 839 }
c894a1ea
C
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 }
dc8bc31b 861}