]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-watch/video-watch.component.ts
add title attribute for exact view counters (#3365)
[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 getExactNumberOfViews () {
223 return (this.video.views >= 1000)
224 ? `${this.video.views} ${this.video.isLive ? $localize`viewers` : $localize`views`}`
225 : ''
226 }
227
228 showMoreDescription () {
229 if (this.completeVideoDescription === undefined) {
230 return this.loadCompleteDescription()
231 }
232
233 this.updateVideoDescription(this.completeVideoDescription)
234 this.completeDescriptionShown = true
235 }
236
237 showLessDescription () {
238 this.updateVideoDescription(this.shortVideoDescription)
239 this.completeDescriptionShown = false
240 }
241
242 showDownloadModal () {
243 this.videoDownloadModal.show(this.video, this.videoCaptions)
244 }
245
246 isVideoDownloadable () {
247 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
248 }
249
250 loadCompleteDescription () {
251 this.descriptionLoading = true
252
253 this.videoService.loadCompleteDescription(this.video.descriptionPath)
254 .subscribe(
255 description => {
256 this.completeDescriptionShown = true
257 this.descriptionLoading = false
258
259 this.shortVideoDescription = this.video.description
260 this.completeVideoDescription = description
261
262 this.updateVideoDescription(this.completeVideoDescription)
263 },
264
265 error => {
266 this.descriptionLoading = false
267 this.notifier.error(error.message)
268 }
269 )
270 }
271
272 showSupportModal () {
273 // Check video was playing before opening support modal
274 const isVideoPlaying = this.isPlaying()
275
276 this.pausePlayer()
277
278 const modalRef = this.videoSupportModal.show()
279
280 modalRef.result.then(() => {
281 if (isVideoPlaying) {
282 this.resumePlayer()
283 }
284 })
285 }
286
287 showShareModal () {
288 this.pausePlayer()
289
290 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
291 }
292
293 isUserLoggedIn () {
294 return this.authService.isLoggedIn()
295 }
296
297 getVideoTags () {
298 if (!this.video || Array.isArray(this.video.tags) === false) return []
299
300 return this.video.tags
301 }
302
303 onRecommendations (videos: Video[]) {
304 if (videos.length > 0) {
305 // The recommended videos's first element should be the next video
306 const video = videos[0]
307 this.nextVideoUuid = video.uuid
308 this.nextVideoTitle = video.name
309 }
310 }
311
312 onModalOpened () {
313 this.pausePlayer()
314 }
315
316 onVideoRemoved () {
317 this.redirectService.redirectToHomepage()
318 }
319
320 declinedPrivacyConcern () {
321 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
322 this.hasAlreadyAcceptedPrivacyConcern = false
323 }
324
325 acceptedPrivacyConcern () {
326 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
327 this.hasAlreadyAcceptedPrivacyConcern = true
328 }
329
330 isVideoToTranscode () {
331 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
332 }
333
334 isVideoToImport () {
335 return this.video && this.video.state.id === VideoState.TO_IMPORT
336 }
337
338 hasVideoScheduledPublication () {
339 return this.video && this.video.scheduledUpdate !== undefined
340 }
341
342 isLive () {
343 return !!(this.video?.isLive)
344 }
345
346 isWaitingForLive () {
347 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
348 }
349
350 isLiveEnded () {
351 return this.video?.state.id === VideoState.LIVE_ENDED
352 }
353
354 isVideoBlur (video: Video) {
355 return video.isVideoNSFWForUser(this.user, this.serverConfig)
356 }
357
358 isAutoPlayEnabled () {
359 return (
360 (this.user && this.user.autoPlayNextVideo) ||
361 this.anonymousUser.autoPlayNextVideo
362 )
363 }
364
365 handleTimestampClicked (timestamp: number) {
366 if (this.player) this.player.currentTime(timestamp)
367 scrollToTop()
368 }
369
370 isPlaylistAutoPlayEnabled () {
371 return (
372 (this.user && this.user.autoPlayNextVideoPlaylist) ||
373 this.anonymousUser.autoPlayNextVideoPlaylist
374 )
375 }
376
377 isChannelDisplayNameGeneric () {
378 const genericChannelDisplayName = [
379 `Main ${this.video.channel.ownerAccount.name} channel`,
380 `Default ${this.video.channel.ownerAccount.name} channel`
381 ]
382
383 return genericChannelDisplayName.includes(this.video.channel.displayName)
384 }
385
386 onPlaylistVideoFound (videoId: string) {
387 this.loadVideo(videoId)
388 }
389
390 private loadVideo (videoId: string) {
391 // Video did not change
392 if (this.video && this.video.uuid === videoId) return
393
394 if (this.player) this.player.pause()
395
396 const videoObs = this.hooks.wrapObsFun(
397 this.videoService.getVideo.bind(this.videoService),
398 { videoId },
399 'video-watch',
400 'filter:api.video-watch.video.get.params',
401 'filter:api.video-watch.video.get.result'
402 )
403
404 // Video did change
405 forkJoin([
406 videoObs,
407 this.videoCaptionService.listCaptions(videoId)
408 ])
409 .pipe(
410 // If 401, the video is private or blocked so redirect to 404
411 catchError(err => {
412 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
413 const search = window.location.search
414 let originUrl = err.body.originUrl
415 if (search) originUrl += search
416
417 this.confirmService.confirm(
418 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
419 $localize`Redirection`
420 ).then(res => {
421 if (res === false) return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
422
423 return window.location.href = originUrl
424 })
425 }
426
427 return this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ])
428 })
429 )
430 .subscribe(([ video, captionsResult ]) => {
431 const queryParams = this.route.snapshot.queryParams
432
433 const urlOptions = {
434 resume: queryParams.resume,
435
436 startTime: queryParams.start,
437 stopTime: queryParams.stop,
438
439 muted: queryParams.muted,
440 loop: queryParams.loop,
441 subtitle: queryParams.subtitle,
442
443 playerMode: queryParams.mode,
444 peertubeLink: false
445 }
446
447 this.onVideoFetched(video, captionsResult.data, urlOptions)
448 .catch(err => this.handleError(err))
449 })
450 }
451
452 private loadPlaylist (playlistId: string) {
453 // Playlist did not change
454 if (this.playlist && this.playlist.uuid === playlistId) return
455
456 this.playlistService.getVideoPlaylist(playlistId)
457 .pipe(
458 // If 401, the video is private or blocked so redirect to 404
459 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
460 )
461 .subscribe(playlist => {
462 this.playlist = playlist
463
464 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
465 })
466 }
467
468 private updateVideoDescription (description: string) {
469 this.video.description = description
470 this.setVideoDescriptionHTML()
471 .catch(err => console.error(err))
472 }
473
474 private async setVideoDescriptionHTML () {
475 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
476 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
477 }
478
479 private setVideoLikesBarTooltipText () {
480 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
481 }
482
483 private handleError (err: any) {
484 const errorMessage: string = typeof err === 'string' ? err : err.message
485 if (!errorMessage) return
486
487 // Display a message in the video player instead of a notification
488 if (errorMessage.indexOf('from xs param') !== -1) {
489 this.flushPlayer()
490 this.remoteServerDown = true
491 this.changeDetector.detectChanges()
492
493 return
494 }
495
496 this.notifier.error(errorMessage)
497 }
498
499 private checkUserRating () {
500 // Unlogged users do not have ratings
501 if (this.isUserLoggedIn() === false) return
502
503 this.videoService.getUserVideoRating(this.video.id)
504 .subscribe(
505 ratingObject => {
506 if (ratingObject) {
507 this.userRating = ratingObject.rating
508 }
509 },
510
511 err => this.notifier.error(err.message)
512 )
513 }
514
515 private async onVideoFetched (
516 video: VideoDetails,
517 videoCaptions: VideoCaption[],
518 urlOptions: URLOptions
519 ) {
520 this.subscribeToLiveEventsIfNeeded(this.video, video)
521
522 this.video = video
523 this.videoCaptions = videoCaptions
524
525 // Re init attributes
526 this.descriptionLoading = false
527 this.completeDescriptionShown = false
528 this.remoteServerDown = false
529 this.currentTime = undefined
530
531 if (this.isVideoBlur(this.video)) {
532 const res = await this.confirmService.confirm(
533 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
534 $localize`Mature or explicit content`
535 )
536 if (res === false) return this.location.back()
537 }
538
539 const videoState = this.video.state.id
540 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) return
541
542 // Flush old player if needed
543 this.flushPlayer()
544
545 // Build video element, because videojs removes it on dispose
546 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
547 this.playerElement = document.createElement('video')
548 this.playerElement.className = 'video-js vjs-peertube-skin'
549 this.playerElement.setAttribute('playsinline', 'true')
550 playerElementWrapper.appendChild(this.playerElement)
551
552 const params = {
553 video: this.video,
554 videoCaptions,
555 urlOptions,
556 user: this.user
557 }
558 const { playerMode, playerOptions } = await this.hooks.wrapFun(
559 this.buildPlayerManagerOptions.bind(this),
560 params,
561 'video-watch',
562 'filter:internal.video-watch.player.build-options.params',
563 'filter:internal.video-watch.player.build-options.result'
564 )
565
566 this.zone.runOutsideAngular(async () => {
567 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
568
569 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
570
571 this.player.on('timeupdate', () => {
572 this.currentTime = Math.floor(this.player.currentTime())
573 })
574
575 /**
576 * replaces this.player.one('ended')
577 * 'condition()': true to make the upnext functionality trigger,
578 * false to disable the upnext functionality
579 * go to the next video in 'condition()' if you don't want of the timer.
580 * 'next': function triggered at the end of the timer.
581 * 'suspended': function used at each clic of the timer checking if we need
582 * to reset progress and wait until 'suspended' becomes truthy again.
583 */
584 this.player.upnext({
585 timeout: 10000, // 10s
586 headText: $localize`Up Next`,
587 cancelText: $localize`Cancel`,
588 suspendedText: $localize`Autoplay is suspended`,
589 getTitle: () => this.nextVideoTitle,
590 next: () => this.zone.run(() => this.autoplayNext()),
591 condition: () => {
592 if (this.playlist) {
593 if (this.isPlaylistAutoPlayEnabled()) {
594 // upnext will not trigger, and instead the next video will play immediately
595 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
596 }
597 } else if (this.isAutoPlayEnabled()) {
598 return true // upnext will trigger
599 }
600 return false // upnext will not trigger, and instead leave the video stopping
601 },
602 suspended: () => {
603 return (
604 !isXPercentInViewport(this.player.el(), 80) ||
605 !document.getElementById('content').contains(document.activeElement)
606 )
607 }
608 })
609
610 this.player.one('stopped', () => {
611 if (this.playlist) {
612 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
613 }
614 })
615
616 this.player.on('theaterChange', (_: any, enabled: boolean) => {
617 this.zone.run(() => this.theaterEnabled = enabled)
618 })
619
620 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
621 })
622
623 this.setVideoDescriptionHTML()
624 this.setVideoLikesBarTooltipText()
625
626 this.setOpenGraphTags()
627 this.checkUserRating()
628
629 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
630 }
631
632 private autoplayNext () {
633 if (this.playlist) {
634 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
635 } else if (this.nextVideoUuid) {
636 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
637 }
638 }
639
640 private setRating (nextRating: UserVideoRateType) {
641 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
642 like: this.videoService.setVideoLike,
643 dislike: this.videoService.setVideoDislike,
644 none: this.videoService.unsetVideoLike
645 }
646
647 ratingMethods[nextRating].call(this.videoService, this.video.id)
648 .subscribe(
649 () => {
650 // Update the video like attribute
651 this.updateVideoRating(this.userRating, nextRating)
652 this.userRating = nextRating
653 },
654
655 (err: { message: string }) => this.notifier.error(err.message)
656 )
657 }
658
659 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
660 let likesToIncrement = 0
661 let dislikesToIncrement = 0
662
663 if (oldRating) {
664 if (oldRating === 'like') likesToIncrement--
665 if (oldRating === 'dislike') dislikesToIncrement--
666 }
667
668 if (newRating === 'like') likesToIncrement++
669 if (newRating === 'dislike') dislikesToIncrement++
670
671 this.video.likes += likesToIncrement
672 this.video.dislikes += dislikesToIncrement
673
674 this.video.buildLikeAndDislikePercents()
675 this.setVideoLikesBarTooltipText()
676 }
677
678 private setOpenGraphTags () {
679 this.metaService.setTitle(this.video.name)
680
681 this.metaService.setTag('og:type', 'video')
682
683 this.metaService.setTag('og:title', this.video.name)
684 this.metaService.setTag('name', this.video.name)
685
686 this.metaService.setTag('og:description', this.video.description)
687 this.metaService.setTag('description', this.video.description)
688
689 this.metaService.setTag('og:image', this.video.previewPath)
690
691 this.metaService.setTag('og:duration', this.video.duration.toString())
692
693 this.metaService.setTag('og:site_name', 'PeerTube')
694
695 this.metaService.setTag('og:url', window.location.href)
696 this.metaService.setTag('url', window.location.href)
697 }
698
699 private isAutoplay () {
700 // We'll jump to the thread id, so do not play the video
701 if (this.route.snapshot.params['threadId']) return false
702
703 // Otherwise true by default
704 if (!this.user) return true
705
706 // Be sure the autoPlay is set to false
707 return this.user.autoPlayVideo !== false
708 }
709
710 private flushPlayer () {
711 // Remove player if it exists
712 if (this.player) {
713 try {
714 this.player.dispose()
715 this.player = undefined
716 } catch (err) {
717 console.error('Cannot dispose player.', err)
718 }
719 }
720 }
721
722 private buildPlayerManagerOptions (params: {
723 video: VideoDetails,
724 videoCaptions: VideoCaption[],
725 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
726 user?: AuthUser
727 }) {
728 const { video, videoCaptions, urlOptions, user } = params
729 const getStartTime = () => {
730 const byUrl = urlOptions.startTime !== undefined
731 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
732
733 if (byUrl) return timeToInt(urlOptions.startTime)
734 if (byHistory) return video.userHistory.currentTime
735
736 return 0
737 }
738
739 let startTime = getStartTime()
740
741 // If we are at the end of the video, reset the timer
742 if (video.duration - startTime <= 1) startTime = 0
743
744 const playerCaptions = videoCaptions.map(c => ({
745 label: c.language.label,
746 language: c.language.id,
747 src: environment.apiUrl + c.captionPath
748 }))
749
750 const options: PeertubePlayerManagerOptions = {
751 common: {
752 autoplay: this.isAutoplay(),
753 nextVideo: () => this.zone.run(() => this.autoplayNext()),
754
755 playerElement: this.playerElement,
756 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
757
758 videoDuration: video.duration,
759 enableHotkeys: true,
760 inactivityTimeout: 2500,
761 poster: video.previewUrl,
762
763 startTime,
764 stopTime: urlOptions.stopTime,
765 controls: urlOptions.controls,
766 muted: urlOptions.muted,
767 loop: urlOptions.loop,
768 subtitle: urlOptions.subtitle,
769
770 peertubeLink: urlOptions.peertubeLink,
771
772 theaterButton: true,
773 captions: videoCaptions.length !== 0,
774
775 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
776 ? this.videoService.getVideoViewUrl(video.uuid)
777 : null,
778 embedUrl: video.embedUrl,
779
780 isLive: video.isLive,
781
782 language: this.localeId,
783
784 userWatching: user && user.videosHistoryEnabled === true ? {
785 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
786 authorizationHeader: this.authService.getRequestHeaderValue()
787 } : undefined,
788
789 serverUrl: environment.apiUrl,
790
791 videoCaptions: playerCaptions
792 },
793
794 webtorrent: {
795 videoFiles: video.files
796 }
797 }
798
799 let mode: PlayerMode
800
801 if (urlOptions.playerMode) {
802 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
803 else mode = 'webtorrent'
804 } else {
805 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
806 else mode = 'webtorrent'
807 }
808
809 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
810 if (typeof TextEncoder === 'undefined') {
811 mode = 'webtorrent'
812 }
813
814 if (mode === 'p2p-media-loader') {
815 const hlsPlaylist = video.getHlsPlaylist()
816
817 const p2pMediaLoader = {
818 playlistUrl: hlsPlaylist.playlistUrl,
819 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
820 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
821 trackerAnnounce: video.trackerUrls,
822 videoFiles: hlsPlaylist.files
823 } as P2PMediaLoaderOptions
824
825 Object.assign(options, { p2pMediaLoader })
826 }
827
828 return { playerMode: mode, playerOptions: options }
829 }
830
831 private pausePlayer () {
832 if (!this.player) return
833
834 this.player.pause()
835 }
836
837 private resumePlayer () {
838 if (!this.player) return
839
840 this.player.play()
841 }
842
843 private isPlaying () {
844 if (!this.player) return
845
846 return !this.player.paused()
847 }
848
849 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
850 if (!this.liveVideosSub) {
851 this.liveVideosSub = this.peertubeSocket.getLiveVideosObservable()
852 .subscribe(({ payload }) => {
853 if (payload.state !== VideoState.PUBLISHED || this.video.state.id !== VideoState.WAITING_FOR_LIVE) return
854
855 const videoUUID = this.video.uuid
856
857 // Reset to refetch the video
858 this.video = undefined
859 this.loadVideo(videoUUID)
860 })
861 }
862
863 if (oldVideo && oldVideo.id !== newVideo.id) {
864 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
865 }
866
867 if (!newVideo.isLive) return
868
869 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
870 }
871
872 private initHotkeys () {
873 this.hotkeys = [
874 // These hotkeys are managed by the player
875 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
876 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
877 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
878
879 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)`),
880
881 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
882 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
883
884 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
885 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
886
887 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
888 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
889
890 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
891 ]
892
893 if (this.isUserLoggedIn()) {
894 this.hotkeys = this.hotkeys.concat([
895 new Hotkey('shift+l', () => {
896 this.setLike()
897 return false
898 }, undefined, $localize`Like the video`),
899
900 new Hotkey('shift+d', () => {
901 this.setDislike()
902 return false
903 }, undefined, $localize`Dislike the video`),
904
905 new Hotkey('shift+s', () => {
906 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
907 return false
908 }, undefined, $localize`Subscribe to the account`)
909 ])
910 }
911
912 this.hotkeysService.add(this.hotkeys)
913 }
914 }