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