]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Improve 4k resolution bitrate
[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 { 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 showMoreDescription () {
170 if (this.completeVideoDescription === undefined) {
171 return this.loadCompleteDescription()
172 }
173
174 this.updateVideoDescription(this.completeVideoDescription)
175 this.completeDescriptionShown = true
176 }
177
178 showLessDescription () {
179 this.updateVideoDescription(this.shortVideoDescription)
180 this.completeDescriptionShown = false
181 }
182
183 loadCompleteDescription () {
184 this.descriptionLoading = true
185
186 this.videoService.loadCompleteDescription(this.video.descriptionPath)
187 .subscribe(
188 description => {
189 this.completeDescriptionShown = true
190 this.descriptionLoading = false
191
192 this.shortVideoDescription = this.video.description
193 this.completeVideoDescription = description
194
195 this.updateVideoDescription(this.completeVideoDescription)
196 },
197
198 error => {
199 this.descriptionLoading = false
200 this.notifier.error(error.message)
201 }
202 )
203 }
204
205 showSupportModal () {
206 this.pausePlayer()
207
208 this.videoSupportModal.show()
209 }
210
211 showShareModal () {
212 this.pausePlayer()
213
214 this.videoShareModal.show(this.currentTime)
215 }
216
217 isUserLoggedIn () {
218 return this.authService.isLoggedIn()
219 }
220
221 getVideoTags () {
222 if (!this.video || Array.isArray(this.video.tags) === false) return []
223
224 return this.video.tags
225 }
226
227 onRecommendations (videos: Video[]) {
228 if (videos.length > 0) {
229 // Pick a random video until the recommendations are improved
230 this.nextVideoUuid = videos[randomInt(0,videos.length - 1)].uuid
231 }
232 }
233
234 onModalOpened () {
235 this.pausePlayer()
236 }
237
238 onVideoRemoved () {
239 this.redirectService.redirectToHomepage()
240 }
241
242 acceptedPrivacyConcern () {
243 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
244 this.hasAlreadyAcceptedPrivacyConcern = true
245 }
246
247 isVideoToTranscode () {
248 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
249 }
250
251 isVideoToImport () {
252 return this.video && this.video.state.id === VideoState.TO_IMPORT
253 }
254
255 hasVideoScheduledPublication () {
256 return this.video && this.video.scheduledUpdate !== undefined
257 }
258
259 isVideoBlur (video: Video) {
260 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
261 }
262
263 private loadVideo (videoId: string) {
264 // Video did not change
265 if (this.video && this.video.uuid === videoId) return
266
267 if (this.player) this.player.pause()
268
269 const videoObs = this.hooks.wrapObsFun(
270 this.videoService.getVideo.bind(this.videoService),
271 { videoId },
272 'video-watch',
273 'filter:api.video-watch.video.get.params',
274 'filter:api.video-watch.video.get.result'
275 )
276
277 // Video did change
278 forkJoin([
279 videoObs,
280 this.videoCaptionService.listCaptions(videoId)
281 ])
282 .pipe(
283 // If 401, the video is private or blacklisted so redirect to 404
284 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
285 )
286 .subscribe(([ video, captionsResult ]) => {
287 const queryParams = this.route.snapshot.queryParams
288
289 const urlOptions = {
290 startTime: queryParams.start,
291 stopTime: queryParams.stop,
292
293 muted: queryParams.muted,
294 loop: queryParams.loop,
295 subtitle: queryParams.subtitle,
296
297 playerMode: queryParams.mode,
298 peertubeLink: false
299 }
300
301 this.onVideoFetched(video, captionsResult.data, urlOptions)
302 .catch(err => this.handleError(err))
303 })
304 }
305
306 private loadPlaylist (playlistId: string) {
307 // Playlist did not change
308 if (this.playlist && this.playlist.uuid === playlistId) return
309
310 this.playlistService.getVideoPlaylist(playlistId)
311 .pipe(
312 // If 401, the video is private or blacklisted so redirect to 404
313 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
314 )
315 .subscribe(playlist => {
316 this.playlist = playlist
317
318 const videoId = this.route.snapshot.queryParams['videoId']
319 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
320 })
321 }
322
323 private updateVideoDescription (description: string) {
324 this.video.description = description
325 this.setVideoDescriptionHTML()
326 .catch(err => console.error(err))
327 }
328
329 private async setVideoDescriptionHTML () {
330 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
331 }
332
333 private setVideoLikesBarTooltipText () {
334 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
335 likesNumber: this.video.likes,
336 dislikesNumber: this.video.dislikes
337 })
338 }
339
340 private handleError (err: any) {
341 const errorMessage: string = typeof err === 'string' ? err : err.message
342 if (!errorMessage) return
343
344 // Display a message in the video player instead of a notification
345 if (errorMessage.indexOf('from xs param') !== -1) {
346 this.flushPlayer()
347 this.remoteServerDown = true
348 this.changeDetector.detectChanges()
349
350 return
351 }
352
353 this.notifier.error(errorMessage)
354 }
355
356 private checkUserRating () {
357 // Unlogged users do not have ratings
358 if (this.isUserLoggedIn() === false) return
359
360 this.videoService.getUserVideoRating(this.video.id)
361 .subscribe(
362 ratingObject => {
363 if (ratingObject) {
364 this.userRating = ratingObject.rating
365 }
366 },
367
368 err => this.notifier.error(err.message)
369 )
370 }
371
372 private async onVideoFetched (
373 video: VideoDetails,
374 videoCaptions: VideoCaption[],
375 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
376 ) {
377 this.video = video
378 this.videoCaptions = videoCaptions
379
380 // Re init attributes
381 this.descriptionLoading = false
382 this.completeDescriptionShown = false
383 this.remoteServerDown = false
384 this.currentTime = undefined
385
386 this.videoWatchPlaylist.updatePlaylistIndex(video)
387
388 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
389 // If we are at the end of the video, reset the timer
390 if (this.video.duration - startTime <= 1) startTime = 0
391
392 if (this.isVideoBlur(this.video)) {
393 const res = await this.confirmService.confirm(
394 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
395 this.i18n('Mature or explicit content')
396 )
397 if (res === false) return this.location.back()
398 }
399
400 // Flush old player if needed
401 this.flushPlayer()
402
403 // Build video element, because videojs removes it on dispose
404 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
405 this.playerElement = document.createElement('video')
406 this.playerElement.className = 'video-js vjs-peertube-skin'
407 this.playerElement.setAttribute('playsinline', 'true')
408 playerElementWrapper.appendChild(this.playerElement)
409
410 const playerCaptions = videoCaptions.map(c => ({
411 label: c.language.label,
412 language: c.language.id,
413 src: environment.apiUrl + c.captionPath
414 }))
415
416 const options: PeertubePlayerManagerOptions = {
417 common: {
418 autoplay: this.isAutoplay(),
419
420 playerElement: this.playerElement,
421 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
422
423 videoDuration: this.video.duration,
424 enableHotkeys: true,
425 inactivityTimeout: 2500,
426 poster: this.video.previewUrl,
427
428 startTime,
429 stopTime: urlOptions.stopTime,
430 controls: urlOptions.controls,
431 muted: urlOptions.muted,
432 loop: urlOptions.loop,
433 subtitle: urlOptions.subtitle,
434
435 peertubeLink: urlOptions.peertubeLink,
436
437 theaterMode: true,
438 captions: videoCaptions.length !== 0,
439
440 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
441 ? this.videoService.getVideoViewUrl(this.video.uuid)
442 : null,
443 embedUrl: this.video.embedUrl,
444
445 language: this.localeId,
446
447 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
448 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
449 authorizationHeader: this.authService.getRequestHeaderValue()
450 } : undefined,
451
452 serverUrl: environment.apiUrl,
453
454 videoCaptions: playerCaptions
455 },
456
457 webtorrent: {
458 videoFiles: this.video.files
459 }
460 }
461
462 let mode: PlayerMode
463
464 if (urlOptions.playerMode) {
465 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
466 else mode = 'webtorrent'
467 } else {
468 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
469 else mode = 'webtorrent'
470 }
471
472 if (mode === 'p2p-media-loader') {
473 const hlsPlaylist = this.video.getHlsPlaylist()
474
475 const p2pMediaLoader = {
476 playlistUrl: hlsPlaylist.playlistUrl,
477 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
478 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
479 trackerAnnounce: this.video.trackerUrls,
480 videoFiles: hlsPlaylist.files
481 } as P2PMediaLoaderOptions
482
483 Object.assign(options, { p2pMediaLoader })
484 }
485
486 this.zone.runOutsideAngular(async () => {
487 this.player = await PeertubePlayerManager.initialize(mode, options, player => this.player = player)
488 this.player.focus()
489
490 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
491
492 this.player.on('timeupdate', () => {
493 this.currentTime = Math.floor(this.player.currentTime())
494 })
495
496 this.player.one('ended', () => {
497 if (this.playlist) {
498 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
499 } else if (this.user && this.user.autoPlayNextVideo) {
500 this.zone.run(() => this.autoplayNext())
501 }
502 })
503
504 this.player.one('stopped', () => {
505 if (this.playlist) {
506 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
507 }
508 })
509
510 this.player.on('theaterChange', (_: any, enabled: boolean) => {
511 this.zone.run(() => this.theaterEnabled = enabled)
512 })
513
514 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
515 })
516
517 this.setVideoDescriptionHTML()
518 this.setVideoLikesBarTooltipText()
519
520 this.setOpenGraphTags()
521 this.checkUserRating()
522
523 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
524 }
525
526 private autoplayNext () {
527 if (this.nextVideoUuid) {
528 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
529 }
530 }
531
532 private setRating (nextRating: UserVideoRateType) {
533 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
534 like: this.videoService.setVideoLike,
535 dislike: this.videoService.setVideoDislike,
536 none: this.videoService.unsetVideoLike
537 }
538
539 ratingMethods[nextRating].call(this.videoService, this.video.id)
540 .subscribe(
541 () => {
542 // Update the video like attribute
543 this.updateVideoRating(this.userRating, nextRating)
544 this.userRating = nextRating
545 },
546
547 (err: { message: string }) => this.notifier.error(err.message)
548 )
549 }
550
551 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
552 let likesToIncrement = 0
553 let dislikesToIncrement = 0
554
555 if (oldRating) {
556 if (oldRating === 'like') likesToIncrement--
557 if (oldRating === 'dislike') dislikesToIncrement--
558 }
559
560 if (newRating === 'like') likesToIncrement++
561 if (newRating === 'dislike') dislikesToIncrement++
562
563 this.video.likes += likesToIncrement
564 this.video.dislikes += dislikesToIncrement
565
566 this.video.buildLikeAndDislikePercents()
567 this.setVideoLikesBarTooltipText()
568 }
569
570 private setOpenGraphTags () {
571 this.metaService.setTitle(this.video.name)
572
573 this.metaService.setTag('og:type', 'video')
574
575 this.metaService.setTag('og:title', this.video.name)
576 this.metaService.setTag('name', this.video.name)
577
578 this.metaService.setTag('og:description', this.video.description)
579 this.metaService.setTag('description', this.video.description)
580
581 this.metaService.setTag('og:image', this.video.previewPath)
582
583 this.metaService.setTag('og:duration', this.video.duration.toString())
584
585 this.metaService.setTag('og:site_name', 'PeerTube')
586
587 this.metaService.setTag('og:url', window.location.href)
588 this.metaService.setTag('url', window.location.href)
589 }
590
591 private isAutoplay () {
592 // We'll jump to the thread id, so do not play the video
593 if (this.route.snapshot.params['threadId']) return false
594
595 // Otherwise true by default
596 if (!this.user) return true
597
598 // Be sure the autoPlay is set to false
599 return this.user.autoPlayVideo !== false
600 }
601
602 private flushPlayer () {
603 // Remove player if it exists
604 if (this.player) {
605 try {
606 this.player.dispose()
607 this.player = undefined
608 } catch (err) {
609 console.error('Cannot dispose player.', err)
610 }
611 }
612 }
613
614 private initHotkeys () {
615 this.hotkeys = [
616 new Hotkey('shift+l', () => {
617 this.setLike()
618 return false
619 }, undefined, this.i18n('Like the video')),
620
621 new Hotkey('shift+d', () => {
622 this.setDislike()
623 return false
624 }, undefined, this.i18n('Dislike the video')),
625
626 new Hotkey('shift+s', () => {
627 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
628 return false
629 }, undefined, this.i18n('Subscribe to the account'))
630 ]
631 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
632 }
633
634 private pausePlayer () {
635 if (!this.player) return
636
637 this.player.pause()
638 }
639 }