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