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