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