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