]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Add hook to alter player build options
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
1 import { catchError } from 'rxjs/operators'
2 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { RedirectService } from '@app/core/routing/redirect.service'
5 import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
6 import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
7 import { MetaService } from '@ngx-meta/core'
8 import { AuthUser, Notifier, ServerService } from '@app/core'
9 import { forkJoin, Observable, Subscription } from 'rxjs'
10 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
11 import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
12 import { AuthService, ConfirmService } from '../../core'
13 import { RestExtractor, VideoBlacklistService } from '../../shared'
14 import { VideoDetails } from '../../shared/video/video-details.model'
15 import { VideoService } from '../../shared/video/video.service'
16 import { VideoShareComponent } from './modal/video-share.component'
17 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
18 import { I18n } from '@ngx-translate/i18n-polyfill'
19 import { environment } from '../../../environments/environment'
20 import { VideoCaptionService } from '@app/shared/video-caption'
21 import { MarkdownService } from '@app/shared/renderer'
22 import {
23 videojs,
24 CustomizationOptions,
25 P2PMediaLoaderOptions,
26 PeertubePlayerManager,
27 PeertubePlayerManagerOptions,
28 PlayerMode
29 } from '../../../assets/player/peertube-player-manager'
30 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
31 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
32 import { Video } from '@app/shared/video/video.model'
33 import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
34 import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
35 import { getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
36 import { PluginService } from '@app/core/plugins/plugin.service'
37 import { HooksService } from '@app/core/plugins/hooks.service'
38 import { PlatformLocation } from '@angular/common'
39 import { randomInt } from '@shared/core-utils/miscs/miscs'
40
41 @Component({
42 selector: 'my-video-watch',
43 templateUrl: './video-watch.component.html',
44 styleUrls: [ './video-watch.component.scss' ]
45 })
46 export class VideoWatchComponent implements OnInit, OnDestroy {
47 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
48
49 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
50 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
51 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
52 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
53
54 player: any
55 playerElement: HTMLVideoElement
56 theaterEnabled = false
57 userRating: UserVideoRateType = null
58 descriptionLoading = false
59
60 video: VideoDetails = null
61 videoCaptions: VideoCaption[] = []
62
63 playlist: VideoPlaylist = null
64
65 completeDescriptionShown = false
66 completeVideoDescription: string
67 shortVideoDescription: string
68 videoHTMLDescription = ''
69 likesBarTooltipText = ''
70 hasAlreadyAcceptedPrivacyConcern = false
71 remoteServerDown = false
72 hotkeys: Hotkey[]
73
74 private nextVideoUuid = ''
75 private currentTime: number
76 private paramsSub: Subscription
77 private queryParamsSub: Subscription
78 private configSub: Subscription
79
80 constructor (
81 private elementRef: ElementRef,
82 private changeDetector: ChangeDetectorRef,
83 private route: ActivatedRoute,
84 private router: Router,
85 private videoService: VideoService,
86 private playlistService: VideoPlaylistService,
87 private videoBlacklistService: VideoBlacklistService,
88 private confirmService: ConfirmService,
89 private metaService: MetaService,
90 private authService: AuthService,
91 private serverService: ServerService,
92 private restExtractor: RestExtractor,
93 private notifier: Notifier,
94 private pluginService: PluginService,
95 private markdownService: MarkdownService,
96 private zone: NgZone,
97 private redirectService: RedirectService,
98 private videoCaptionService: VideoCaptionService,
99 private i18n: I18n,
100 private hotkeysService: HotkeysService,
101 private hooks: HooksService,
102 private location: PlatformLocation,
103 @Inject(LOCALE_ID) private localeId: string
104 ) {}
105
106 get user () {
107 return this.authService.getUser()
108 }
109
110 async ngOnInit () {
111 this.configSub = this.serverService.configLoaded
112 .subscribe(() => {
113 if (
114 isWebRTCDisabled() ||
115 this.serverService.getConfig().tracker.enabled === false ||
116 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
117 ) {
118 this.hasAlreadyAcceptedPrivacyConcern = true
119 }
120 })
121
122 this.paramsSub = this.route.params.subscribe(routeParams => {
123 const videoId = routeParams[ 'videoId' ]
124 if (videoId) this.loadVideo(videoId)
125
126 const playlistId = routeParams[ 'playlistId' ]
127 if (playlistId) this.loadPlaylist(playlistId)
128 })
129
130 this.queryParamsSub = this.route.queryParams.subscribe(queryParams => {
131 const videoId = queryParams[ 'videoId' ]
132 if (videoId) this.loadVideo(videoId)
133 })
134
135 this.initHotkeys()
136
137 this.theaterEnabled = getStoredTheater()
138
139 this.hooks.runAction('action:video-watch.init', 'video-watch')
140 }
141
142 ngOnDestroy () {
143 this.flushPlayer()
144
145 // Unsubscribe subscriptions
146 if (this.paramsSub) this.paramsSub.unsubscribe()
147 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
148
149 // Unbind hotkeys
150 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
151 }
152
153 setLike () {
154 if (this.isUserLoggedIn() === false) return
155
156 // Already liked this video
157 if (this.userRating === 'like') this.setRating('none')
158 else this.setRating('like')
159 }
160
161 setDislike () {
162 if (this.isUserLoggedIn() === false) return
163
164 // Already disliked this video
165 if (this.userRating === 'dislike') this.setRating('none')
166 else this.setRating('dislike')
167 }
168
169 getRatePopoverText () {
170 if (this.isUserLoggedIn()) return undefined
171
172 return this.i18n('You need to be connected to rate this content.')
173 }
174
175 showMoreDescription () {
176 if (this.completeVideoDescription === undefined) {
177 return this.loadCompleteDescription()
178 }
179
180 this.updateVideoDescription(this.completeVideoDescription)
181 this.completeDescriptionShown = true
182 }
183
184 showLessDescription () {
185 this.updateVideoDescription(this.shortVideoDescription)
186 this.completeDescriptionShown = false
187 }
188
189 loadCompleteDescription () {
190 this.descriptionLoading = true
191
192 this.videoService.loadCompleteDescription(this.video.descriptionPath)
193 .subscribe(
194 description => {
195 this.completeDescriptionShown = true
196 this.descriptionLoading = false
197
198 this.shortVideoDescription = this.video.description
199 this.completeVideoDescription = description
200
201 this.updateVideoDescription(this.completeVideoDescription)
202 },
203
204 error => {
205 this.descriptionLoading = false
206 this.notifier.error(error.message)
207 }
208 )
209 }
210
211 showSupportModal () {
212 this.pausePlayer()
213
214 this.videoSupportModal.show()
215 }
216
217 showShareModal () {
218 this.pausePlayer()
219
220 this.videoShareModal.show(this.currentTime)
221 }
222
223 isUserLoggedIn () {
224 return this.authService.isLoggedIn()
225 }
226
227 getVideoTags () {
228 if (!this.video || Array.isArray(this.video.tags) === false) return []
229
230 return this.video.tags
231 }
232
233 onRecommendations (videos: Video[]) {
234 if (videos.length > 0) {
235 // Pick a random video until the recommendations are improved
236 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
237 }
238 }
239
240 onModalOpened () {
241 this.pausePlayer()
242 }
243
244 onVideoRemoved () {
245 this.redirectService.redirectToHomepage()
246 }
247
248 acceptedPrivacyConcern () {
249 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
250 this.hasAlreadyAcceptedPrivacyConcern = true
251 }
252
253 isVideoToTranscode () {
254 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
255 }
256
257 isVideoToImport () {
258 return this.video && this.video.state.id === VideoState.TO_IMPORT
259 }
260
261 hasVideoScheduledPublication () {
262 return this.video && this.video.scheduledUpdate !== undefined
263 }
264
265 isVideoBlur (video: Video) {
266 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
267 }
268
269 private loadVideo (videoId: string) {
270 // Video did not change
271 if (this.video && this.video.uuid === videoId) return
272
273 if (this.player) this.player.pause()
274
275 const videoObs = this.hooks.wrapObsFun(
276 this.videoService.getVideo.bind(this.videoService),
277 { videoId },
278 'video-watch',
279 'filter:api.video-watch.video.get.params',
280 'filter:api.video-watch.video.get.result'
281 )
282
283 // Video did change
284 forkJoin([
285 videoObs,
286 this.videoCaptionService.listCaptions(videoId)
287 ])
288 .pipe(
289 // If 401, the video is private or blacklisted so redirect to 404
290 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
291 )
292 .subscribe(([ video, captionsResult ]) => {
293 const queryParams = this.route.snapshot.queryParams
294
295 const urlOptions = {
296 startTime: queryParams.start,
297 stopTime: queryParams.stop,
298
299 muted: queryParams.muted,
300 loop: queryParams.loop,
301 subtitle: queryParams.subtitle,
302
303 playerMode: queryParams.mode,
304 peertubeLink: false
305 }
306
307 this.onVideoFetched(video, captionsResult.data, urlOptions)
308 .catch(err => this.handleError(err))
309 })
310 }
311
312 private loadPlaylist (playlistId: string) {
313 // Playlist did not change
314 if (this.playlist && this.playlist.uuid === playlistId) return
315
316 this.playlistService.getVideoPlaylist(playlistId)
317 .pipe(
318 // If 401, the video is private or blacklisted so redirect to 404
319 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
320 )
321 .subscribe(playlist => {
322 this.playlist = playlist
323
324 const videoId = this.route.snapshot.queryParams['videoId']
325 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
326 })
327 }
328
329 private updateVideoDescription (description: string) {
330 this.video.description = description
331 this.setVideoDescriptionHTML()
332 .catch(err => console.error(err))
333 }
334
335 private async setVideoDescriptionHTML () {
336 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
337 }
338
339 private setVideoLikesBarTooltipText () {
340 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
341 likesNumber: this.video.likes,
342 dislikesNumber: this.video.dislikes
343 })
344 }
345
346 private handleError (err: any) {
347 const errorMessage: string = typeof err === 'string' ? err : err.message
348 if (!errorMessage) return
349
350 // Display a message in the video player instead of a notification
351 if (errorMessage.indexOf('from xs param') !== -1) {
352 this.flushPlayer()
353 this.remoteServerDown = true
354 this.changeDetector.detectChanges()
355
356 return
357 }
358
359 this.notifier.error(errorMessage)
360 }
361
362 private checkUserRating () {
363 // Unlogged users do not have ratings
364 if (this.isUserLoggedIn() === false) return
365
366 this.videoService.getUserVideoRating(this.video.id)
367 .subscribe(
368 ratingObject => {
369 if (ratingObject) {
370 this.userRating = ratingObject.rating
371 }
372 },
373
374 err => this.notifier.error(err.message)
375 )
376 }
377
378 private async onVideoFetched (
379 video: VideoDetails,
380 videoCaptions: VideoCaption[],
381 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
382 ) {
383 this.video = video
384 this.videoCaptions = videoCaptions
385
386 // Re init attributes
387 this.descriptionLoading = false
388 this.completeDescriptionShown = false
389 this.remoteServerDown = false
390 this.currentTime = undefined
391
392 this.videoWatchPlaylist.updatePlaylistIndex(video)
393
394 if (this.isVideoBlur(this.video)) {
395 const res = await this.confirmService.confirm(
396 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
397 this.i18n('Mature or explicit content')
398 )
399 if (res === false) return this.location.back()
400 }
401
402 // Flush old player if needed
403 this.flushPlayer()
404
405 // Build video element, because videojs removes it on dispose
406 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
407 this.playerElement = document.createElement('video')
408 this.playerElement.className = 'video-js vjs-peertube-skin'
409 this.playerElement.setAttribute('playsinline', 'true')
410 playerElementWrapper.appendChild(this.playerElement)
411
412 const params = {
413 video: this.video,
414 videoCaptions,
415 urlOptions,
416 user: this.user
417 }
418 const { playerMode, playerOptions } = await this.hooks.wrapFun(
419 this.buildPlayerManagerOptions.bind(this),
420 params,
421 'filter:internal.video-watch.player.build-options.result'
422 )
423
424 this.zone.runOutsideAngular(async () => {
425 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
426 this.player.focus()
427
428 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
429
430 this.player.on('timeupdate', () => {
431 this.currentTime = Math.floor(this.player.currentTime())
432 })
433
434 this.player.one('ended', () => {
435 if (this.playlist) {
436 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
437 } else if (this.user && this.user.autoPlayNextVideo) {
438 this.zone.run(() => this.autoplayNext())
439 }
440 })
441
442 this.player.one('stopped', () => {
443 if (this.playlist) {
444 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
445 }
446 })
447
448 this.player.on('theaterChange', (_: any, enabled: boolean) => {
449 this.zone.run(() => this.theaterEnabled = enabled)
450 })
451
452 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
453 })
454
455 this.setVideoDescriptionHTML()
456 this.setVideoLikesBarTooltipText()
457
458 this.setOpenGraphTags()
459 this.checkUserRating()
460
461 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
462 }
463
464 private autoplayNext () {
465 if (this.nextVideoUuid) {
466 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
467 }
468 }
469
470 private setRating (nextRating: UserVideoRateType) {
471 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
472 like: this.videoService.setVideoLike,
473 dislike: this.videoService.setVideoDislike,
474 none: this.videoService.unsetVideoLike
475 }
476
477 ratingMethods[nextRating].call(this.videoService, this.video.id)
478 .subscribe(
479 () => {
480 // Update the video like attribute
481 this.updateVideoRating(this.userRating, nextRating)
482 this.userRating = nextRating
483 },
484
485 (err: { message: string }) => this.notifier.error(err.message)
486 )
487 }
488
489 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
490 let likesToIncrement = 0
491 let dislikesToIncrement = 0
492
493 if (oldRating) {
494 if (oldRating === 'like') likesToIncrement--
495 if (oldRating === 'dislike') dislikesToIncrement--
496 }
497
498 if (newRating === 'like') likesToIncrement++
499 if (newRating === 'dislike') dislikesToIncrement++
500
501 this.video.likes += likesToIncrement
502 this.video.dislikes += dislikesToIncrement
503
504 this.video.buildLikeAndDislikePercents()
505 this.setVideoLikesBarTooltipText()
506 }
507
508 private setOpenGraphTags () {
509 this.metaService.setTitle(this.video.name)
510
511 this.metaService.setTag('og:type', 'video')
512
513 this.metaService.setTag('og:title', this.video.name)
514 this.metaService.setTag('name', this.video.name)
515
516 this.metaService.setTag('og:description', this.video.description)
517 this.metaService.setTag('description', this.video.description)
518
519 this.metaService.setTag('og:image', this.video.previewPath)
520
521 this.metaService.setTag('og:duration', this.video.duration.toString())
522
523 this.metaService.setTag('og:site_name', 'PeerTube')
524
525 this.metaService.setTag('og:url', window.location.href)
526 this.metaService.setTag('url', window.location.href)
527 }
528
529 private isAutoplay () {
530 // We'll jump to the thread id, so do not play the video
531 if (this.route.snapshot.params['threadId']) return false
532
533 // Otherwise true by default
534 if (!this.user) return true
535
536 // Be sure the autoPlay is set to false
537 return this.user.autoPlayVideo !== false
538 }
539
540 private flushPlayer () {
541 // Remove player if it exists
542 if (this.player) {
543 try {
544 this.player.dispose()
545 this.player = undefined
546 } catch (err) {
547 console.error('Cannot dispose player.', err)
548 }
549 }
550 }
551
552 private initHotkeys () {
553 this.hotkeys = [
554 new Hotkey('shift+l', () => {
555 this.setLike()
556 return false
557 }, undefined, this.i18n('Like the video')),
558
559 new Hotkey('shift+d', () => {
560 this.setDislike()
561 return false
562 }, undefined, this.i18n('Dislike the video')),
563
564 new Hotkey('shift+s', () => {
565 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
566 return false
567 }, undefined, this.i18n('Subscribe to the account'))
568 ]
569 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
570 }
571
572 private buildPlayerManagerOptions (params: {
573 video: VideoDetails,
574 videoCaptions: VideoCaption[],
575 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
576 user?: AuthUser
577 }) {
578 const { video, videoCaptions, urlOptions, user } = params
579
580 let startTime = timeToInt(urlOptions.startTime) || (video.userHistory ? video.userHistory.currentTime : 0)
581 // If we are at the end of the video, reset the timer
582 if (video.duration - startTime <= 1) startTime = 0
583
584 const playerCaptions = videoCaptions.map(c => ({
585 label: c.language.label,
586 language: c.language.id,
587 src: environment.apiUrl + c.captionPath
588 }))
589
590 const options: PeertubePlayerManagerOptions = {
591 common: {
592 autoplay: this.isAutoplay(),
593
594 playerElement: this.playerElement,
595 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
596
597 videoDuration: video.duration,
598 enableHotkeys: true,
599 inactivityTimeout: 2500,
600 poster: video.previewUrl,
601
602 startTime,
603 stopTime: urlOptions.stopTime,
604 controls: urlOptions.controls,
605 muted: urlOptions.muted,
606 loop: urlOptions.loop,
607 subtitle: urlOptions.subtitle,
608
609 peertubeLink: urlOptions.peertubeLink,
610
611 theaterButton: true,
612 captions: videoCaptions.length !== 0,
613
614 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
615 ? this.videoService.getVideoViewUrl(video.uuid)
616 : null,
617 embedUrl: video.embedUrl,
618
619 language: this.localeId,
620
621 userWatching: user && user.videosHistoryEnabled === true ? {
622 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
623 authorizationHeader: this.authService.getRequestHeaderValue()
624 } : undefined,
625
626 serverUrl: environment.apiUrl,
627
628 videoCaptions: playerCaptions
629 },
630
631 webtorrent: {
632 videoFiles: video.files
633 }
634 }
635
636 let mode: PlayerMode
637
638 if (urlOptions.playerMode) {
639 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
640 else mode = 'webtorrent'
641 } else {
642 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
643 else mode = 'webtorrent'
644 }
645
646 if (mode === 'p2p-media-loader') {
647 const hlsPlaylist = video.getHlsPlaylist()
648
649 const p2pMediaLoader = {
650 playlistUrl: hlsPlaylist.playlistUrl,
651 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
652 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
653 trackerAnnounce: video.trackerUrls,
654 videoFiles: hlsPlaylist.files
655 } as P2PMediaLoaderOptions
656
657 Object.assign(options, { p2pMediaLoader })
658 }
659
660 return { playerMode: mode, playerOptions: options }
661 }
662
663 private pausePlayer () {
664 if (!this.player) return
665
666 this.player.pause()
667 }
668 }