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