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