]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-watch/video-watch.component.ts
Upgrade client dependencies
[github/Chocobozzz/PeerTube.git] / client / src / app / +videos / +video-watch / video-watch.component.ts
1 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
2 import { forkJoin, Observable, Subscription } from 'rxjs'
3 import { catchError } from 'rxjs/operators'
4 import { PlatformLocation } from '@angular/common'
5 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
6 import { ActivatedRoute, Router } from '@angular/router'
7 import {
8 AuthService,
9 AuthUser,
10 ConfirmService,
11 MarkdownService,
12 Notifier,
13 PeerTubeSocket,
14 RestExtractor,
15 ServerService,
16 UserService
17 } from '@app/core'
18 import { HooksService } from '@app/core/plugins/hooks.service'
19 import { RedirectService } from '@app/core/routing/redirect.service'
20 import { isXPercentInViewport, scrollToTop } from '@app/helpers'
21 import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main'
22 import { VideoShareComponent } from '@app/shared/shared-share-modal'
23 import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription'
24 import { VideoActionsDisplayType, VideoDownloadComponent } from '@app/shared/shared-video-miniature'
25 import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist'
26 import { MetaService } from '@ngx-meta/core'
27 import { peertubeLocalStorage } from '@root-helpers/peertube-web-storage'
28 import { ServerConfig, ServerErrorCode, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '@shared/models'
29 import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
30 import {
31 CustomizationOptions,
32 P2PMediaLoaderOptions,
33 PeertubePlayerManager,
34 PeertubePlayerManagerOptions,
35 PlayerMode,
36 videojs
37 } from '../../../assets/player/peertube-player-manager'
38 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
39 import { environment } from '../../../environments/environment'
40 import { VideoSupportComponent } from './modal/video-support.component'
41 import { VideoWatchPlaylistComponent } from './video-watch-playlist.component'
42
43 type URLOptions = CustomizationOptions & { playerMode: PlayerMode }
44
45 @Component({
46 selector: 'my-video-watch',
47 templateUrl: './video-watch.component.html',
48 styleUrls: [ './video-watch.component.scss' ]
49 })
50 export class VideoWatchComponent implements OnInit, OnDestroy {
51 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
52
53 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
54 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
55 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
56 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
57 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
58
59 player: any
60 playerElement: HTMLVideoElement
61 theaterEnabled = false
62 userRating: UserVideoRateType = null
63 descriptionLoading = false
64
65 video: VideoDetails = null
66 videoCaptions: VideoCaption[] = []
67
68 playlistPosition: number
69 playlist: VideoPlaylist = null
70
71 completeDescriptionShown = false
72 completeVideoDescription: string
73 shortVideoDescription: string
74 videoHTMLDescription = ''
75 likesBarTooltipText = ''
76 hasAlreadyAcceptedPrivacyConcern = false
77 remoteServerDown = false
78 hotkeys: Hotkey[] = []
79
80 tooltipLike = ''
81 tooltipDislike = ''
82 tooltipSupport = ''
83 tooltipSaveToPlaylist = ''
84
85 videoActionsOptions: VideoActionsDisplayType = {
86 playlist: false,
87 download: true,
88 update: true,
89 blacklist: true,
90 delete: true,
91 report: true,
92 duplicate: true,
93 mute: true,
94 liveInfo: true
95 }
96
97 private nextVideoUuid = ''
98 private nextVideoTitle = ''
99 private currentTime: number
100 private paramsSub: Subscription
101 private queryParamsSub: Subscription
102 private configSub: Subscription
103 private liveVideosSub: Subscription
104
105 private serverConfig: ServerConfig
106
107 constructor (
108 private elementRef: ElementRef,
109 private changeDetector: ChangeDetectorRef,
110 private route: ActivatedRoute,
111 private router: Router,
112 private videoService: VideoService,
113 private playlistService: VideoPlaylistService,
114 private confirmService: ConfirmService,
115 private metaService: MetaService,
116 private authService: AuthService,
117 private userService: UserService,
118 private serverService: ServerService,
119 private restExtractor: RestExtractor,
120 private notifier: Notifier,
121 private markdownService: MarkdownService,
122 private zone: NgZone,
123 private redirectService: RedirectService,
124 private videoCaptionService: VideoCaptionService,
125 private hotkeysService: HotkeysService,
126 private hooks: HooksService,
127 private peertubeSocket: PeerTubeSocket,
128 private location: PlatformLocation,
129 @Inject(LOCALE_ID) private localeId: string
130 ) {
131 this.tooltipLike = $localize`Like this video`
132 this.tooltipDislike = $localize`Dislike this video`
133 this.tooltipSupport = $localize`Support options for this video`
134 this.tooltipSaveToPlaylist = $localize`Save to playlist`
135 }
136
137 get user () {
138 return this.authService.getUser()
139 }
140
141 get anonymousUser () {
142 return this.userService.getAnonymousUser()
143 }
144
145 async ngOnInit () {
146 PeertubePlayerManager.initState()
147
148 this.serverConfig = this.serverService.getTmpConfig()
149
150 this.configSub = this.serverService.getConfig()
151 .subscribe(config => {
152 this.serverConfig = config
153
154 if (
155 isWebRTCDisabled() ||
156 this.serverConfig.tracker.enabled === false ||
157 getStoredP2PEnabled() === false ||
158 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
159 ) {
160 this.hasAlreadyAcceptedPrivacyConcern = true
161 }
162 })
163
164 this.paramsSub = this.route.params.subscribe(routeParams => {
165 const videoId = routeParams[ 'videoId' ]
166 if (videoId) this.loadVideo(videoId)
167
168 const playlistId = routeParams[ 'playlistId' ]
169 if (playlistId) this.loadPlaylist(playlistId)
170 })
171
172 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
173 this.playlistPosition = queryParams[ 'playlistPosition' ]
174 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
175
176 const start = queryParams[ 'start' ]
177 if (this.player && start) this.player.currentTime(parseInt(start, 10))
178 })
179
180 this.initHotkeys()
181
182 this.theaterEnabled = getStoredTheater()
183
184 this.hooks.runAction('action:video-watch.init', 'video-watch')
185 }
186
187 ngOnDestroy () {
188 this.flushPlayer()
189
190 // Unsubscribe subscriptions
191 if (this.paramsSub) this.paramsSub.unsubscribe()
192 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
193 if (this.configSub) this.configSub.unsubscribe()
194 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
195
196 // Unbind hotkeys
197 this.hotkeysService.remove(this.hotkeys)
198 }
199
200 setLike () {
201 if (this.isUserLoggedIn() === false) return
202
203 // Already liked this video
204 if (this.userRating === 'like') this.setRating('none')
205 else this.setRating('like')
206 }
207
208 setDislike () {
209 if (this.isUserLoggedIn() === false) return
210
211 // Already disliked this video
212 if (this.userRating === 'dislike') this.setRating('none')
213 else this.setRating('dislike')
214 }
215
216 getRatePopoverText () {
217 if (this.isUserLoggedIn()) return undefined
218
219 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
220 }
221
222 showMoreDescription () {
223 if (this.completeVideoDescription === undefined) {
224 return this.loadCompleteDescription()
225 }
226
227 this.updateVideoDescription(this.completeVideoDescription)
228 this.completeDescriptionShown = true
229 }
230
231 showLessDescription () {
232 this.updateVideoDescription(this.shortVideoDescription)
233 this.completeDescriptionShown = false
234 }
235
236 showDownloadModal () {
237 this.videoDownloadModal.show(this.video, this.videoCaptions)
238 }
239
240 isVideoDownloadable () {
241 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
242 }
243
244 loadCompleteDescription () {
245 this.descriptionLoading = true
246
247 this.videoService.loadCompleteDescription(this.video.descriptionPath)
248 .subscribe(
249 description => {
250 this.completeDescriptionShown = true
251 this.descriptionLoading = false
252
253 this.shortVideoDescription = this.video.description
254 this.completeVideoDescription = description
255
256 this.updateVideoDescription(this.completeVideoDescription)
257 },
258
259 error => {
260 this.descriptionLoading = false
261 this.notifier.error(error.message)
262 }
263 )
264 }
265
266 showSupportModal () {
267 // Check video was playing before opening support modal
268 const isVideoPlaying = this.isPlaying()
269
270 this.pausePlayer()
271
272 const modalRef = this.videoSupportModal.show()
273
274 modalRef.result.then(() => {
275 if (isVideoPlaying) {
276 this.resumePlayer()
277 }
278 })
279 }
280
281 showShareModal () {
282 this.pausePlayer()
283
284 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
285 }
286
287 isUserLoggedIn () {
288 return this.authService.isLoggedIn()
289 }
290
291 getVideoTags () {
292 if (!this.video || Array.isArray(this.video.tags) === false) return []
293
294 return this.video.tags
295 }
296
297 onRecommendations (videos: Video[]) {
298 if (videos.length > 0) {
299 // The recommended videos's first element should be the next video
300 const video = videos[0]
301 this.nextVideoUuid = video.uuid
302 this.nextVideoTitle = video.name
303 }
304 }
305
306 onModalOpened () {
307 this.pausePlayer()
308 }
309
310 onVideoRemoved () {
311 this.redirectService.redirectToHomepage()
312 }
313
314 declinedPrivacyConcern () {
315 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
316 this.hasAlreadyAcceptedPrivacyConcern = false
317 }
318
319 acceptedPrivacyConcern () {
320 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
321 this.hasAlreadyAcceptedPrivacyConcern = true
322 }
323
324 isVideoToTranscode () {
325 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
326 }
327
328 isVideoToImport () {
329 return this.video && this.video.state.id === VideoState.TO_IMPORT
330 }
331
332 hasVideoScheduledPublication () {
333 return this.video && this.video.scheduledUpdate !== undefined
334 }
335
336 isLive () {
337 return !!(this.video?.isLive)
338 }
339
340 isWaitingForLive () {
341 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
342 }
343
344 isLiveEnded () {
345 return this.video?.state.id === VideoState.LIVE_ENDED
346 }
347
348 isVideoBlur (video: Video) {
349 return video.isVideoNSFWForUser(this.user, this.serverConfig)
350 }
351
352 isAutoPlayEnabled () {
353 return (
354 (this.user && this.user.autoPlayNextVideo) ||
355 this.anonymousUser.autoPlayNextVideo
356 )
357 }
358
359 handleTimestampClicked (timestamp: number) {
360 if (this.player) this.player.currentTime(timestamp)
361 scrollToTop()
362 }
363
364 isPlaylistAutoPlayEnabled () {
365 return (
366 (this.user && this.user.autoPlayNextVideoPlaylist) ||
367 this.anonymousUser.autoPlayNextVideoPlaylist
368 )
369 }
370
371 isChannelDisplayNameGeneric () {
372 const genericChannelDisplayName = [
373 `Main ${this.video.channel.ownerAccount.name} channel`,
374 `Default ${this.video.channel.ownerAccount.name} channel`
375 ]
376
377 return genericChannelDisplayName.includes(this.video.channel.displayName)
378 }
379
380 onPlaylistVideoFound (videoId: string) {
381 this.loadVideo(videoId)
382 }
383
384 private loadVideo (videoId: string) {
385 // Video did not change
386 if (this.video && this.video.uuid === videoId) return
387
388 if (this.player) this.player.pause()
389
390 const videoObs = this.hooks.wrapObsFun(
391 this.videoService.getVideo.bind(this.videoService),
392 { videoId },
393 'video-watch',
394 'filter:api.video-watch.video.get.params',
395 'filter:api.video-watch.video.get.result'
396 )
397
398 // Video did change
399 forkJoin([
400 videoObs,
401 this.videoCaptionService.listCaptions(videoId)
402 ])
403 .pipe(
404 // If 401, the video is private or blocked so redirect to 404
405 catchError(err => {
406 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
407 const search = window.location.search
408 let originUrl = err.body.originUrl
409 if (search) originUrl += search
410
411 this.confirmService.confirm(
412 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
413 $localize`Redirection`
414 ).then(res => {
415 if (res === false) return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
416
417 return window.location.href = originUrl
418 })
419 }
420
421 return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
422 })
423 )
424 .subscribe(([ video, captionsResult ]) => {
425 const queryParams = this.route.snapshot.queryParams
426
427 const urlOptions = {
428 resume: queryParams.resume,
429
430 startTime: queryParams.start,
431 stopTime: queryParams.stop,
432
433 muted: queryParams.muted,
434 loop: queryParams.loop,
435 subtitle: queryParams.subtitle,
436
437 playerMode: queryParams.mode,
438 peertubeLink: false
439 }
440
441 this.onVideoFetched(video, captionsResult.data, urlOptions)
442 .catch(err => this.handleError(err))
443 })
444 }
445
446 private loadPlaylist (playlistId: string) {
447 // Playlist did not change
448 if (this.playlist && this.playlist.uuid === playlistId) return
449
450 this.playlistService.getVideoPlaylist(playlistId)
451 .pipe(
452 // If 401, the video is private or blocked so redirect to 404
453 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
454 )
455 .subscribe(playlist => {
456 this.playlist = playlist
457
458 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
459 })
460 }
461
462 private updateVideoDescription (description: string) {
463 this.video.description = description
464 this.setVideoDescriptionHTML()
465 .catch(err => console.error(err))
466 }
467
468 private async setVideoDescriptionHTML () {
469 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
470 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
471 }
472
473 private setVideoLikesBarTooltipText () {
474 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
475 }
476
477 private handleError (err: any) {
478 const errorMessage: string = typeof err === 'string' ? err : err.message
479 if (!errorMessage) return
480
481 // Display a message in the video player instead of a notification
482 if (errorMessage.indexOf('from xs param') !== -1) {
483 this.flushPlayer()
484 this.remoteServerDown = true
485 this.changeDetector.detectChanges()
486
487 return
488 }
489
490 this.notifier.error(errorMessage)
491 }
492
493 private checkUserRating () {
494 // Unlogged users do not have ratings
495 if (this.isUserLoggedIn() === false) return
496
497 this.videoService.getUserVideoRating(this.video.id)
498 .subscribe(
499 ratingObject => {
500 if (ratingObject) {
501 this.userRating = ratingObject.rating
502 }
503 },
504
505 err => this.notifier.error(err.message)
506 )
507 }
508
509 private async onVideoFetched (
510 video: VideoDetails,
511 videoCaptions: VideoCaption[],
512 urlOptions: URLOptions
513 ) {
514 this.subscribeToLiveEventsIfNeeded(this.video, video)
515
516 this.video = video
517 this.videoCaptions = videoCaptions
518
519 // Re init attributes
520 this.descriptionLoading = false
521 this.completeDescriptionShown = false
522 this.remoteServerDown = false
523 this.currentTime = undefined
524
525 if (this.isVideoBlur(this.video)) {
526 const res = await this.confirmService.confirm(
527 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
528 $localize`Mature or explicit content`
529 )
530 if (res === false) return this.location.back()
531 }
532
533 const videoState = this.video.state.id
534 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) return
535
536 // Flush old player if needed
537 this.flushPlayer()
538
539 // Build video element, because videojs removes it on dispose
540 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
541 this.playerElement = document.createElement('video')
542 this.playerElement.className = 'video-js vjs-peertube-skin'
543 this.playerElement.setAttribute('playsinline', 'true')
544 playerElementWrapper.appendChild(this.playerElement)
545
546 const params = {
547 video: this.video,
548 videoCaptions,
549 urlOptions,
550 user: this.user
551 }
552 const { playerMode, playerOptions } = await this.hooks.wrapFun(
553 this.buildPlayerManagerOptions.bind(this),
554 params,
555 'video-watch',
556 'filter:internal.video-watch.player.build-options.params',
557 'filter:internal.video-watch.player.build-options.result'
558 )
559
560 this.zone.runOutsideAngular(async () => {
561 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
562
563 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
564
565 this.player.on('timeupdate', () => {
566 this.currentTime = Math.floor(this.player.currentTime())
567 })
568
569 /**
570 * replaces this.player.one('ended')
571 * 'condition()': true to make the upnext functionality trigger,
572 * false to disable the upnext functionality
573 * go to the next video in 'condition()' if you don't want of the timer.
574 * 'next': function triggered at the end of the timer.
575 * 'suspended': function used at each clic of the timer checking if we need
576 * to reset progress and wait until 'suspended' becomes truthy again.
577 */
578 this.player.upnext({
579 timeout: 10000, // 10s
580 headText: $localize`Up Next`,
581 cancelText: $localize`Cancel`,
582 suspendedText: $localize`Autoplay is suspended`,
583 getTitle: () => this.nextVideoTitle,
584 next: () => this.zone.run(() => this.autoplayNext()),
585 condition: () => {
586 if (this.playlist) {
587 if (this.isPlaylistAutoPlayEnabled()) {
588 // upnext will not trigger, and instead the next video will play immediately
589 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
590 }
591 } else if (this.isAutoPlayEnabled()) {
592 return true // upnext will trigger
593 }
594 return false // upnext will not trigger, and instead leave the video stopping
595 },
596 suspended: () => {
597 return (
598 !isXPercentInViewport(this.player.el(), 80) ||
599 !document.getElementById('content').contains(document.activeElement)
600 )
601 }
602 })
603
604 this.player.one('stopped', () => {
605 if (this.playlist) {
606 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
607 }
608 })
609
610 this.player.on('theaterChange', (_: any, enabled: boolean) => {
611 this.zone.run(() => this.theaterEnabled = enabled)
612 })
613
614 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
615 })
616
617 this.setVideoDescriptionHTML()
618 this.setVideoLikesBarTooltipText()
619
620 this.setOpenGraphTags()
621 this.checkUserRating()
622
623 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
624 }
625
626 private autoplayNext () {
627 if (this.playlist) {
628 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
629 } else if (this.nextVideoUuid) {
630 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
631 }
632 }
633
634 private setRating (nextRating: UserVideoRateType) {
635 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
636 like: this.videoService.setVideoLike,
637 dislike: this.videoService.setVideoDislike,
638 none: this.videoService.unsetVideoLike
639 }
640
641 ratingMethods[nextRating].call(this.videoService, this.video.id)
642 .subscribe(
643 () => {
644 // Update the video like attribute
645 this.updateVideoRating(this.userRating, nextRating)
646 this.userRating = nextRating
647 },
648
649 (err: { message: string }) => this.notifier.error(err.message)
650 )
651 }
652
653 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
654 let likesToIncrement = 0
655 let dislikesToIncrement = 0
656
657 if (oldRating) {
658 if (oldRating === 'like') likesToIncrement--
659 if (oldRating === 'dislike') dislikesToIncrement--
660 }
661
662 if (newRating === 'like') likesToIncrement++
663 if (newRating === 'dislike') dislikesToIncrement++
664
665 this.video.likes += likesToIncrement
666 this.video.dislikes += dislikesToIncrement
667
668 this.video.buildLikeAndDislikePercents()
669 this.setVideoLikesBarTooltipText()
670 }
671
672 private setOpenGraphTags () {
673 this.metaService.setTitle(this.video.name)
674
675 this.metaService.setTag('og:type', 'video')
676
677 this.metaService.setTag('og:title', this.video.name)
678 this.metaService.setTag('name', this.video.name)
679
680 this.metaService.setTag('og:description', this.video.description)
681 this.metaService.setTag('description', this.video.description)
682
683 this.metaService.setTag('og:image', this.video.previewPath)
684
685 this.metaService.setTag('og:duration', this.video.duration.toString())
686
687 this.metaService.setTag('og:site_name', 'PeerTube')
688
689 this.metaService.setTag('og:url', window.location.href)
690 this.metaService.setTag('url', window.location.href)
691 }
692
693 private isAutoplay () {
694 // We'll jump to the thread id, so do not play the video
695 if (this.route.snapshot.params['threadId']) return false
696
697 // Otherwise true by default
698 if (!this.user) return true
699
700 // Be sure the autoPlay is set to false
701 return this.user.autoPlayVideo !== false
702 }
703
704 private flushPlayer () {
705 // Remove player if it exists
706 if (this.player) {
707 try {
708 this.player.dispose()
709 this.player = undefined
710 } catch (err) {
711 console.error('Cannot dispose player.', err)
712 }
713 }
714 }
715
716 private buildPlayerManagerOptions (params: {
717 video: VideoDetails,
718 videoCaptions: VideoCaption[],
719 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
720 user?: AuthUser
721 }) {
722 const { video, videoCaptions, urlOptions, user } = params
723 const getStartTime = () => {
724 const byUrl = urlOptions.startTime !== undefined
725 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
726
727 if (byUrl) return timeToInt(urlOptions.startTime)
728 if (byHistory) return video.userHistory.currentTime
729
730 return 0
731 }
732
733 let startTime = getStartTime()
734
735 // If we are at the end of the video, reset the timer
736 if (video.duration - startTime <= 1) startTime = 0
737
738 const playerCaptions = videoCaptions.map(c => ({
739 label: c.language.label,
740 language: c.language.id,
741 src: environment.apiUrl + c.captionPath
742 }))
743
744 const options: PeertubePlayerManagerOptions = {
745 common: {
746 autoplay: this.isAutoplay(),
747 nextVideo: () => this.zone.run(() => this.autoplayNext()),
748
749 playerElement: this.playerElement,
750 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
751
752 videoDuration: video.duration,
753 enableHotkeys: true,
754 inactivityTimeout: 2500,
755 poster: video.previewUrl,
756
757 startTime,
758 stopTime: urlOptions.stopTime,
759 controls: urlOptions.controls,
760 muted: urlOptions.muted,
761 loop: urlOptions.loop,
762 subtitle: urlOptions.subtitle,
763
764 peertubeLink: urlOptions.peertubeLink,
765
766 theaterButton: true,
767 captions: videoCaptions.length !== 0,
768
769 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
770 ? this.videoService.getVideoViewUrl(video.uuid)
771 : null,
772 embedUrl: video.embedUrl,
773
774 isLive: video.isLive,
775
776 language: this.localeId,
777
778 userWatching: user && user.videosHistoryEnabled === true ? {
779 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
780 authorizationHeader: this.authService.getRequestHeaderValue()
781 } : undefined,
782
783 serverUrl: environment.apiUrl,
784
785 videoCaptions: playerCaptions
786 },
787
788 webtorrent: {
789 videoFiles: video.files
790 }
791 }
792
793 let mode: PlayerMode
794
795 if (urlOptions.playerMode) {
796 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
797 else mode = 'webtorrent'
798 } else {
799 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
800 else mode = 'webtorrent'
801 }
802
803 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
804 if (typeof TextEncoder === 'undefined') {
805 mode = 'webtorrent'
806 }
807
808 if (mode === 'p2p-media-loader') {
809 const hlsPlaylist = video.getHlsPlaylist()
810
811 const p2pMediaLoader = {
812 playlistUrl: hlsPlaylist.playlistUrl,
813 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
814 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
815 trackerAnnounce: video.trackerUrls,
816 videoFiles: hlsPlaylist.files
817 } as P2PMediaLoaderOptions
818
819 Object.assign(options, { p2pMediaLoader })
820 }
821
822 return { playerMode: mode, playerOptions: options }
823 }
824
825 private pausePlayer () {
826 if (!this.player) return
827
828 this.player.pause()
829 }
830
831 private resumePlayer () {
832 if (!this.player) return
833
834 this.player.play()
835 }
836
837 private isPlaying () {
838 if (!this.player) return
839
840 return !this.player.paused()
841 }
842
843 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
844 if (!this.liveVideosSub) {
845 this.liveVideosSub = this.peertubeSocket.getLiveVideosObservable()
846 .subscribe(({ payload }) => {
847 if (payload.state !== VideoState.PUBLISHED || this.video.state.id !== VideoState.WAITING_FOR_LIVE) return
848
849 const videoUUID = this.video.uuid
850
851 // Reset to refetch the video
852 this.video = undefined
853 this.loadVideo(videoUUID)
854 })
855 }
856
857 if (oldVideo && oldVideo.id !== newVideo.id) {
858 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
859 }
860
861 if (!newVideo.isLive) return
862
863 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
864 }
865
866 private initHotkeys () {
867 this.hotkeys = [
868 // These hotkeys are managed by the player
869 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
870 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
871 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
872
873 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)`),
874
875 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
876 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
877
878 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
879 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
880
881 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
882 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
883
884 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
885 ]
886
887 if (this.isUserLoggedIn()) {
888 this.hotkeys = this.hotkeys.concat([
889 new Hotkey('shift+l', () => {
890 this.setLike()
891 return false
892 }, undefined, $localize`Like the video`),
893
894 new Hotkey('shift+d', () => {
895 this.setDislike()
896 return false
897 }, undefined, $localize`Dislike the video`),
898
899 new Hotkey('shift+s', () => {
900 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
901 return false
902 }, undefined, $localize`Subscribe to the account`)
903 ])
904 }
905
906 this.hotkeysService.add(this.hotkeys)
907 }
908 }