]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
aacd697cff7f89b67d3712f9c2c9b47c2e914a26
[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 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 let startTime = timeToInt(urlOptions.startTime) || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
395 // If we are at the end of the video, reset the timer
396 if (this.video.duration - startTime <= 1) startTime = 0
397
398 if (this.isVideoBlur(this.video)) {
399 const res = await this.confirmService.confirm(
400 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
401 this.i18n('Mature or explicit content')
402 )
403 if (res === false) return this.location.back()
404 }
405
406 // Flush old player if needed
407 this.flushPlayer()
408
409 // Build video element, because videojs removes it on dispose
410 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
411 this.playerElement = document.createElement('video')
412 this.playerElement.className = 'video-js vjs-peertube-skin'
413 this.playerElement.setAttribute('playsinline', 'true')
414 playerElementWrapper.appendChild(this.playerElement)
415
416 const playerCaptions = videoCaptions.map(c => ({
417 label: c.language.label,
418 language: c.language.id,
419 src: environment.apiUrl + c.captionPath
420 }))
421
422 const options: PeertubePlayerManagerOptions = {
423 common: {
424 autoplay: this.isAutoplay(),
425
426 playerElement: this.playerElement,
427 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
428
429 videoDuration: this.video.duration,
430 enableHotkeys: true,
431 inactivityTimeout: 2500,
432 poster: this.video.previewUrl,
433
434 startTime,
435 stopTime: urlOptions.stopTime,
436 controls: urlOptions.controls,
437 muted: urlOptions.muted,
438 loop: urlOptions.loop,
439 subtitle: urlOptions.subtitle,
440
441 peertubeLink: urlOptions.peertubeLink,
442
443 theaterMode: true,
444 captions: videoCaptions.length !== 0,
445
446 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE
447 ? this.videoService.getVideoViewUrl(this.video.uuid)
448 : null,
449 embedUrl: this.video.embedUrl,
450
451 language: this.localeId,
452
453 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
454 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
455 authorizationHeader: this.authService.getRequestHeaderValue()
456 } : undefined,
457
458 serverUrl: environment.apiUrl,
459
460 videoCaptions: playerCaptions
461 },
462
463 webtorrent: {
464 videoFiles: this.video.files
465 }
466 }
467
468 let mode: PlayerMode
469
470 if (urlOptions.playerMode) {
471 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
472 else mode = 'webtorrent'
473 } else {
474 if (this.video.hasHlsPlaylist()) mode = 'p2p-media-loader'
475 else mode = 'webtorrent'
476 }
477
478 if (mode === 'p2p-media-loader') {
479 const hlsPlaylist = this.video.getHlsPlaylist()
480
481 const p2pMediaLoader = {
482 playlistUrl: hlsPlaylist.playlistUrl,
483 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
484 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
485 trackerAnnounce: this.video.trackerUrls,
486 videoFiles: hlsPlaylist.files
487 } as P2PMediaLoaderOptions
488
489 Object.assign(options, { p2pMediaLoader })
490 }
491
492 this.zone.runOutsideAngular(async () => {
493 this.player = await PeertubePlayerManager.initialize(mode, options, player => this.player = player)
494 this.player.focus()
495
496 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
497
498 this.player.on('timeupdate', () => {
499 this.currentTime = Math.floor(this.player.currentTime())
500 })
501
502 this.player.one('ended', () => {
503 if (this.playlist) {
504 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
505 } else if (this.user && this.user.autoPlayNextVideo) {
506 this.zone.run(() => this.autoplayNext())
507 }
508 })
509
510 this.player.one('stopped', () => {
511 if (this.playlist) {
512 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
513 }
514 })
515
516 this.player.on('theaterChange', (_: any, enabled: boolean) => {
517 this.zone.run(() => this.theaterEnabled = enabled)
518 })
519
520 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
521 })
522
523 this.setVideoDescriptionHTML()
524 this.setVideoLikesBarTooltipText()
525
526 this.setOpenGraphTags()
527 this.checkUserRating()
528
529 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
530 }
531
532 private autoplayNext () {
533 if (this.nextVideoUuid) {
534 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
535 }
536 }
537
538 private setRating (nextRating: UserVideoRateType) {
539 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
540 like: this.videoService.setVideoLike,
541 dislike: this.videoService.setVideoDislike,
542 none: this.videoService.unsetVideoLike
543 }
544
545 ratingMethods[nextRating].call(this.videoService, this.video.id)
546 .subscribe(
547 () => {
548 // Update the video like attribute
549 this.updateVideoRating(this.userRating, nextRating)
550 this.userRating = nextRating
551 },
552
553 (err: { message: string }) => this.notifier.error(err.message)
554 )
555 }
556
557 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
558 let likesToIncrement = 0
559 let dislikesToIncrement = 0
560
561 if (oldRating) {
562 if (oldRating === 'like') likesToIncrement--
563 if (oldRating === 'dislike') dislikesToIncrement--
564 }
565
566 if (newRating === 'like') likesToIncrement++
567 if (newRating === 'dislike') dislikesToIncrement++
568
569 this.video.likes += likesToIncrement
570 this.video.dislikes += dislikesToIncrement
571
572 this.video.buildLikeAndDislikePercents()
573 this.setVideoLikesBarTooltipText()
574 }
575
576 private setOpenGraphTags () {
577 this.metaService.setTitle(this.video.name)
578
579 this.metaService.setTag('og:type', 'video')
580
581 this.metaService.setTag('og:title', this.video.name)
582 this.metaService.setTag('name', this.video.name)
583
584 this.metaService.setTag('og:description', this.video.description)
585 this.metaService.setTag('description', this.video.description)
586
587 this.metaService.setTag('og:image', this.video.previewPath)
588
589 this.metaService.setTag('og:duration', this.video.duration.toString())
590
591 this.metaService.setTag('og:site_name', 'PeerTube')
592
593 this.metaService.setTag('og:url', window.location.href)
594 this.metaService.setTag('url', window.location.href)
595 }
596
597 private isAutoplay () {
598 // We'll jump to the thread id, so do not play the video
599 if (this.route.snapshot.params['threadId']) return false
600
601 // Otherwise true by default
602 if (!this.user) return true
603
604 // Be sure the autoPlay is set to false
605 return this.user.autoPlayVideo !== false
606 }
607
608 private flushPlayer () {
609 // Remove player if it exists
610 if (this.player) {
611 try {
612 this.player.dispose()
613 this.player = undefined
614 } catch (err) {
615 console.error('Cannot dispose player.', err)
616 }
617 }
618 }
619
620 private initHotkeys () {
621 this.hotkeys = [
622 new Hotkey('shift+l', () => {
623 this.setLike()
624 return false
625 }, undefined, this.i18n('Like the video')),
626
627 new Hotkey('shift+d', () => {
628 this.setDislike()
629 return false
630 }, undefined, this.i18n('Dislike the video')),
631
632 new Hotkey('shift+s', () => {
633 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
634 return false
635 }, undefined, this.i18n('Subscribe to the account'))
636 ]
637 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
638 }
639
640 private pausePlayer () {
641 if (!this.player) return
642
643 this.player.pause()
644 }
645 }