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