]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/+videos/+video-watch/video-watch.component.ts
Don't stuck state when move transcoding job failed
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-watch / video-watch.component.ts
CommitLineData
67ed6552 1import { Hotkey, HotkeysService } from 'angular2-hotkeys'
6ea59f41 2import { forkJoin, Subscription } from 'rxjs'
a9bfa85d 3import { isP2PEnabled } from 'src/assets/player/utils'
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'
67ed6552
C
23import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
24import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
25import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
15a7eafb 26import { timeToInt } from '@shared/core-utils'
c0e8b12e
C
27import {
28 HTMLServerConfig,
29 HttpStatusCode,
30 PeerTubeProblemDocument,
31 ServerErrorCode,
32 VideoCaption,
33 VideoPrivacy,
34 VideoState
35} from '@shared/models'
6ebdd12f 36import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage'
6ec0b75b 37import {
5efab546 38 CustomizationOptions,
6ec0b75b
C
39 P2PMediaLoaderOptions,
40 PeertubePlayerManager,
41 PeertubePlayerManagerOptions,
67ed6552
C
42 PlayerMode,
43 videojs
6ec0b75b 44} from '../../../assets/player/peertube-player-manager'
67ed6552 45import { environment } from '../../../environments/environment'
911186da 46import { VideoWatchPlaylistComponent } from './shared'
dc8bc31b 47
a5cf76af
C
48type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
49
dc8bc31b
C
50@Component({
51 selector: 'my-video-watch',
ec8d8440
C
52 templateUrl: './video-watch.component.html',
53 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 54})
0629423c 55export class VideoWatchComponent implements OnInit, OnDestroy {
f36da21e 56 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
2f5d2ec5 57 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
df98563e 58
2adfc7ea 59 player: any
0826c92d 60 playerElement: HTMLVideoElement
c15d61f5 61 playerPlaceholderImgSrc: string
c894a1ea 62 theaterEnabled = false
2de96f4d 63
2f4c784a
C
64 video: VideoDetails = null
65 videoCaptions: VideoCaption[] = []
66
d142c7b9 67 playlistPosition: number
e2f01c47 68 playlist: VideoPlaylist = null
e2f01c47 69
6d88de72 70 remoteServerDown = false
c15d61f5 71
c894a1ea 72 private nextVideoUUID = ''
3bcb4fd7 73 private nextVideoTitle = ''
c894a1ea 74
f0a39880 75 private currentTime: number
c894a1ea 76
df98563e 77 private paramsSub: Subscription
e2f01c47 78 private queryParamsSub: Subscription
31b6ddf8 79 private configSub: Subscription
a5cf76af 80 private liveVideosSub: Subscription
df98563e 81
2989628b 82 private serverConfig: HTMLServerConfig
ba430d75 83
6ea59f41
C
84 private hotkeys: Hotkey[] = []
85
df98563e 86 constructor (
4fd8aa32 87 private elementRef: ElementRef,
0629423c 88 private route: ActivatedRoute,
92fb909c 89 private router: Router,
d3ef341a 90 private videoService: VideoService,
e2f01c47 91 private playlistService: VideoPlaylistService,
92fb909c 92 private confirmService: ConfirmService,
3ec343a4 93 private metaService: MetaService,
7ddd02c9 94 private authService: AuthService,
d3217560 95 private userService: UserService,
0883b324 96 private serverService: ServerService,
a51bad1a 97 private restExtractor: RestExtractor,
f8b2c1b4 98 private notifier: Notifier,
901637bb 99 private zone: NgZone,
16f7022b 100 private videoCaptionService: VideoCaptionService,
20d21199 101 private hotkeysService: HotkeysService,
93cae479 102 private hooks: HooksService,
72f611ca 103 private pluginService: PluginService,
a5cf76af 104 private peertubeSocket: PeerTubeSocket,
2666fd7c 105 private screenService: ScreenService,
60c2bc80 106 private location: PlatformLocation,
e945b184 107 @Inject(LOCALE_ID) private localeId: string
2666fd7c 108 ) { }
dc8bc31b 109
b2731bff
C
110 get user () {
111 return this.authService.getUser()
112 }
113
d3217560
RK
114 get anonymousUser () {
115 return this.userService.getAnonymousUser()
116 }
117
98ab5dc8 118 ngOnInit () {
6ebdd12f
C
119 this.serverConfig = this.serverService.getHTMLConfig()
120
1a568b6f
C
121 PeertubePlayerManager.initState()
122
c894a1ea
C
123 this.loadRouteParams()
124 this.loadRouteQuery()
20d21199 125
1c8ddbfa 126 this.initHotkeys()
011e1e6b
C
127
128 this.theaterEnabled = getStoredTheater()
18a6f04c 129
c9e3eeed 130 this.hooks.runAction('action:video-watch.init', 'video-watch')
58b9ce30 131
132 setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI
d1992b93
C
133 }
134
df98563e 135 ngOnDestroy () {
09edde40 136 this.flushPlayer()
067e3f84 137
13fc89f4 138 // Unsubscribe subscriptions
e2f01c47
C
139 if (this.paramsSub) this.paramsSub.unsubscribe()
140 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
5abc96fc 141 if (this.configSub) this.configSub.unsubscribe()
a5cf76af 142 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
20d21199
RK
143
144 // Unbind hotkeys
3d216ea0 145 this.hotkeysService.remove(this.hotkeys)
dc8bc31b 146 }
98b01bac 147
06a55579
C
148 getCurrentTime () {
149 return this.currentTime
6863f814
RK
150 }
151
06a55579
C
152 getCurrentPlaylistPosition () {
153 return this.videoWatchPlaylist.currentPlaylistPosition
99cc4f49
C
154 }
155
6aa54148 156 onRecommendations (videos: Video[]) {
c894a1ea 157 if (videos.length === 0) return
6aa54148 158
c894a1ea
C
159 // The recommended videos's first element should be the next video
160 const video = videos[0]
161 this.nextVideoUUID = video.uuid
162 this.nextVideoTitle = video.name
b29bf61d
RK
163 }
164
165 handleTimestampClicked (timestamp: number) {
18429d01
C
166 if (!this.player || this.video.isLive) return
167
168 this.player.currentTime(timestamp)
b29bf61d 169 scrollToTop()
706c5a47
RK
170 }
171
c894a1ea
C
172 onPlaylistVideoFound (videoId: string) {
173 this.loadVideo(videoId)
174 }
175
176 isUserLoggedIn () {
177 return this.authService.isLoggedIn()
178 }
179
180 isVideoBlur (video: Video) {
181 return video.isVideoNSFWForUser(this.user, this.serverConfig)
706c5a47
RK
182 }
183
b40a2193
K
184 isChannelDisplayNameGeneric () {
185 const genericChannelDisplayName = [
186 `Main ${this.video.channel.ownerAccount.name} channel`,
187 `Default ${this.video.channel.ownerAccount.name} channel`
188 ]
189
190 return genericChannelDisplayName.includes(this.video.channel.displayName)
191 }
192
0f7407d9
C
193 displayOtherVideosAsRow () {
194 // Use the same value as in the SASS file
195 return this.screenService.getWindowInnerWidth() <= 1100
196 }
197
c894a1ea
C
198 private loadRouteParams () {
199 this.paramsSub = this.route.params.subscribe(routeParams => {
9df52d66 200 const videoId = routeParams['videoId']
c894a1ea
C
201 if (videoId) return this.loadVideo(videoId)
202
9df52d66 203 const playlistId = routeParams['playlistId']
c894a1ea
C
204 if (playlistId) return this.loadPlaylist(playlistId)
205 })
206 }
207
208 private loadRouteQuery () {
209 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
210 // Handle the ?playlistPosition
9df52d66 211 const positionParam = queryParams['playlistPosition'] ?? 1
c894a1ea
C
212
213 this.playlistPosition = positionParam === 'last'
214 ? -1 // Handle the "last" index
215 : parseInt(positionParam + '', 10)
216
217 if (isNaN(this.playlistPosition)) {
218 console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`)
219 this.playlistPosition = 1
220 }
221
222 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
223
9df52d66 224 const start = queryParams['start']
c894a1ea
C
225 if (this.player && start) this.player.currentTime(parseInt(start, 10))
226 })
227 }
228
e2f01c47 229 private loadVideo (videoId: string) {
c894a1ea 230 if (this.isSameElement(this.video, videoId)) return
e2f01c47
C
231
232 if (this.player) this.player.pause()
233
93cae479
C
234 const videoObs = this.hooks.wrapObsFun(
235 this.videoService.getVideo.bind(this.videoService),
236 { videoId },
237 'video-watch',
238 'filter:api.video-watch.video.get.params',
239 'filter:api.video-watch.video.get.result'
240 )
241
a9bfa85d
C
242 forkJoin([
243 videoObs,
244 this.videoCaptionService.listCaptions(videoId),
245 this.userService.getAnonymousOrLoggedUser()
246 ]).subscribe({
247 next: ([ video, captionsResult, loggedInOrAnonymousUser ]) => {
248 const queryParams = this.route.snapshot.queryParams
e6abf95e 249
a9bfa85d
C
250 const urlOptions = {
251 resume: queryParams.resume,
e2f01c47 252
a9bfa85d
C
253 startTime: queryParams.start,
254 stopTime: queryParams.stop,
3c6a44a1 255
a9bfa85d
C
256 muted: queryParams.muted,
257 loop: queryParams.loop,
258 subtitle: queryParams.subtitle,
5efab546 259
a9bfa85d
C
260 playerMode: queryParams.mode,
261 peertubeLink: false
262 }
5efab546 263
a9bfa85d
C
264 this.onVideoFetched({ video, videoCaptions: captionsResult.data, loggedInOrAnonymousUser, urlOptions })
265 .catch(err => this.handleGlobalError(err))
266 },
4c72c1cd 267
a9bfa85d
C
268 error: err => this.handleRequestError(err)
269 })
e2f01c47
C
270 }
271
272 private loadPlaylist (playlistId: string) {
c894a1ea 273 if (this.isSameElement(this.playlist, playlistId)) return
e2f01c47
C
274
275 this.playlistService.getVideoPlaylist(playlistId)
1378c0d3
C
276 .subscribe({
277 next: playlist => {
c894a1ea
C
278 this.playlist = playlist
279
280 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
281 },
282
1378c0d3
C
283 error: err => this.handleRequestError(err)
284 })
c894a1ea 285 }
e2f01c47 286
c894a1ea
C
287 private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) {
288 if (!element) return false
289
290 return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId
291 }
292
293 private async handleRequestError (err: any) {
294 const errorBody = err.body as PeerTubeProblemDocument
295
231ff4af 296 if (errorBody?.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) {
c894a1ea
C
297 const originUrl = errorBody.originUrl + (window.location.search ?? '')
298
299 const res = await this.confirmService.confirm(
9df52d66 300 // eslint-disable-next-line max-len
c894a1ea
C
301 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
302 $localize`Redirection`
303 )
304
305 if (res === true) return window.location.href = originUrl
306 }
307
308 // If 400, 403 or 404, the video is private or blocked so redirect to 404
309 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
310 HttpStatusCode.BAD_REQUEST_400,
311 HttpStatusCode.FORBIDDEN_403,
312 HttpStatusCode.NOT_FOUND_404
313 ])
e2f01c47
C
314 }
315
c894a1ea 316 private handleGlobalError (err: any) {
0c31c33d 317 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
318 if (!errorMessage) return
319
6d88de72 320 // Display a message in the video player instead of a notification
9df52d66 321 if (errorMessage.includes('from xs param')) {
6d88de72
C
322 this.flushPlayer()
323 this.remoteServerDown = true
3b492bff 324
6d88de72 325 return
0c31c33d
C
326 }
327
f8b2c1b4 328 this.notifier.error(errorMessage)
0c31c33d
C
329 }
330
a9bfa85d
C
331 private async onVideoFetched (options: {
332 video: VideoDetails
333 videoCaptions: VideoCaption[]
a5cf76af 334 urlOptions: URLOptions
a9bfa85d
C
335 loggedInOrAnonymousUser: User
336 }) {
337 const { video, videoCaptions, urlOptions, loggedInOrAnonymousUser } = options
338
a5cf76af
C
339 this.subscribeToLiveEventsIfNeeded(this.video, video)
340
df98563e 341 this.video = video
2f4c784a 342 this.videoCaptions = videoCaptions
92fb909c 343
c448d412 344 // Re init attributes
c15d61f5 345 this.playerPlaceholderImgSrc = undefined
6d88de72 346 this.remoteServerDown = false
f0a39880 347 this.currentTime = undefined
c448d412 348
e2f01c47 349 if (this.isVideoBlur(this.video)) {
22b59e80 350 const res = await this.confirmService.confirm(
66357162
C
351 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
352 $localize`Mature or explicit content`
d6e32a2e 353 )
60c2bc80 354 if (res === false) return this.location.back()
92fb909c
C
355 }
356
a9bfa85d 357 this.buildPlayer(urlOptions, loggedInOrAnonymousUser)
0a6817f0
C
358 .catch(err => console.error('Cannot build the player', err))
359
0a6817f0 360 this.setOpenGraphTags()
0a6817f0 361
55b84d53
C
362 const hookOptions = {
363 videojs,
364 video: this.video,
365 playlist: this.playlist
366 }
367 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
0a6817f0
C
368 }
369
a9bfa85d 370 private async buildPlayer (urlOptions: URLOptions, loggedInOrAnonymousUser: User) {
09edde40
C
371 // Flush old player if needed
372 this.flushPlayer()
b891f9bc 373
c15d61f5
C
374 const videoState = this.video.state.id
375 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
376 this.playerPlaceholderImgSrc = this.video.previewPath
377 return
378 }
379
60c2bc80 380 // Build video element, because videojs removes it on dispose
e2f01c47 381 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
382 this.playerElement = document.createElement('video')
383 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 384 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
385 playerElementWrapper.appendChild(this.playerElement)
386
3d9a63d3
C
387 const params = {
388 video: this.video,
0a6817f0 389 videoCaptions: this.videoCaptions,
3d9a63d3 390 urlOptions,
a9bfa85d 391 loggedInOrAnonymousUser,
3d9a63d3 392 user: this.user
e945b184 393 }
3d9a63d3
C
394 const { playerMode, playerOptions } = await this.hooks.wrapFun(
395 this.buildPlayerManagerOptions.bind(this),
396 params,
c2023a9f
C
397 'video-watch',
398 'filter:internal.video-watch.player.build-options.params',
3d9a63d3
C
399 'filter:internal.video-watch.player.build-options.result'
400 )
e945b184 401
e945b184 402 this.zone.runOutsideAngular(async () => {
3d9a63d3 403 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
9a18a625 404
c894a1ea
C
405 this.player.on('customError', ({ err }: { err: any }) => {
406 this.zone.run(() => this.handleGlobalError(err))
407 })
f0a39880
C
408
409 this.player.on('timeupdate', () => {
c894a1ea 410 // Don't need to trigger angular change for this variable, that is sent to children components on click
f0a39880
C
411 this.currentTime = Math.floor(this.player.currentTime())
412 })
e2f01c47 413
3bcb4fd7 414 /**
c894a1ea
C
415 * condition: true to make the upnext functionality trigger, false to disable the upnext functionality
416 * go to the next video in 'condition()' if you don't want of the timer.
417 * next: function triggered at the end of the timer.
418 * suspended: function used at each click of the timer checking if we need to reset progress
419 * and wait until suspended becomes truthy again.
3bcb4fd7
RK
420 */
421 this.player.upnext({
c894a1ea
C
422 timeout: 5000, // 5s
423
66357162
C
424 headText: $localize`Up Next`,
425 cancelText: $localize`Cancel`,
426 suspendedText: $localize`Autoplay is suspended`,
c894a1ea 427
3bcb4fd7 428 getTitle: () => this.nextVideoTitle,
c894a1ea
C
429
430 next: () => this.zone.run(() => this.playNextVideoInAngularZone()),
3bcb4fd7 431 condition: () => {
c894a1ea
C
432 if (!this.playlist) return this.isAutoPlayNext()
433
434 // Don't wait timeout to play the next playlist video
435 if (this.isPlaylistAutoPlayNext()) {
436 this.playNextVideoInAngularZone()
437 return undefined
3bcb4fd7 438 }
c894a1ea
C
439
440 return false
223b24e6 441 },
c894a1ea 442
223b24e6
RK
443 suspended: () => {
444 return (
445 !isXPercentInViewport(this.player.el(), 80) ||
446 !document.getElementById('content').contains(document.activeElement)
447 )
e2f01c47
C
448 }
449 })
450
451 this.player.one('stopped', () => {
c894a1ea
C
452 if (this.playlist && this.isPlaylistAutoPlayNext()) {
453 this.playNextVideoInAngularZone()
e2f01c47
C
454 }
455 })
9a18a625 456
e772bdf1
C
457 this.player.one('ended', () => {
458 if (this.video.isLive) {
ceb8f322 459 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
e772bdf1
C
460 }
461 })
462
9a18a625
C
463 this.player.on('theaterChange', (_: any, enabled: boolean) => {
464 this.zone.run(() => this.theaterEnabled = enabled)
465 })
5f85f8aa 466
c3bb0441 467 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', {
468 player: this.player,
469 playlist: this.playlist,
470 playlistPosition: this.playlistPosition,
471 videojs,
472 video: this.video
473 })
b891f9bc 474 })
92fb909c
C
475 }
476
c894a1ea 477 private playNextVideoInAngularZone () {
6dd873d6
RK
478 if (this.playlist) {
479 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
c894a1ea 480 return
6aa54148 481 }
3ec343a4 482
c894a1ea
C
483 if (this.nextVideoUUID) {
484 this.router.navigate([ '/w', this.nextVideoUUID ])
c894a1ea 485 }
3ec343a4 486 }
1f3e9fec 487
d4c6a3b9 488 private isAutoplay () {
bf079b7b
C
489 // We'll jump to the thread id, so do not play the video
490 if (this.route.snapshot.params['threadId']) return false
491
492 // Otherwise true by default
d4c6a3b9
C
493 if (!this.user) return true
494
495 // Be sure the autoPlay is set to false
496 return this.user.autoPlayVideo !== false
497 }
09edde40 498
c894a1ea
C
499 private isAutoPlayNext () {
500 return (
9df52d66 501 (this.user?.autoPlayNextVideo) ||
c894a1ea
C
502 this.anonymousUser.autoPlayNextVideo
503 )
504 }
505
506 private isPlaylistAutoPlayNext () {
507 return (
9df52d66 508 (this.user?.autoPlayNextVideoPlaylist) ||
c894a1ea
C
509 this.anonymousUser.autoPlayNextVideoPlaylist
510 )
511 }
512
09edde40
C
513 private flushPlayer () {
514 // Remove player if it exists
d4a8e7a6
C
515 if (!this.player) return
516
517 try {
518 this.player.dispose()
519 this.player = undefined
520 } catch (err) {
521 console.error('Cannot dispose player.', err)
09edde40
C
522 }
523 }
1c8ddbfa 524
3d9a63d3 525 private buildPlayerManagerOptions (params: {
9df52d66
C
526 video: VideoDetails
527 videoCaptions: VideoCaption[]
528 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
a9bfa85d 529 loggedInOrAnonymousUser: User
3d9a63d3
C
530 user?: AuthUser
531 }) {
a9bfa85d 532 const { video, videoCaptions, urlOptions, loggedInOrAnonymousUser, user } = params
c894a1ea 533
706c5a47
RK
534 const getStartTime = () => {
535 const byUrl = urlOptions.startTime !== undefined
96f6278f 536 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
58b9ce30 537 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
706c5a47 538
3c6a44a1
C
539 if (byUrl) return timeToInt(urlOptions.startTime)
540 if (byHistory) return video.userHistory.currentTime
58b9ce30 541 if (byLocalStorage) return byLocalStorage.duration
3c6a44a1
C
542
543 return 0
706c5a47 544 }
3d9a63d3 545
706c5a47 546 let startTime = getStartTime()
3c6a44a1 547
3d9a63d3
C
548 // If we are at the end of the video, reset the timer
549 if (video.duration - startTime <= 1) startTime = 0
550
551 const playerCaptions = videoCaptions.map(c => ({
552 label: c.language.label,
553 language: c.language.id,
554 src: environment.apiUrl + c.captionPath
555 }))
556
557 const options: PeertubePlayerManagerOptions = {
558 common: {
559 autoplay: this.isAutoplay(),
a9bfa85d
C
560 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
561
c894a1ea 562 nextVideo: () => this.playNextVideoInAngularZone(),
3d9a63d3
C
563
564 playerElement: this.playerElement,
565 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
566
567 videoDuration: video.duration,
568 enableHotkeys: true,
569 inactivityTimeout: 2500,
570 poster: video.previewUrl,
571
572 startTime,
573 stopTime: urlOptions.stopTime,
574 controls: urlOptions.controls,
575 muted: urlOptions.muted,
576 loop: urlOptions.loop,
577 subtitle: urlOptions.subtitle,
578
579 peertubeLink: urlOptions.peertubeLink,
580
581 theaterButton: true,
582 captions: videoCaptions.length !== 0,
583
584 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
585 ? this.videoService.getVideoViewUrl(video.uuid)
586 : null,
587 embedUrl: video.embedUrl,
4097c6d6 588 embedTitle: video.name,
3d9a63d3 589
25b7c847
C
590 isLive: video.isLive,
591
3d9a63d3
C
592 language: this.localeId,
593
9df52d66
C
594 userWatching: user && user.videosHistoryEnabled === true
595 ? {
596 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
597 authorizationHeader: this.authService.getRequestHeaderValue()
598 }
599 : undefined,
3d9a63d3
C
600
601 serverUrl: environment.apiUrl,
602
58b9ce30 603 videoCaptions: playerCaptions,
604
9162fdd3 605 videoShortUUID: video.shortUUID,
3e0e8d4a 606 videoUUID: video.uuid
3d9a63d3
C
607 },
608
609 webtorrent: {
610 videoFiles: video.files
72f611ca 611 },
612
613 pluginsManager: this.pluginService.getPluginsManager()
3d9a63d3
C
614 }
615
dfdcbb94 616 // Only set this if we're in a playlist
5bb2ed6b
P
617 if (this.playlist) {
618 options.common.previousVideo = () => {
619 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
620 }
dfdcbb94
P
621 }
622
3d9a63d3
C
623 let mode: PlayerMode
624
625 if (urlOptions.playerMode) {
626 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
627 else mode = 'webtorrent'
628 } else {
629 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
630 else mode = 'webtorrent'
631 }
632
c894a1ea 633 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
089af69b
C
634 if (typeof TextEncoder === 'undefined') {
635 mode = 'webtorrent'
636 }
637
3d9a63d3
C
638 if (mode === 'p2p-media-loader') {
639 const hlsPlaylist = video.getHlsPlaylist()
640
641 const p2pMediaLoader = {
642 playlistUrl: hlsPlaylist.playlistUrl,
643 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
644 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
645 trackerAnnounce: video.trackerUrls,
646 videoFiles: hlsPlaylist.files
647 } as P2PMediaLoaderOptions
648
649 Object.assign(options, { p2pMediaLoader })
650 }
651
652 return { playerMode: mode, playerOptions: options }
653 }
654
a5cf76af
C
655 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
656 if (!this.liveVideosSub) {
a800dbf3 657 this.liveVideosSub = this.buildLiveEventsSubscription()
a5cf76af
C
658 }
659
660 if (oldVideo && oldVideo.id !== newVideo.id) {
98ab5dc8 661 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
a5cf76af
C
662 }
663
664 if (!newVideo.isLive) return
665
666 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
667 }
668
a800dbf3
C
669 private buildLiveEventsSubscription () {
670 return this.peertubeSocket.getLiveVideosObservable()
671 .subscribe(({ type, payload }) => {
672 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
51353d9a 673 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
a800dbf3
C
674 })
675 }
676
677 private handleLiveStateChange (newState: VideoState) {
678 if (newState !== VideoState.PUBLISHED) return
679
680 const videoState = this.video.state.id
681 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
682
683 console.log('Loading video after live update.')
684
685 const videoUUID = this.video.uuid
686
c894a1ea 687 // Reset to force refresh the video
a800dbf3
C
688 this.video = undefined
689 this.loadVideo(videoUUID)
690 }
691
51353d9a 692 private handleLiveViewsChange (newViewers: number) {
a800dbf3
C
693 if (!this.video) {
694 console.error('Cannot update video live views because video is no defined.')
695 return
696 }
697
e43b5a3f
C
698 console.log('Updating live views.')
699
51353d9a 700 this.video.viewers = newViewers
a800dbf3
C
701 }
702
941c5eac
C
703 private initHotkeys () {
704 this.hotkeys = [
941c5eac 705 // These hotkeys are managed by the player
66357162
C
706 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
707 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
708 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
941c5eac 709
66357162 710 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90% (requires player focus)`),
941c5eac 711
66357162
C
712 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
713 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
941c5eac 714
66357162
C
715 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
716 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
941c5eac 717
66357162
C
718 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
719 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
941c5eac 720
66357162 721 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
941c5eac 722 ]
3d216ea0
C
723
724 if (this.isUserLoggedIn()) {
725 this.hotkeys = this.hotkeys.concat([
3d216ea0 726 new Hotkey('shift+s', () => {
9df52d66
C
727 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
728 else this.subscribeButton.subscribe()
77d873c5 729
3d216ea0 730 return false
66357162 731 }, undefined, $localize`Subscribe to the account`)
3d216ea0
C
732 ])
733 }
734
735 this.hotkeysService.add(this.hotkeys)
941c5eac 736 }
c894a1ea
C
737
738 private setOpenGraphTags () {
739 this.metaService.setTitle(this.video.name)
740
741 this.metaService.setTag('og:type', 'video')
742
743 this.metaService.setTag('og:title', this.video.name)
744 this.metaService.setTag('name', this.video.name)
745
746 this.metaService.setTag('og:description', this.video.description)
747 this.metaService.setTag('description', this.video.description)
748
749 this.metaService.setTag('og:image', this.video.previewPath)
750
751 this.metaService.setTag('og:duration', this.video.duration.toString())
752
753 this.metaService.setTag('og:site_name', 'PeerTube')
754
755 this.metaService.setTag('og:url', window.location.href)
756 this.metaService.setTag('url', window.location.href)
757 }
dc8bc31b 758}