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