]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/+videos/+video-watch/video-watch.component.ts
Redesign account's channels page
[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
64 theaterEnabled = false
65
66 userRating: UserVideoRateType = null
67
68 playerPlaceholderImgSrc: string
69
70 video: VideoDetails = null
71 videoCaptions: VideoCaption[] = []
72
73 playlistPosition: number
74 playlist: VideoPlaylist = null
75
76 descriptionLoading = false
77 completeDescriptionShown = false
78 completeVideoDescription: string
79 shortVideoDescription: string
80 videoHTMLDescription = ''
81
82 likesBarTooltipText = ''
83
84 hasAlreadyAcceptedPrivacyConcern = false
85 remoteServerDown = false
86
87 hotkeys: Hotkey[] = []
88
89 tooltipLike = ''
90 tooltipDislike = ''
91 tooltipSupport = ''
92 tooltipSaveToPlaylist = ''
93
94 videoActionsOptions: VideoActionsDisplayType = {
95 playlist: false,
96 download: true,
97 update: true,
98 blacklist: true,
99 delete: true,
100 report: true,
101 duplicate: true,
102 mute: true,
103 liveInfo: true
104 }
105
106 private nextVideoUuid = ''
107 private nextVideoTitle = ''
108 private currentTime: number
109 private paramsSub: Subscription
110 private queryParamsSub: Subscription
111 private configSub: Subscription
112 private liveVideosSub: Subscription
113
114 private serverConfig: ServerConfig
115
116 constructor (
117 private elementRef: ElementRef,
118 private changeDetector: ChangeDetectorRef,
119 private route: ActivatedRoute,
120 private router: Router,
121 private videoService: VideoService,
122 private playlistService: VideoPlaylistService,
123 private confirmService: ConfirmService,
124 private metaService: MetaService,
125 private authService: AuthService,
126 private userService: UserService,
127 private serverService: ServerService,
128 private restExtractor: RestExtractor,
129 private notifier: Notifier,
130 private markdownService: MarkdownService,
131 private zone: NgZone,
132 private redirectService: RedirectService,
133 private videoCaptionService: VideoCaptionService,
134 private hotkeysService: HotkeysService,
135 private hooks: HooksService,
136 private peertubeSocket: PeerTubeSocket,
137 private screenService: ScreenService,
138 private location: PlatformLocation,
139 @Inject(LOCALE_ID) private localeId: string
140 ) { }
141
142 get user () {
143 return this.authService.getUser()
144 }
145
146 get anonymousUser () {
147 return this.userService.getAnonymousUser()
148 }
149
150 async ngOnInit () {
151 // Hide the tooltips for unlogged users in mobile view, this adds confusion with the popover
152 if (this.user || !this.screenService.isInMobileView()) {
153 this.tooltipLike = $localize`Like this video`
154 this.tooltipDislike = $localize`Dislike this video`
155 this.tooltipSupport = $localize`Support options for this video`
156 this.tooltipSaveToPlaylist = $localize`Save to playlist`
157 }
158
159 PeertubePlayerManager.initState()
160
161 this.serverConfig = this.serverService.getTmpConfig()
162
163 this.configSub = this.serverService.getConfig()
164 .subscribe(config => {
165 this.serverConfig = config
166
167 if (
168 isWebRTCDisabled() ||
169 this.serverConfig.tracker.enabled === false ||
170 getStoredP2PEnabled() === false ||
171 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
172 ) {
173 this.hasAlreadyAcceptedPrivacyConcern = true
174 }
175 })
176
177 this.paramsSub = this.route.params.subscribe(routeParams => {
178 const videoId = routeParams[ 'videoId' ]
179 if (videoId) this.loadVideo(videoId)
180
181 const playlistId = routeParams[ 'playlistId' ]
182 if (playlistId) this.loadPlaylist(playlistId)
183 })
184
185 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
186 this.playlistPosition = queryParams[ 'playlistPosition' ]
187 this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition)
188
189 const start = queryParams[ 'start' ]
190 if (this.player && start) this.player.currentTime(parseInt(start, 10))
191 })
192
193 this.initHotkeys()
194
195 this.theaterEnabled = getStoredTheater()
196
197 this.hooks.runAction('action:video-watch.init', 'video-watch')
198 }
199
200 ngOnDestroy () {
201 this.flushPlayer()
202
203 // Unsubscribe subscriptions
204 if (this.paramsSub) this.paramsSub.unsubscribe()
205 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
206 if (this.configSub) this.configSub.unsubscribe()
207 if (this.liveVideosSub) this.liveVideosSub.unsubscribe()
208
209 // Unbind hotkeys
210 this.hotkeysService.remove(this.hotkeys)
211 }
212
213 setLike () {
214 if (this.isUserLoggedIn() === false) return
215
216 // Already liked this video
217 if (this.userRating === 'like') this.setRating('none')
218 else this.setRating('like')
219 }
220
221 setDislike () {
222 if (this.isUserLoggedIn() === false) return
223
224 // Already disliked this video
225 if (this.userRating === 'dislike') this.setRating('none')
226 else this.setRating('dislike')
227 }
228
229 getRatePopoverText () {
230 if (this.isUserLoggedIn()) return undefined
231
232 return $localize`You need to be <a href="/login">logged in</a> to rate this video.`
233 }
234
235 showMoreDescription () {
236 if (this.completeVideoDescription === undefined) {
237 return this.loadCompleteDescription()
238 }
239
240 this.updateVideoDescription(this.completeVideoDescription)
241 this.completeDescriptionShown = true
242 }
243
244 showLessDescription () {
245 this.updateVideoDescription(this.shortVideoDescription)
246 this.completeDescriptionShown = false
247 }
248
249 showDownloadModal () {
250 this.videoDownloadModal.show(this.video, this.videoCaptions)
251 }
252
253 isVideoDownloadable () {
254 return this.video && this.video instanceof VideoDetails && this.video.downloadEnabled && !this.video.isLive
255 }
256
257 loadCompleteDescription () {
258 this.descriptionLoading = true
259
260 this.videoService.loadCompleteDescription(this.video.descriptionPath)
261 .subscribe(
262 description => {
263 this.completeDescriptionShown = true
264 this.descriptionLoading = false
265
266 this.shortVideoDescription = this.video.description
267 this.completeVideoDescription = description
268
269 this.updateVideoDescription(this.completeVideoDescription)
270 },
271
272 error => {
273 this.descriptionLoading = false
274 this.notifier.error(error.message)
275 }
276 )
277 }
278
279 showSupportModal () {
280 // Check video was playing before opening support modal
281 const isVideoPlaying = this.isPlaying()
282
283 this.pausePlayer()
284
285 const modalRef = this.videoSupportModal.show()
286
287 modalRef.result.then(() => {
288 if (isVideoPlaying) {
289 this.resumePlayer()
290 }
291 })
292 }
293
294 showShareModal () {
295 this.pausePlayer()
296
297 this.videoShareModal.show(this.currentTime, this.videoWatchPlaylist.currentPlaylistPosition)
298 }
299
300 isUserLoggedIn () {
301 return this.authService.isLoggedIn()
302 }
303
304 getVideoTags () {
305 if (!this.video || Array.isArray(this.video.tags) === false) return []
306
307 return this.video.tags
308 }
309
310 onRecommendations (videos: Video[]) {
311 if (videos.length > 0) {
312 // The recommended videos's first element should be the next video
313 const video = videos[0]
314 this.nextVideoUuid = video.uuid
315 this.nextVideoTitle = video.name
316 }
317 }
318
319 onModalOpened () {
320 this.pausePlayer()
321 }
322
323 onVideoRemoved () {
324 this.redirectService.redirectToHomepage()
325 }
326
327 declinedPrivacyConcern () {
328 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
329 this.hasAlreadyAcceptedPrivacyConcern = false
330 }
331
332 acceptedPrivacyConcern () {
333 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
334 this.hasAlreadyAcceptedPrivacyConcern = true
335 }
336
337 isVideoToTranscode () {
338 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
339 }
340
341 isVideoToImport () {
342 return this.video && this.video.state.id === VideoState.TO_IMPORT
343 }
344
345 hasVideoScheduledPublication () {
346 return this.video && this.video.scheduledUpdate !== undefined
347 }
348
349 isLive () {
350 return !!(this.video?.isLive)
351 }
352
353 isWaitingForLive () {
354 return this.video?.state.id === VideoState.WAITING_FOR_LIVE
355 }
356
357 isLiveEnded () {
358 return this.video?.state.id === VideoState.LIVE_ENDED
359 }
360
361 isVideoBlur (video: Video) {
362 return video.isVideoNSFWForUser(this.user, this.serverConfig)
363 }
364
365 isAutoPlayEnabled () {
366 return (
367 (this.user && this.user.autoPlayNextVideo) ||
368 this.anonymousUser.autoPlayNextVideo
369 )
370 }
371
372 handleTimestampClicked (timestamp: number) {
373 if (!this.player || this.video.isLive) return
374
375 this.player.currentTime(timestamp)
376 scrollToTop()
377 }
378
379 isPlaylistAutoPlayEnabled () {
380 return (
381 (this.user && this.user.autoPlayNextVideoPlaylist) ||
382 this.anonymousUser.autoPlayNextVideoPlaylist
383 )
384 }
385
386 isChannelDisplayNameGeneric () {
387 const genericChannelDisplayName = [
388 `Main ${this.video.channel.ownerAccount.name} channel`,
389 `Default ${this.video.channel.ownerAccount.name} channel`
390 ]
391
392 return genericChannelDisplayName.includes(this.video.channel.displayName)
393 }
394
395 onPlaylistVideoFound (videoId: string) {
396 this.loadVideo(videoId)
397 }
398
399 private loadVideo (videoId: string) {
400 // Video did not change
401 if (this.video && this.video.uuid === videoId) return
402
403 if (this.player) this.player.pause()
404
405 const videoObs = this.hooks.wrapObsFun(
406 this.videoService.getVideo.bind(this.videoService),
407 { videoId },
408 'video-watch',
409 'filter:api.video-watch.video.get.params',
410 'filter:api.video-watch.video.get.result'
411 )
412
413 // Video did change
414 forkJoin([
415 videoObs,
416 this.videoCaptionService.listCaptions(videoId)
417 ])
418 .pipe(
419 // If 400, 403 or 404, the video is private or blocked so redirect to 404
420 catchError(err => {
421 if (err.body.errorCode === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
422 const search = window.location.search
423 let originUrl = err.body.originUrl
424 if (search) originUrl += search
425
426 this.confirmService.confirm(
427 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
428 $localize`Redirection`
429 ).then(res => {
430 if (res === false) {
431 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
432 HttpStatusCode.BAD_REQUEST_400,
433 HttpStatusCode.FORBIDDEN_403,
434 HttpStatusCode.NOT_FOUND_404
435 ])
436 }
437
438 return window.location.href = originUrl
439 })
440 }
441
442 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
443 HttpStatusCode.BAD_REQUEST_400,
444 HttpStatusCode.FORBIDDEN_403,
445 HttpStatusCode.NOT_FOUND_404
446 ])
447 })
448 )
449 .subscribe(([ video, captionsResult ]) => {
450 const queryParams = this.route.snapshot.queryParams
451
452 const urlOptions = {
453 resume: queryParams.resume,
454
455 startTime: queryParams.start,
456 stopTime: queryParams.stop,
457
458 muted: queryParams.muted,
459 loop: queryParams.loop,
460 subtitle: queryParams.subtitle,
461
462 playerMode: queryParams.mode,
463 peertubeLink: false
464 }
465
466 this.onVideoFetched(video, captionsResult.data, urlOptions)
467 .catch(err => this.handleError(err))
468 })
469 }
470
471 private loadPlaylist (playlistId: string) {
472 // Playlist did not change
473 if (this.playlist && this.playlist.uuid === playlistId) return
474
475 this.playlistService.getVideoPlaylist(playlistId)
476 .pipe(
477 // If 400 or 403, the video is private or blocked so redirect to 404
478 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
479 HttpStatusCode.BAD_REQUEST_400,
480 HttpStatusCode.FORBIDDEN_403,
481 HttpStatusCode.NOT_FOUND_404
482 ]))
483 )
484 .subscribe(playlist => {
485 this.playlist = playlist
486
487 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
488 })
489 }
490
491 private updateVideoDescription (description: string) {
492 this.video.description = description
493 this.setVideoDescriptionHTML()
494 .catch(err => console.error(err))
495 }
496
497 private async setVideoDescriptionHTML () {
498 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
499 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
500 }
501
502 private setVideoLikesBarTooltipText () {
503 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
504 }
505
506 private handleError (err: any) {
507 const errorMessage: string = typeof err === 'string' ? err : err.message
508 if (!errorMessage) return
509
510 // Display a message in the video player instead of a notification
511 if (errorMessage.indexOf('from xs param') !== -1) {
512 this.flushPlayer()
513 this.remoteServerDown = true
514 this.changeDetector.detectChanges()
515
516 return
517 }
518
519 this.notifier.error(errorMessage)
520 }
521
522 private checkUserRating () {
523 // Unlogged users do not have ratings
524 if (this.isUserLoggedIn() === false) return
525
526 this.videoService.getUserVideoRating(this.video.id)
527 .subscribe(
528 ratingObject => {
529 if (ratingObject) {
530 this.userRating = ratingObject.rating
531 }
532 },
533
534 err => this.notifier.error(err.message)
535 )
536 }
537
538 private async onVideoFetched (
539 video: VideoDetails,
540 videoCaptions: VideoCaption[],
541 urlOptions: URLOptions
542 ) {
543 this.subscribeToLiveEventsIfNeeded(this.video, video)
544
545 this.video = video
546 this.videoCaptions = videoCaptions
547
548 // Re init attributes
549 this.playerPlaceholderImgSrc = undefined
550 this.descriptionLoading = false
551 this.completeDescriptionShown = false
552 this.completeVideoDescription = undefined
553 this.remoteServerDown = false
554 this.currentTime = undefined
555
556 if (this.isVideoBlur(this.video)) {
557 const res = await this.confirmService.confirm(
558 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
559 $localize`Mature or explicit content`
560 )
561 if (res === false) return this.location.back()
562 }
563
564 this.buildPlayer(urlOptions)
565 .catch(err => console.error('Cannot build the player', err))
566
567 this.setVideoDescriptionHTML()
568 this.setVideoLikesBarTooltipText()
569
570 this.setOpenGraphTags()
571 this.checkUserRating()
572
573 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
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
772 if (byUrl) return timeToInt(urlOptions.startTime)
773 if (byHistory) return video.userHistory.currentTime
774
775 return 0
776 }
777
778 let startTime = getStartTime()
779
780 // If we are at the end of the video, reset the timer
781 if (video.duration - startTime <= 1) startTime = 0
782
783 const playerCaptions = videoCaptions.map(c => ({
784 label: c.language.label,
785 language: c.language.id,
786 src: environment.apiUrl + c.captionPath
787 }))
788
789 const options: PeertubePlayerManagerOptions = {
790 common: {
791 autoplay: this.isAutoplay(),
792 nextVideo: () => this.zone.run(() => this.autoplayNext()),
793
794 playerElement: this.playerElement,
795 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
796
797 videoDuration: video.duration,
798 enableHotkeys: true,
799 inactivityTimeout: 2500,
800 poster: video.previewUrl,
801
802 startTime,
803 stopTime: urlOptions.stopTime,
804 controls: urlOptions.controls,
805 muted: urlOptions.muted,
806 loop: urlOptions.loop,
807 subtitle: urlOptions.subtitle,
808
809 peertubeLink: urlOptions.peertubeLink,
810
811 theaterButton: true,
812 captions: videoCaptions.length !== 0,
813
814 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
815 ? this.videoService.getVideoViewUrl(video.uuid)
816 : null,
817 embedUrl: video.embedUrl,
818 embedTitle: video.name,
819
820 isLive: video.isLive,
821
822 language: this.localeId,
823
824 userWatching: user && user.videosHistoryEnabled === true ? {
825 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
826 authorizationHeader: this.authService.getRequestHeaderValue()
827 } : undefined,
828
829 serverUrl: environment.apiUrl,
830
831 videoCaptions: playerCaptions
832 },
833
834 webtorrent: {
835 videoFiles: video.files
836 }
837 }
838
839 let mode: PlayerMode
840
841 if (urlOptions.playerMode) {
842 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
843 else mode = 'webtorrent'
844 } else {
845 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
846 else mode = 'webtorrent'
847 }
848
849 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
850 if (typeof TextEncoder === 'undefined') {
851 mode = 'webtorrent'
852 }
853
854 if (mode === 'p2p-media-loader') {
855 const hlsPlaylist = video.getHlsPlaylist()
856
857 const p2pMediaLoader = {
858 playlistUrl: hlsPlaylist.playlistUrl,
859 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
860 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
861 trackerAnnounce: video.trackerUrls,
862 videoFiles: hlsPlaylist.files
863 } as P2PMediaLoaderOptions
864
865 Object.assign(options, { p2pMediaLoader })
866 }
867
868 return { playerMode: mode, playerOptions: options }
869 }
870
871 private pausePlayer () {
872 if (!this.player) return
873
874 this.player.pause()
875 }
876
877 private resumePlayer () {
878 if (!this.player) return
879
880 this.player.play()
881 }
882
883 private isPlaying () {
884 if (!this.player) return
885
886 return !this.player.paused()
887 }
888
889 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
890 if (!this.liveVideosSub) {
891 this.liveVideosSub = this.buildLiveEventsSubscription()
892 }
893
894 if (oldVideo && oldVideo.id !== newVideo.id) {
895 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
896 }
897
898 if (!newVideo.isLive) return
899
900 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
901 }
902
903 private buildLiveEventsSubscription () {
904 return this.peertubeSocket.getLiveVideosObservable()
905 .subscribe(({ type, payload }) => {
906 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
907 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
908 })
909 }
910
911 private handleLiveStateChange (newState: VideoState) {
912 if (newState !== VideoState.PUBLISHED) return
913
914 const videoState = this.video.state.id
915 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
916
917 console.log('Loading video after live update.')
918
919 const videoUUID = this.video.uuid
920
921 // Reset to refetch the video
922 this.video = undefined
923 this.loadVideo(videoUUID)
924 }
925
926 private handleLiveViewsChange (newViews: number) {
927 if (!this.video) {
928 console.error('Cannot update video live views because video is no defined.')
929 return
930 }
931
932 console.log('Updating live views.')
933
934 this.video.views = newViews
935 }
936
937 private initHotkeys () {
938 this.hotkeys = [
939 // These hotkeys are managed by the player
940 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
941 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
942 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
943
944 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)`),
945
946 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
947 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
948
949 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
950 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
951
952 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
953 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
954
955 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
956 ]
957
958 if (this.isUserLoggedIn()) {
959 this.hotkeys = this.hotkeys.concat([
960 new Hotkey('shift+l', () => {
961 this.setLike()
962 return false
963 }, undefined, $localize`Like the video`),
964
965 new Hotkey('shift+d', () => {
966 this.setDislike()
967 return false
968 }, undefined, $localize`Dislike the video`),
969
970 new Hotkey('shift+s', () => {
971 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
972 return false
973 }, undefined, $localize`Subscribe to the account`)
974 ])
975 }
976
977 this.hotkeysService.add(this.hotkeys)
978 }
979 }