]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/+videos/+video-watch/video-watch.component.ts
Merge branch 'release/4.1.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'
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'
6ec0b75b 36import {
5efab546 37 CustomizationOptions,
6ec0b75b
C
38 P2PMediaLoaderOptions,
39 PeertubePlayerManager,
40 PeertubePlayerManagerOptions,
67ed6552
C
41 PlayerMode,
42 videojs
c4207f97
C
43} from '../../../assets/player'
44import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage'
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
a5a79d15
C
477 private hasNextVideo () {
478 if (this.playlist) {
479 return this.videoWatchPlaylist.hasNextVideo()
480 }
481
482 return true
483 }
484
c894a1ea 485 private playNextVideoInAngularZone () {
6dd873d6
RK
486 if (this.playlist) {
487 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
c894a1ea 488 return
6aa54148 489 }
3ec343a4 490
c894a1ea
C
491 if (this.nextVideoUUID) {
492 this.router.navigate([ '/w', this.nextVideoUUID ])
c894a1ea 493 }
3ec343a4 494 }
1f3e9fec 495
d4c6a3b9 496 private isAutoplay () {
bf079b7b
C
497 // We'll jump to the thread id, so do not play the video
498 if (this.route.snapshot.params['threadId']) return false
499
500 // Otherwise true by default
d4c6a3b9
C
501 if (!this.user) return true
502
503 // Be sure the autoPlay is set to false
504 return this.user.autoPlayVideo !== false
505 }
09edde40 506
c894a1ea
C
507 private isAutoPlayNext () {
508 return (
9df52d66 509 (this.user?.autoPlayNextVideo) ||
c894a1ea
C
510 this.anonymousUser.autoPlayNextVideo
511 )
512 }
513
514 private isPlaylistAutoPlayNext () {
515 return (
9df52d66 516 (this.user?.autoPlayNextVideoPlaylist) ||
c894a1ea
C
517 this.anonymousUser.autoPlayNextVideoPlaylist
518 )
519 }
520
09edde40
C
521 private flushPlayer () {
522 // Remove player if it exists
d4a8e7a6
C
523 if (!this.player) return
524
525 try {
526 this.player.dispose()
527 this.player = undefined
528 } catch (err) {
529 console.error('Cannot dispose player.', err)
09edde40
C
530 }
531 }
1c8ddbfa 532
3d9a63d3 533 private buildPlayerManagerOptions (params: {
9df52d66
C
534 video: VideoDetails
535 videoCaptions: VideoCaption[]
536 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
a9bfa85d 537 loggedInOrAnonymousUser: User
3d9a63d3
C
538 user?: AuthUser
539 }) {
a9bfa85d 540 const { video, videoCaptions, urlOptions, loggedInOrAnonymousUser, user } = params
c894a1ea 541
706c5a47
RK
542 const getStartTime = () => {
543 const byUrl = urlOptions.startTime !== undefined
96f6278f 544 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
58b9ce30 545 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
706c5a47 546
3c6a44a1
C
547 if (byUrl) return timeToInt(urlOptions.startTime)
548 if (byHistory) return video.userHistory.currentTime
58b9ce30 549 if (byLocalStorage) return byLocalStorage.duration
3c6a44a1
C
550
551 return 0
706c5a47 552 }
3d9a63d3 553
706c5a47 554 let startTime = getStartTime()
3c6a44a1 555
3d9a63d3
C
556 // If we are at the end of the video, reset the timer
557 if (video.duration - startTime <= 1) startTime = 0
558
559 const playerCaptions = videoCaptions.map(c => ({
560 label: c.language.label,
561 language: c.language.id,
562 src: environment.apiUrl + c.captionPath
563 }))
564
565 const options: PeertubePlayerManagerOptions = {
566 common: {
567 autoplay: this.isAutoplay(),
a9bfa85d
C
568 p2pEnabled: isP2PEnabled(video, this.serverConfig, loggedInOrAnonymousUser.p2pEnabled),
569
a5a79d15 570 hasNextVideo: () => this.hasNextVideo(),
c894a1ea 571 nextVideo: () => this.playNextVideoInAngularZone(),
3d9a63d3
C
572
573 playerElement: this.playerElement,
574 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
575
576 videoDuration: video.duration,
577 enableHotkeys: true,
578 inactivityTimeout: 2500,
579 poster: video.previewUrl,
580
581 startTime,
582 stopTime: urlOptions.stopTime,
583 controls: urlOptions.controls,
584 muted: urlOptions.muted,
585 loop: urlOptions.loop,
586 subtitle: urlOptions.subtitle,
587
588 peertubeLink: urlOptions.peertubeLink,
589
590 theaterButton: true,
591 captions: videoCaptions.length !== 0,
592
593 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
594 ? this.videoService.getVideoViewUrl(video.uuid)
595 : null,
596 embedUrl: video.embedUrl,
4097c6d6 597 embedTitle: video.name,
3d9a63d3 598
25b7c847
C
599 isLive: video.isLive,
600
3d9a63d3
C
601 language: this.localeId,
602
9df52d66
C
603 userWatching: user && user.videosHistoryEnabled === true
604 ? {
605 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
606 authorizationHeader: this.authService.getRequestHeaderValue()
607 }
608 : undefined,
3d9a63d3
C
609
610 serverUrl: environment.apiUrl,
611
58b9ce30 612 videoCaptions: playerCaptions,
613
9162fdd3 614 videoShortUUID: video.shortUUID,
c4207f97
C
615 videoUUID: video.uuid,
616
617 errorNotifier: (message: string) => this.notifier.error(message)
3d9a63d3
C
618 },
619
620 webtorrent: {
621 videoFiles: video.files
72f611ca 622 },
623
624 pluginsManager: this.pluginService.getPluginsManager()
3d9a63d3
C
625 }
626
dfdcbb94 627 // Only set this if we're in a playlist
5bb2ed6b 628 if (this.playlist) {
a5a79d15
C
629 options.common.hasPreviousVideo = () => this.videoWatchPlaylist.hasPreviousVideo()
630
5bb2ed6b
P
631 options.common.previousVideo = () => {
632 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
633 }
dfdcbb94
P
634 }
635
3d9a63d3
C
636 let mode: PlayerMode
637
638 if (urlOptions.playerMode) {
639 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
640 else mode = 'webtorrent'
641 } else {
642 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
643 else mode = 'webtorrent'
644 }
645
c894a1ea 646 // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available
089af69b
C
647 if (typeof TextEncoder === 'undefined') {
648 mode = 'webtorrent'
649 }
650
3d9a63d3
C
651 if (mode === 'p2p-media-loader') {
652 const hlsPlaylist = video.getHlsPlaylist()
653
654 const p2pMediaLoader = {
655 playlistUrl: hlsPlaylist.playlistUrl,
656 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
657 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
658 trackerAnnounce: video.trackerUrls,
659 videoFiles: hlsPlaylist.files
660 } as P2PMediaLoaderOptions
661
662 Object.assign(options, { p2pMediaLoader })
663 }
664
665 return { playerMode: mode, playerOptions: options }
666 }
667
a5cf76af
C
668 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
669 if (!this.liveVideosSub) {
a800dbf3 670 this.liveVideosSub = this.buildLiveEventsSubscription()
a5cf76af
C
671 }
672
673 if (oldVideo && oldVideo.id !== newVideo.id) {
98ab5dc8 674 this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
a5cf76af
C
675 }
676
677 if (!newVideo.isLive) return
678
679 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
680 }
681
a800dbf3
C
682 private buildLiveEventsSubscription () {
683 return this.peertubeSocket.getLiveVideosObservable()
684 .subscribe(({ type, payload }) => {
685 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
51353d9a 686 if (type === 'views-change') return this.handleLiveViewsChange(payload.viewers)
a800dbf3
C
687 })
688 }
689
690 private handleLiveStateChange (newState: VideoState) {
691 if (newState !== VideoState.PUBLISHED) return
692
a800dbf3
C
693 console.log('Loading video after live update.')
694
695 const videoUUID = this.video.uuid
696
c894a1ea 697 // Reset to force refresh the video
a800dbf3
C
698 this.video = undefined
699 this.loadVideo(videoUUID)
700 }
701
51353d9a 702 private handleLiveViewsChange (newViewers: number) {
a800dbf3
C
703 if (!this.video) {
704 console.error('Cannot update video live views because video is no defined.')
705 return
706 }
707
e43b5a3f
C
708 console.log('Updating live views.')
709
51353d9a 710 this.video.viewers = newViewers
a800dbf3
C
711 }
712
941c5eac
C
713 private initHotkeys () {
714 this.hotkeys = [
941c5eac 715 // These hotkeys are managed by the player
fc3412fd
C
716 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen`),
717 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video`),
718 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video`),
941c5eac 719
fc3412fd 720 new Hotkey('0-9', e => e, undefined, $localize`Skip to a percentage of the video: 0 is 0% and 9 is 90%`),
941c5eac 721
fc3412fd
C
722 new Hotkey('up', e => e, undefined, $localize`Increase the volume`),
723 new Hotkey('down', e => e, undefined, $localize`Decrease the volume`),
941c5eac 724
fc3412fd
C
725 new Hotkey('right', e => e, undefined, $localize`Seek the video forward`),
726 new Hotkey('left', e => e, undefined, $localize`Seek the video backward`),
941c5eac 727
fc3412fd
C
728 new Hotkey('>', e => e, undefined, $localize`Increase playback rate`),
729 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate`),
941c5eac 730
fc3412fd
C
731 new Hotkey(',', e => e, undefined, $localize`Navigate in the video to the previous frame`),
732 new Hotkey('.', e => e, undefined, $localize`Navigate in the video to the next frame`),
733
734 new Hotkey('t', e => {
735 this.theaterEnabled = !this.theaterEnabled
736 return false
737 }, undefined, $localize`Toggle theater mode`)
941c5eac 738 ]
3d216ea0
C
739
740 if (this.isUserLoggedIn()) {
741 this.hotkeys = this.hotkeys.concat([
3d216ea0 742 new Hotkey('shift+s', () => {
9df52d66
C
743 if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe()
744 else this.subscribeButton.subscribe()
77d873c5 745
3d216ea0 746 return false
66357162 747 }, undefined, $localize`Subscribe to the account`)
3d216ea0
C
748 ])
749 }
750
751 this.hotkeysService.add(this.hotkeys)
941c5eac 752 }
c894a1ea
C
753
754 private setOpenGraphTags () {
755 this.metaService.setTitle(this.video.name)
756
757 this.metaService.setTag('og:type', 'video')
758
759 this.metaService.setTag('og:title', this.video.name)
760 this.metaService.setTag('name', this.video.name)
761
762 this.metaService.setTag('og:description', this.video.description)
763 this.metaService.setTag('description', this.video.description)
764
765 this.metaService.setTag('og:image', this.video.previewPath)
766
767 this.metaService.setTag('og:duration', this.video.duration.toString())
768
769 this.metaService.setTag('og:site_name', 'PeerTube')
770
771 this.metaService.setTag('og:url', window.location.href)
772 this.metaService.setTag('url', window.location.href)
773 }
dc8bc31b 774}