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