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