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