]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Handle theater mode for playlists
[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 { VideoDownloadComponent } from './modal/video-download.component'
17 import { VideoReportComponent } from './modal/video-report.component'
18 import { VideoShareComponent } from './modal/video-share.component'
19 import { VideoBlacklistComponent } from './modal/video-blacklist.component'
20 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
21 import { I18n } from '@ngx-translate/i18n-polyfill'
22 import { environment } from '../../../environments/environment'
23 import { VideoCaptionService } from '@app/shared/video-caption'
24 import { MarkdownService } from '@app/shared/renderer'
25 import {
26 P2PMediaLoaderOptions,
27 PeertubePlayerManager,
28 PeertubePlayerManagerOptions,
29 PlayerMode
30 } from '../../../assets/player/peertube-player-manager'
31 import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
32 import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
33 import { ComponentPagination } from '@app/shared/rest/component-pagination.model'
34 import { Video } from '@app/shared/video/video.model'
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('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
45 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
46 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
47 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
48 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
49 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
50
51 player: any
52 playerElement: HTMLVideoElement
53 theaterEnabled = false
54 userRating: UserVideoRateType = null
55 video: VideoDetails = null
56 descriptionLoading = false
57
58 playlist: VideoPlaylist = null
59 playlistVideos: Video[] = []
60 playlistPagination: ComponentPagination = {
61 currentPage: 1,
62 itemsPerPage: 30,
63 totalItems: null
64 }
65 noPlaylistVideos = false
66 currentPlaylistPosition = 1
67
68 completeDescriptionShown = false
69 completeVideoDescription: string
70 shortVideoDescription: string
71 videoHTMLDescription = ''
72 likesBarTooltipText = ''
73 hasAlreadyAcceptedPrivacyConcern = false
74 remoteServerDown = false
75 hotkeys: Hotkey[]
76
77 private currentTime: number
78 private paramsSub: Subscription
79 private queryParamsSub: Subscription
80
81 constructor (
82 private elementRef: ElementRef,
83 private changeDetector: ChangeDetectorRef,
84 private route: ActivatedRoute,
85 private router: Router,
86 private videoService: VideoService,
87 private playlistService: VideoPlaylistService,
88 private videoBlacklistService: VideoBlacklistService,
89 private confirmService: ConfirmService,
90 private metaService: MetaService,
91 private authService: AuthService,
92 private serverService: ServerService,
93 private restExtractor: RestExtractor,
94 private notifier: Notifier,
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 @Inject(LOCALE_ID) private localeId: string
102 ) {}
103
104 get user () {
105 return this.authService.getUser()
106 }
107
108 ngOnInit () {
109 if (
110 !!((window as any).RTCPeerConnection || (window as any).mozRTCPeerConnection || (window as any).webkitRTCPeerConnection) === false ||
111 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
112 ) {
113 this.hasAlreadyAcceptedPrivacyConcern = true
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 showReportModal (event: Event) {
216 event.preventDefault()
217 this.videoReportModal.show()
218 }
219
220 showSupportModal () {
221 this.videoSupportModal.show()
222 }
223
224 showShareModal () {
225 this.videoShareModal.show(this.currentTime)
226 }
227
228 showDownloadModal (event: Event) {
229 event.preventDefault()
230 this.videoDownloadModal.show()
231 }
232
233 showBlacklistModal (event: Event) {
234 event.preventDefault()
235 this.videoBlacklistModal.show()
236 }
237
238 async unblacklistVideo (event: Event) {
239 event.preventDefault()
240
241 const confirmMessage = this.i18n(
242 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
243 )
244
245 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
246 if (res === false) return
247
248 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
249 () => {
250 this.notifier.success(this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name }))
251
252 this.video.blacklisted = false
253 this.video.blacklistedReason = null
254 },
255
256 err => this.notifier.error(err.message)
257 )
258 }
259
260 isUserLoggedIn () {
261 return this.authService.isLoggedIn()
262 }
263
264 isVideoUpdatable () {
265 return this.video.isUpdatableBy(this.authService.getUser())
266 }
267
268 isVideoBlacklistable () {
269 return this.video.isBlackistableBy(this.user)
270 }
271
272 isVideoUnblacklistable () {
273 return this.video.isUnblacklistableBy(this.user)
274 }
275
276 getVideoTags () {
277 if (!this.video || Array.isArray(this.video.tags) === false) return []
278
279 return this.video.tags
280 }
281
282 isVideoRemovable () {
283 return this.video.isRemovableBy(this.authService.getUser())
284 }
285
286 async removeVideo (event: Event) {
287 event.preventDefault()
288
289 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
290 if (res === false) return
291
292 this.videoService.removeVideo(this.video.id)
293 .subscribe(
294 () => {
295 this.notifier.success(this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name }))
296
297 // Go back to the video-list.
298 this.redirectService.redirectToHomepage()
299 },
300
301 error => this.notifier.error(error.message)
302 )
303 }
304
305 acceptedPrivacyConcern () {
306 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
307 this.hasAlreadyAcceptedPrivacyConcern = true
308 }
309
310 isVideoToTranscode () {
311 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
312 }
313
314 isVideoDownloadable () {
315 return this.video && this.video.downloadEnabled
316 }
317
318 isVideoToImport () {
319 return this.video && this.video.state.id === VideoState.TO_IMPORT
320 }
321
322 hasVideoScheduledPublication () {
323 return this.video && this.video.scheduledUpdate !== undefined
324 }
325
326 isVideoBlur (video: Video) {
327 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
328 }
329
330 isPlaylistOwned () {
331 return this.playlist.isLocal === true && this.playlist.ownerAccount.name === this.user.username
332 }
333
334 isUnlistedPlaylist () {
335 return this.playlist.privacy.id === VideoPlaylistPrivacy.UNLISTED
336 }
337
338 isPrivatePlaylist () {
339 return this.playlist.privacy.id === VideoPlaylistPrivacy.PRIVATE
340 }
341
342 isPublicPlaylist () {
343 return this.playlist.privacy.id === VideoPlaylistPrivacy.PUBLIC
344 }
345
346 onPlaylistVideosNearOfBottom () {
347 // Last page
348 if (this.playlistPagination.totalItems <= (this.playlistPagination.currentPage * this.playlistPagination.itemsPerPage)) return
349
350 this.playlistPagination.currentPage += 1
351 this.loadPlaylistElements(false)
352 }
353
354 onElementRemoved (video: Video) {
355 this.playlistVideos = this.playlistVideos.filter(v => v.id !== video.id)
356
357 this.playlistPagination.totalItems--
358 }
359
360 private loadVideo (videoId: string) {
361 // Video did not change
362 if (this.video && this.video.uuid === videoId) return
363
364 if (this.player) this.player.pause()
365
366 // Video did change
367 forkJoin(
368 this.videoService.getVideo(videoId),
369 this.videoCaptionService.listCaptions(videoId)
370 )
371 .pipe(
372 // If 401, the video is private or blacklisted so redirect to 404
373 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
374 )
375 .subscribe(([ video, captionsResult ]) => {
376 const queryParams = this.route.snapshot.queryParams
377 const startTime = queryParams.start
378 const stopTime = queryParams.stop
379 const subtitle = queryParams.subtitle
380 const playerMode = queryParams.mode
381
382 this.onVideoFetched(video, captionsResult.data, { startTime, stopTime, subtitle, playerMode })
383 .catch(err => this.handleError(err))
384 })
385 }
386
387 private loadPlaylist (playlistId: string) {
388 // Playlist did not change
389 if (this.playlist && this.playlist.uuid === playlistId) return
390
391 this.playlistService.getVideoPlaylist(playlistId)
392 .pipe(
393 // If 401, the video is private or blacklisted so redirect to 404
394 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
395 )
396 .subscribe(playlist => {
397 this.playlist = playlist
398
399 const videoId = this.route.snapshot.queryParams['videoId']
400 this.loadPlaylistElements(!videoId)
401 })
402 }
403
404 private loadPlaylistElements (redirectToFirst = false) {
405 this.videoService.getPlaylistVideos(this.playlist.uuid, this.playlistPagination)
406 .subscribe(({ totalVideos, videos }) => {
407 this.playlistVideos = this.playlistVideos.concat(videos)
408 this.playlistPagination.totalItems = totalVideos
409
410 if (totalVideos === 0) {
411 this.noPlaylistVideos = true
412 return
413 }
414
415 this.updatePlaylistIndex()
416
417 if (redirectToFirst) {
418 const extras = {
419 queryParams: { videoId: this.playlistVideos[ 0 ].uuid },
420 replaceUrl: true
421 }
422 this.router.navigate([], extras)
423 }
424 })
425 }
426
427 private updateVideoDescription (description: string) {
428 this.video.description = description
429 this.setVideoDescriptionHTML()
430 }
431
432 private async setVideoDescriptionHTML () {
433 this.videoHTMLDescription = await this.markdownService.textMarkdownToHTML(this.video.description)
434 }
435
436 private setVideoLikesBarTooltipText () {
437 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
438 likesNumber: this.video.likes,
439 dislikesNumber: this.video.dislikes
440 })
441 }
442
443 private handleError (err: any) {
444 const errorMessage: string = typeof err === 'string' ? err : err.message
445 if (!errorMessage) return
446
447 // Display a message in the video player instead of a notification
448 if (errorMessage.indexOf('from xs param') !== -1) {
449 this.flushPlayer()
450 this.remoteServerDown = true
451 this.changeDetector.detectChanges()
452
453 return
454 }
455
456 this.notifier.error(errorMessage)
457 }
458
459 private checkUserRating () {
460 // Unlogged users do not have ratings
461 if (this.isUserLoggedIn() === false) return
462
463 this.videoService.getUserVideoRating(this.video.id)
464 .subscribe(
465 ratingObject => {
466 if (ratingObject) {
467 this.userRating = ratingObject.rating
468 }
469 },
470
471 err => this.notifier.error(err.message)
472 )
473 }
474
475 private async onVideoFetched (
476 video: VideoDetails,
477 videoCaptions: VideoCaption[],
478 urlOptions: { startTime?: number, stopTime?: number, subtitle?: string, playerMode?: string }
479 ) {
480 this.video = video
481
482 // Re init attributes
483 this.descriptionLoading = false
484 this.completeDescriptionShown = false
485 this.remoteServerDown = false
486 this.currentTime = undefined
487
488 this.updatePlaylistIndex()
489
490 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
491 // If we are at the end of the video, reset the timer
492 if (this.video.duration - startTime <= 1) startTime = 0
493
494 if (this.isVideoBlur(this.video)) {
495 const res = await this.confirmService.confirm(
496 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
497 this.i18n('Mature or explicit content')
498 )
499 if (res === false) return this.redirectService.redirectToHomepage()
500 }
501
502 // Flush old player if needed
503 this.flushPlayer()
504
505 // Build video element, because videojs remove it on dispose
506 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
507 this.playerElement = document.createElement('video')
508 this.playerElement.className = 'video-js vjs-peertube-skin'
509 this.playerElement.setAttribute('playsinline', 'true')
510 playerElementWrapper.appendChild(this.playerElement)
511
512 const playerCaptions = videoCaptions.map(c => ({
513 label: c.language.label,
514 language: c.language.id,
515 src: environment.apiUrl + c.captionPath
516 }))
517
518 const options: PeertubePlayerManagerOptions = {
519 common: {
520 autoplay: this.isAutoplay(),
521
522 playerElement: this.playerElement,
523 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
524
525 videoDuration: this.video.duration,
526 enableHotkeys: true,
527 inactivityTimeout: 2500,
528 poster: this.video.previewUrl,
529 startTime,
530 stopTime: urlOptions.stopTime,
531
532 theaterMode: true,
533 captions: videoCaptions.length !== 0,
534 peertubeLink: false,
535
536 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
537 embedUrl: this.video.embedUrl,
538
539 language: this.localeId,
540
541 subtitle: urlOptions.subtitle,
542
543 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
544 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
545 authorizationHeader: this.authService.getRequestHeaderValue()
546 } : undefined,
547
548 serverUrl: environment.apiUrl,
549
550 videoCaptions: playerCaptions
551 },
552
553 webtorrent: {
554 videoFiles: this.video.files
555 }
556 }
557
558 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
559
560 if (mode === 'p2p-media-loader') {
561 const hlsPlaylist = this.video.getHlsPlaylist()
562
563 const p2pMediaLoader = {
564 playlistUrl: hlsPlaylist.playlistUrl,
565 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
566 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
567 trackerAnnounce: this.video.trackerUrls,
568 videoFiles: this.video.files
569 } as P2PMediaLoaderOptions
570
571 Object.assign(options, { p2pMediaLoader })
572 }
573
574 this.zone.runOutsideAngular(async () => {
575 this.player = await PeertubePlayerManager.initialize(mode, options)
576 this.theaterEnabled = this.player.theaterEnabled
577
578 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
579
580 this.player.on('timeupdate', () => {
581 this.currentTime = Math.floor(this.player.currentTime())
582 })
583
584 this.player.one('ended', () => {
585 if (this.playlist) {
586 this.zone.run(() => this.navigateToNextPlaylistVideo())
587 }
588 })
589
590 this.player.one('stopped', () => {
591 if (this.playlist) {
592 this.zone.run(() => this.navigateToNextPlaylistVideo())
593 }
594 })
595
596 this.player.on('theaterChange', (_: any, enabled: boolean) => {
597 this.zone.run(() => this.theaterEnabled = enabled)
598 })
599 })
600
601 this.setVideoDescriptionHTML()
602 this.setVideoLikesBarTooltipText()
603
604 this.setOpenGraphTags()
605 this.checkUserRating()
606 }
607
608 private setRating (nextRating: UserVideoRateType) {
609 let method
610 switch (nextRating) {
611 case 'like':
612 method = this.videoService.setVideoLike
613 break
614 case 'dislike':
615 method = this.videoService.setVideoDislike
616 break
617 case 'none':
618 method = this.videoService.unsetVideoLike
619 break
620 }
621
622 method.call(this.videoService, this.video.id)
623 .subscribe(
624 () => {
625 // Update the video like attribute
626 this.updateVideoRating(this.userRating, nextRating)
627 this.userRating = nextRating
628 },
629
630 (err: { message: string }) => this.notifier.error(err.message)
631 )
632 }
633
634 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
635 let likesToIncrement = 0
636 let dislikesToIncrement = 0
637
638 if (oldRating) {
639 if (oldRating === 'like') likesToIncrement--
640 if (oldRating === 'dislike') dislikesToIncrement--
641 }
642
643 if (newRating === 'like') likesToIncrement++
644 if (newRating === 'dislike') dislikesToIncrement++
645
646 this.video.likes += likesToIncrement
647 this.video.dislikes += dislikesToIncrement
648
649 this.video.buildLikeAndDislikePercents()
650 this.setVideoLikesBarTooltipText()
651 }
652
653 private updatePlaylistIndex () {
654 if (this.playlistVideos.length === 0 || !this.video) return
655
656 for (const video of this.playlistVideos) {
657 if (video.id === this.video.id) {
658 this.currentPlaylistPosition = video.playlistElement.position
659 return
660 }
661 }
662
663 // Load more videos to find our video
664 this.onPlaylistVideosNearOfBottom()
665 }
666
667 private setOpenGraphTags () {
668 this.metaService.setTitle(this.video.name)
669
670 this.metaService.setTag('og:type', 'video')
671
672 this.metaService.setTag('og:title', this.video.name)
673 this.metaService.setTag('name', this.video.name)
674
675 this.metaService.setTag('og:description', this.video.description)
676 this.metaService.setTag('description', this.video.description)
677
678 this.metaService.setTag('og:image', this.video.previewPath)
679
680 this.metaService.setTag('og:duration', this.video.duration.toString())
681
682 this.metaService.setTag('og:site_name', 'PeerTube')
683
684 this.metaService.setTag('og:url', window.location.href)
685 this.metaService.setTag('url', window.location.href)
686 }
687
688 private isAutoplay () {
689 // We'll jump to the thread id, so do not play the video
690 if (this.route.snapshot.params['threadId']) return false
691
692 // Otherwise true by default
693 if (!this.user) return true
694
695 // Be sure the autoPlay is set to false
696 return this.user.autoPlayVideo !== false
697 }
698
699 private flushPlayer () {
700 // Remove player if it exists
701 if (this.player) {
702 this.player.dispose()
703 this.player = undefined
704 }
705 }
706
707 private navigateToNextPlaylistVideo () {
708 if (this.currentPlaylistPosition < this.playlistPagination.totalItems) {
709 const next = this.playlistVideos.find(v => v.playlistElement.position === this.currentPlaylistPosition + 1)
710
711 const start = next.playlistElement.startTimestamp
712 const stop = next.playlistElement.stopTimestamp
713 this.router.navigate([],{ queryParams: { videoId: next.uuid, start, stop } })
714 }
715 }
716 }