]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
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
C
182 onPlaylistVideoFound (videoId: string) {
183 this.loadVideo(videoId)
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']
c894a1ea
C
215 if (videoId) return this.loadVideo(videoId)
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
e2f01c47 243 private loadVideo (videoId: string) {
c894a1ea 244 if (this.isSameElement(this.video, videoId)) return
e2f01c47
C
245
246 if (this.player) this.player.pause()
247
5a9a56b7
C
248 this.video = undefined
249
93cae479
C
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
3545e72c 258 const videoAndLiveObs: Observable<{ video: VideoDetails, live?: LiveVideo, videoFileToken?: string }> = videoObs.pipe(
f443a746 259 switchMap(video => {
3545e72c 260 if (!video.isLive) return of({ video, live: undefined })
f443a746
C
261
262 return this.liveVideoService.getVideoLive(video.uuid)
263 .pipe(map(live => ({ live, video })))
3545e72c
C
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 })))
f443a746
C
271 })
272 )
273
a9bfa85d 274 forkJoin([
f443a746 275 videoAndLiveObs,
a9bfa85d
C
276 this.videoCaptionService.listCaptions(videoId),
277 this.userService.getAnonymousOrLoggedUser()
278 ]).subscribe({
3545e72c 279 next: ([ { video, live, videoFileToken }, captionsResult, loggedInOrAnonymousUser ]) => {
a9bfa85d 280 const queryParams = this.route.snapshot.queryParams
e6abf95e 281
a9bfa85d
C
282 const urlOptions = {
283 resume: queryParams.resume,
e2f01c47 284
a9bfa85d
C
285 startTime: queryParams.start,
286 stopTime: queryParams.stop,
3c6a44a1 287
a9bfa85d
C
288 muted: queryParams.muted,
289 loop: queryParams.loop,
290 subtitle: queryParams.subtitle,
5efab546 291
a9bfa85d
C
292 playerMode: queryParams.mode,
293 peertubeLink: false
294 }
5efab546 295
3545e72c 296 this.onVideoFetched({ video, live, videoCaptions: captionsResult.data, videoFileToken, loggedInOrAnonymousUser, urlOptions })
a9bfa85d
C
297 .catch(err => this.handleGlobalError(err))
298 },
4c72c1cd 299
a9bfa85d
C
300 error: err => this.handleRequestError(err)
301 })
e2f01c47
C
302 }
303
304 private loadPlaylist (playlistId: string) {
c894a1ea 305 if (this.isSameElement(this.playlist, playlistId)) return
e2f01c47 306
5a2f775a
C
307 this.noPlaylistVideoFound = false
308
e2f01c47 309 this.playlistService.getVideoPlaylist(playlistId)
1378c0d3
C
310 .subscribe({
311 next: playlist => {
c894a1ea
C
312 this.playlist = playlist
313
314 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
315 },
316
1378c0d3
C
317 error: err => this.handleRequestError(err)
318 })
c894a1ea 319 }
e2f01c47 320
c894a1ea
C
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
231ff4af 330 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
c894a1ea
C
331 const originUrl = errorBody.originUrl + (window.location.search ?? '')
332
333 const res = await this.confirmService.confirm(
9df52d66 334 // eslint-disable-next-line max-len
c894a1ea
C
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 ])
e2f01c47
C
348 }
349
c894a1ea 350 private handleGlobalError (err: any) {
0c31c33d 351 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
352 if (!errorMessage) return
353
6d88de72 354 // Display a message in the video player instead of a notification
9df52d66 355 if (errorMessage.includes('from xs param')) {
6d88de72
C
356 this.flushPlayer()
357 this.remoteServerDown = true
3b492bff 358
6d88de72 359 return
0c31c33d
C
360 }
361
f8b2c1b4 362 this.notifier.error(errorMessage)
0c31c33d
C
363 }
364
a9bfa85d
C
365 private async onVideoFetched (options: {
366 video: VideoDetails
f443a746 367 live: LiveVideo
a9bfa85d 368 videoCaptions: VideoCaption[]
3545e72c
C
369 videoFileToken: string
370
a5cf76af 371 urlOptions: URLOptions
a9bfa85d
C
372 loggedInOrAnonymousUser: User
373 }) {
3545e72c 374 const { video, live, videoCaptions, urlOptions, videoFileToken, loggedInOrAnonymousUser } = options
a9bfa85d 375
a5cf76af
C
376 this.subscribeToLiveEventsIfNeeded(this.video, video)
377
df98563e 378 this.video = video
2f4c784a 379 this.videoCaptions = videoCaptions
f443a746 380 this.liveVideo = live
3545e72c 381 this.videoFileToken = videoFileToken
92fb909c 382
c448d412 383 // Re init attributes
c15d61f5 384 this.playerPlaceholderImgSrc = undefined
6d88de72 385 this.remoteServerDown = false
f0a39880 386 this.currentTime = undefined
c448d412 387
e2f01c47 388 if (this.isVideoBlur(this.video)) {
22b59e80 389 const res = await this.confirmService.confirm(
66357162
C
390 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
391 $localize`Mature or explicit content`
d6e32a2e 392 )
60c2bc80 393 if (res === false) return this.location.back()
92fb909c
C
394 }
395
a9bfa85d 396 this.buildPlayer(urlOptions, loggedInOrAnonymousUser)
42b40636 397 .catch(err => logger.error('Cannot build the player', err))
0a6817f0 398
0a6817f0 399 this.setOpenGraphTags()
0a6817f0 400
55b84d53
C
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)
0a6817f0
C
407 }
408
a9bfa85d 409 private async buildPlayer (urlOptions: URLOptions, loggedInOrAnonymousUser: User) {
09edde40
C
410 // Flush old player if needed
411 this.flushPlayer()
b891f9bc 412
c15d61f5
C
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
60c2bc80 419 // Build video element, because videojs removes it on dispose
e2f01c47 420 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
421 this.playerElement = document.createElement('video')
422 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 423 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
424 playerElementWrapper.appendChild(this.playerElement)
425
3d9a63d3
C
426 const params = {
427 video: this.video,
0a6817f0 428 videoCaptions: this.videoCaptions,
f443a746 429 liveVideo: this.liveVideo,
3545e72c 430 videoFileToken: this.videoFileToken,
3d9a63d3 431 urlOptions,
a9bfa85d 432 loggedInOrAnonymousUser,
3d9a63d3 433 user: this.user
e945b184 434 }
3d9a63d3
C
435 const { playerMode, playerOptions } = await this.hooks.wrapFun(
436 this.buildPlayerManagerOptions.bind(this),
437 params,
c2023a9f
C
438 'video-watch',
439 'filter:internal.video-watch.player.build-options.params',
3d9a63d3
C
440 'filter:internal.video-watch.player.build-options.result'
441 )
e945b184 442
e945b184 443 this.zone.runOutsideAngular(async () => {
3d9a63d3 444 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
9a18a625 445
57d65032
C
446 this.player.on('customError', (_e, data: any) => {
447 this.zone.run(() => this.handleGlobalError(data.err))
c894a1ea 448 })
f0a39880
C
449
450 this.player.on('timeupdate', () => {
c894a1ea 451 // Don't need to trigger angular change for this variable, that is sent to children components on click
f0a39880
C
452 this.currentTime = Math.floor(this.player.currentTime())
453 })
e2f01c47 454
3bcb4fd7 455 /**
c894a1ea
C
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.
3bcb4fd7
RK
461 */
462 this.player.upnext({
c894a1ea
C
463 timeout: 5000, // 5s
464
66357162
C
465 headText: $localize`Up Next`,
466 cancelText: $localize`Cancel`,
467 suspendedText: $localize`Autoplay is suspended`,
c894a1ea 468
3bcb4fd7 469 getTitle: () => this.nextVideoTitle,
c894a1ea
C
470
471 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
3bcb4fd7 472 condition: () => {
c894a1ea
C
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
3bcb4fd7 479 }
c894a1ea
C
480
481 return false
223b24e6 482 },
c894a1ea 483
223b24e6
RK
484 suspended: () => {
485 return (
57d65032 486 !isXPercentInViewport(this.player.el() as HTMLElement, 80) ||
223b24e6
RK
487 !document.getElementById('content').contains(document.activeElement)
488 )
e2f01c47
C
489 }
490 })
491
492 this.player.one('stopped', () => {
c894a1ea
C
493 if (this.playlist && this.isPlaylistAutoPlayNext()) {
494 this.playNextVideoInAngularZone()
e2f01c47
C
495 }
496 })
9a18a625 497
e772bdf1
C
498 this.player.one('ended', () => {
499 if (this.video.isLive) {
ceb8f322 500 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
e772bdf1
C
501 }
502 })
503
9a18a625
C
504 this.player.on('theaterChange', (_: any, enabled: boolean) => {
505 this.zone.run(() => this.theaterEnabled = enabled)
506 })
5f85f8aa 507
c3bb0441 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 })
b891f9bc 515 })
92fb909c
C
516 }
517
a5a79d15
C
518 private hasNextVideo () {
519 if (this.playlist) {
520 return this.videoWatchPlaylist.hasNextVideo()
521 }
522
523 return true
524 }
525
c894a1ea 526 private playNextVideoInAngularZone () {
6dd873d6
RK
527 if (this.playlist) {
528 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
c894a1ea 529 return
6aa54148 530 }
3ec343a4 531
c894a1ea
C
532 if (this.nextVideoUUID) {
533 this.router.navigate([ '/w', this.nextVideoUUID ])
c894a1ea 534 }
3ec343a4 535 }
1f3e9fec 536
d4c6a3b9 537 private isAutoplay () {
bf079b7b
C
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
d4c6a3b9
C
542 if (!this.user) return true
543
544 // Be sure the autoPlay is set to false
545 return this.user.autoPlayVideo !== false
546 }
09edde40 547
c894a1ea
C
548 private isAutoPlayNext () {
549 return (
9df52d66 550 (this.user?.autoPlayNextVideo) ||
c894a1ea
C
551 this.anonymousUser.autoPlayNextVideo
552 )
553 }
554
555 private isPlaylistAutoPlayNext () {
556 return (
9df52d66 557 (this.user?.autoPlayNextVideoPlaylist) ||
c894a1ea
C
558 this.anonymousUser.autoPlayNextVideoPlaylist
559 )
560 }
561
09edde40
C
562 private flushPlayer () {
563 // Remove player if it exists
d4a8e7a6
C
564 if (!this.player) return
565
566 try {
567 this.player.dispose()
568 this.player = undefined
569 } catch (err) {
42b40636 570 logger.error('Cannot dispose player.', err)
09edde40
C
571 }
572 }
1c8ddbfa 573
3d9a63d3 574 private buildPlayerManagerOptions (params: {
9df52d66 575 video: VideoDetails
f443a746 576 liveVideo: LiveVideo
9df52d66 577 videoCaptions: VideoCaption[]
3545e72c
C
578
579 videoFileToken: string
580
9df52d66 581 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
3545e72c 582
a9bfa85d 583 loggedInOrAnonymousUser: User
384ba8b7 584 user?: AuthUser // Keep for plugins
3d9a63d3 585 }) {
3545e72c 586 const { video, liveVideo, videoCaptions, videoFileToken, urlOptions, loggedInOrAnonymousUser } = params
c894a1ea 587
706c5a47
RK
588 const getStartTime = () => {
589 const byUrl = urlOptions.startTime !== undefined
96f6278f 590 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
58b9ce30 591 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
706c5a47 592
3c6a44a1
C
593 if (byUrl) return timeToInt(urlOptions.startTime)
594 if (byHistory) return video.userHistory.currentTime
58b9ce30 595 if (byLocalStorage) return byLocalStorage.duration
3c6a44a1
C
596
597 return 0
706c5a47 598 }
3d9a63d3 599
706c5a47 600 let startTime = getStartTime()
3c6a44a1 601
3d9a63d3
C
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
f443a746
C
611 const liveOptions = video.isLive
612 ? { latencyMode: liveVideo.latencyMode }
613 : undefined
614
3d9a63d3
C
615 const options: PeertubePlayerManagerOptions = {
616 common: {
617 autoplay: this.isAutoplay(),
a9bfa85d
C
618 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
619
a5a79d15 620 hasNextVideo: () => this.hasNextVideo(),
c894a1ea 621 nextVideo: () => this.playNextVideoInAngularZone(),
3d9a63d3
C
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,
60f013e1 633 controlBar: urlOptions.controlBar,
3d9a63d3
C
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
3d9a63d3 644 embedUrl: video.embedUrl,
4097c6d6 645 embedTitle: video.name,
bd2b51be 646 instanceName: this.serverConfig.instance.name,
3d9a63d3 647
25b7c847 648 isLive: video.isLive,
f443a746 649 liveOptions,
25b7c847 650
3d9a63d3
C
651 language: this.localeId,
652
3545e72c
C
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
2e3b0825 660 serverUrl: environment.originServerUrl || window.location.origin,
3545e72c
C
661
662 videoFileToken: () => videoFileToken,
663 requiresAuth: videoRequiresAuth(video),
3d9a63d3 664
58b9ce30 665 videoCaptions: playerCaptions,
666
9162fdd3 667 videoShortUUID: video.shortUUID,
c4207f97
C
668 videoUUID: video.uuid,
669
670 errorNotifier: (message: string) => this.notifier.error(message)
3d9a63d3
C
671 },
672
673 webtorrent: {
674 videoFiles: video.files
72f611ca 675 },
676
677 pluginsManager: this.pluginService.getPluginsManager()
3d9a63d3
C
678 }
679
dfdcbb94 680 // Only set this if we're in a playlist
5bb2ed6b 681 if (this.playlist) {
a5a79d15
C
682 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
683
5bb2ed6b
P
684 options.common.previousVideo = () => {
685 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
686 }
dfdcbb94
P
687 }
688
3d9a63d3
C
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
c894a1ea 699 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
089af69b
C
700 if (typeof TextEncoder === 'undefined') {
701 mode = 'webtorrent'
702 }
703
3d9a63d3
C
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
a5cf76af
C
721 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
722 if (!this.liveVideosSub) {
a800dbf3 723 this.liveVideosSub = this.buildLiveEventsSubscription()
a5cf76af
C
724 }
725
726 if (oldVideo && oldVideo.id !== newVideo.id) {
98ab5dc8 727 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
a5cf76af
C
728 }
729
730 if (!newVideo.isLive) return
731
732 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
733 }
734
a800dbf3
C
735 private buildLiveEventsSubscription () {
736 return this.peertubeSocket.getLiveVideosObservable()
737 .subscribe(({ type, payload }) => {
738 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
51353d9a 739 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
a800dbf3
C
740 })
741 }
742
743 private handleLiveStateChange (newState: VideoState) {
744 if (newState !== VideoState.PUBLISHED) return
745
42b40636 746 logger.info('Loading video after live update.')
a800dbf3
C
747
748 const videoUUID = this.video.uuid
749
c894a1ea 750 // Reset to force refresh the video
a800dbf3
C
751 this.video = undefined
752 this.loadVideo(videoUUID)
753 }
754
51353d9a 755 private handleLiveViewsChange (newViewers: number) {
a800dbf3 756 if (!this.video) {
42b40636 757 logger.error('Cannot update video live views because video is no defined.')
a800dbf3
C
758 return
759 }
760
42b40636 761 logger.info('Updating live views.')
e43b5a3f 762
51353d9a 763 this.video.viewers = newViewers
a800dbf3
C
764 }
765
941c5eac
C
766 private initHotkeys () {
767 this.hotkeys = [
941c5eac 768 // These hotkeys are managed by the player
fc3412fd
C
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`),
941c5eac 772
fc3412fd 773 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
941c5eac 774
fc3412fd
C
775 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
776 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
941c5eac 777
fc3412fd
C
778 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
779 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
941c5eac 780
fc3412fd
C
781 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
782 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
941c5eac 783
fc3412fd
C
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`)
941c5eac 791 ]
3d216ea0
C
792
793 if (this.isUserLoggedIn()) {
794 this.hotkeys = this.hotkeys.concat([
3d216ea0 795 new Hotkey('shift+s', () => {
9df52d66
C
796 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
797 else this.subscribeButton.subscribe()
77d873c5 798
3d216ea0 799 return false
66357162 800 }, undefined, $localize`Subscribe to the account`)
3d216ea0
C
801 ])
802 }
803
804 this.hotkeysService.add(this.hotkeys)
941c5eac 805 }
c894a1ea
C
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 }
dc8bc31b 827}