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