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 * as WebTorrent from 'webtorrent'
12 import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
13 import { AuthService, ConfirmService } from '../../core'
14 import { RestExtractor, VideoBlacklistService } from '../../shared'
15 import { VideoDetails } from '../../shared/video/video-details.model'
16 import { VideoService } from '../../shared/video/video.service'
17 import { VideoDownloadComponent } from './modal/video-download.component'
18 import { VideoReportComponent } from './modal/video-report.component'
19 import { VideoShareComponent } from './modal/video-share.component'
20 import { VideoBlacklistComponent } from './modal/video-blacklist.component'
21 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
22 import { I18n } from '@ngx-translate/i18n-polyfill'
23 import { environment } from '../../../environments/environment'
24 import { VideoCaptionService } from '@app/shared/video-caption'
25 import { MarkdownService } from '@app/shared/renderer'
27 P2PMediaLoaderOptions,
28 PeertubePlayerManager,
29 PeertubePlayerManagerOptions,
32 } from '../../../assets/player/peertube-player-manager'
35 selector: 'my-video-watch',
36 templateUrl: './video-watch.component.html',
37 styleUrls: [ './video-watch.component.scss' ]
39 export class VideoWatchComponent implements OnInit, OnDestroy {
40 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
42 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
43 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
44 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
45 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
46 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
47 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
50 playerElement: HTMLVideoElement
51 userRating: UserVideoRateType = null
52 video: VideoDetails = null
53 descriptionLoading = false
55 completeDescriptionShown = false
56 completeVideoDescription: string
57 shortVideoDescription: string
58 videoHTMLDescription = ''
59 likesBarTooltipText = ''
60 hasAlreadyAcceptedPrivacyConcern = false
61 remoteServerDown = false
64 private paramsSub: Subscription
67 private elementRef: ElementRef,
68 private changeDetector: ChangeDetectorRef,
69 private route: ActivatedRoute,
70 private router: Router,
71 private videoService: VideoService,
72 private videoBlacklistService: VideoBlacklistService,
73 private confirmService: ConfirmService,
74 private metaService: MetaService,
75 private authService: AuthService,
76 private serverService: ServerService,
77 private restExtractor: RestExtractor,
78 private notifier: Notifier,
79 private markdownService: MarkdownService,
81 private redirectService: RedirectService,
82 private videoCaptionService: VideoCaptionService,
84 private hotkeysService: HotkeysService,
85 @Inject(LOCALE_ID) private localeId: string
89 return this.authService.getUser()
94 WebTorrent.WEBRTC_SUPPORT === false ||
95 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
97 this.hasAlreadyAcceptedPrivacyConcern = true
100 this.paramsSub = this.route.params.subscribe(routeParams => {
101 const uuid = routeParams[ 'uuid' ]
103 // Video did not change
104 if (this.video && this.video.uuid === uuid) return
106 if (this.player) this.player.pause()
110 this.videoService.getVideo(uuid),
111 this.videoCaptionService.listCaptions(uuid)
114 // If 401, the video is private or blacklisted so redirect to 404
115 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
117 .subscribe(([ video, captionsResult ]) => {
118 const startTime = this.route.snapshot.queryParams.start
119 const subtitle = this.route.snapshot.queryParams.subtitle
121 this.onVideoFetched(video, captionsResult.data, { startTime, subtitle })
122 .catch(err => this.handleError(err))
127 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
130 }, undefined, this.i18n('Like the video')),
131 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
134 }, undefined, this.i18n('Dislike the video')),
135 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
136 this.subscribeButton.subscribed ?
137 this.subscribeButton.unsubscribe() :
138 this.subscribeButton.subscribe()
140 }, undefined, this.i18n('Subscribe to the account'))
142 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
148 // Unsubscribe subscriptions
149 this.paramsSub.unsubscribe()
152 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
156 if (this.isUserLoggedIn() === false) return
157 if (this.userRating === 'like') {
158 // Already liked this video
159 this.setRating('none')
161 this.setRating('like')
166 if (this.isUserLoggedIn() === false) return
167 if (this.userRating === 'dislike') {
168 // Already disliked this video
169 this.setRating('none')
171 this.setRating('dislike')
175 showMoreDescription () {
176 if (this.completeVideoDescription === undefined) {
177 return this.loadCompleteDescription()
180 this.updateVideoDescription(this.completeVideoDescription)
181 this.completeDescriptionShown = true
184 showLessDescription () {
185 this.updateVideoDescription(this.shortVideoDescription)
186 this.completeDescriptionShown = false
189 loadCompleteDescription () {
190 this.descriptionLoading = true
192 this.videoService.loadCompleteDescription(this.video.descriptionPath)
195 this.completeDescriptionShown = true
196 this.descriptionLoading = false
198 this.shortVideoDescription = this.video.description
199 this.completeVideoDescription = description
201 this.updateVideoDescription(this.completeVideoDescription)
205 this.descriptionLoading = false
206 this.notifier.error(error.message)
211 showReportModal (event: Event) {
212 event.preventDefault()
213 this.videoReportModal.show()
216 showSupportModal () {
217 this.videoSupportModal.show()
221 const currentTime = this.player ? this.player.currentTime() : undefined
223 this.videoShareModal.show(currentTime)
226 showDownloadModal (event: Event) {
227 event.preventDefault()
228 this.videoDownloadModal.show()
231 showBlacklistModal (event: Event) {
232 event.preventDefault()
233 this.videoBlacklistModal.show()
236 async unblacklistVideo (event: Event) {
237 event.preventDefault()
239 const confirmMessage = this.i18n(
240 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
243 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
244 if (res === false) return
246 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
248 this.notifier.success(this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name }))
250 this.video.blacklisted = false
251 this.video.blacklistedReason = null
254 err => this.notifier.error(err.message)
259 return this.authService.isLoggedIn()
262 isVideoUpdatable () {
263 return this.video.isUpdatableBy(this.authService.getUser())
266 isVideoBlacklistable () {
267 return this.video.isBlackistableBy(this.user)
270 isVideoUnblacklistable () {
271 return this.video.isUnblacklistableBy(this.user)
275 if (!this.video || Array.isArray(this.video.tags) === false) return []
277 return this.video.tags
280 isVideoRemovable () {
281 return this.video.isRemovableBy(this.authService.getUser())
284 async removeVideo (event: Event) {
285 event.preventDefault()
287 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
288 if (res === false) return
290 this.videoService.removeVideo(this.video.id)
293 this.notifier.success(this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name }))
295 // Go back to the video-list.
296 this.redirectService.redirectToHomepage()
299 error => this.notifier.error(error.message)
303 acceptedPrivacyConcern () {
304 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
305 this.hasAlreadyAcceptedPrivacyConcern = true
308 isVideoToTranscode () {
309 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
313 return this.video && this.video.state.id === VideoState.TO_IMPORT
316 hasVideoScheduledPublication () {
317 return this.video && this.video.scheduledUpdate !== undefined
320 private updateVideoDescription (description: string) {
321 this.video.description = description
322 this.setVideoDescriptionHTML()
325 private setVideoDescriptionHTML () {
326 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
329 private setVideoLikesBarTooltipText () {
330 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
331 likesNumber: this.video.likes,
332 dislikesNumber: this.video.dislikes
336 private handleError (err: any) {
337 const errorMessage: string = typeof err === 'string' ? err : err.message
338 if (!errorMessage) return
340 // Display a message in the video player instead of a notification
341 if (errorMessage.indexOf('from xs param') !== -1) {
343 this.remoteServerDown = true
344 this.changeDetector.detectChanges()
349 this.notifier.error(errorMessage)
352 private checkUserRating () {
353 // Unlogged users do not have ratings
354 if (this.isUserLoggedIn() === false) return
356 this.videoService.getUserVideoRating(this.video.id)
360 this.userRating = ratingObject.rating
364 err => this.notifier.error(err.message)
368 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], urlOptions: { startTime: number, subtitle: string }) {
371 // Re init attributes
372 this.descriptionLoading = false
373 this.completeDescriptionShown = false
374 this.remoteServerDown = false
376 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
377 // If we are at the end of the video, reset the timer
378 if (this.video.duration - startTime <= 1) startTime = 0
380 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
381 const res = await this.confirmService.confirm(
382 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
383 this.i18n('Mature or explicit content')
385 if (res === false) return this.redirectService.redirectToHomepage()
388 // Flush old player if needed
391 // Build video element, because videojs remove it on dispose
392 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
393 this.playerElement = document.createElement('video')
394 this.playerElement.className = 'video-js vjs-peertube-skin'
395 this.playerElement.setAttribute('playsinline', 'true')
396 playerElementWrapper.appendChild(this.playerElement)
398 const playerCaptions = videoCaptions.map(c => ({
399 label: c.language.label,
400 language: c.language.id,
401 src: environment.apiUrl + c.captionPath
404 const options: PeertubePlayerManagerOptions = {
406 autoplay: this.isAutoplay(),
408 playerElement: this.playerElement,
409 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
411 videoDuration: this.video.duration,
413 inactivityTimeout: 2500,
414 poster: this.video.previewUrl,
418 captions: videoCaptions.length !== 0,
421 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
422 embedUrl: this.video.embedUrl,
424 language: this.localeId,
426 subtitle: urlOptions.subtitle,
428 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
429 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
430 authorizationHeader: this.authService.getRequestHeaderValue()
433 serverUrl: environment.apiUrl,
435 videoCaptions: playerCaptions
439 videoFiles: this.video.files
444 const hlsPlaylist = this.video.getHlsPlaylist()
446 mode = 'p2p-media-loader'
448 const p2pMediaLoader = {
449 playlistUrl: hlsPlaylist.playlistUrl,
450 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
451 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
452 trackerAnnounce: this.video.trackerUrls,
453 videoFiles: this.video.files
454 } as P2PMediaLoaderOptions
456 Object.assign(options, { p2pMediaLoader })
461 this.zone.runOutsideAngular(async () => {
462 this.player = await PeertubePlayerManager.initialize(mode, options)
463 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
466 this.setVideoDescriptionHTML()
467 this.setVideoLikesBarTooltipText()
469 this.setOpenGraphTags()
470 this.checkUserRating()
473 private setRating (nextRating: UserVideoRateType) {
475 switch (nextRating) {
477 method = this.videoService.setVideoLike
480 method = this.videoService.setVideoDislike
483 method = this.videoService.unsetVideoLike
487 method.call(this.videoService, this.video.id)
490 // Update the video like attribute
491 this.updateVideoRating(this.userRating, nextRating)
492 this.userRating = nextRating
495 (err: { message: string }) => this.notifier.error(err.message)
499 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
500 let likesToIncrement = 0
501 let dislikesToIncrement = 0
504 if (oldRating === 'like') likesToIncrement--
505 if (oldRating === 'dislike') dislikesToIncrement--
508 if (newRating === 'like') likesToIncrement++
509 if (newRating === 'dislike') dislikesToIncrement++
511 this.video.likes += likesToIncrement
512 this.video.dislikes += dislikesToIncrement
514 this.video.buildLikeAndDislikePercents()
515 this.setVideoLikesBarTooltipText()
518 private setOpenGraphTags () {
519 this.metaService.setTitle(this.video.name)
521 this.metaService.setTag('og:type', 'video')
523 this.metaService.setTag('og:title', this.video.name)
524 this.metaService.setTag('name', this.video.name)
526 this.metaService.setTag('og:description', this.video.description)
527 this.metaService.setTag('description', this.video.description)
529 this.metaService.setTag('og:image', this.video.previewPath)
531 this.metaService.setTag('og:duration', this.video.duration.toString())
533 this.metaService.setTag('og:site_name', 'PeerTube')
535 this.metaService.setTag('og:url', window.location.href)
536 this.metaService.setTag('url', window.location.href)
539 private isAutoplay () {
540 // We'll jump to the thread id, so do not play the video
541 if (this.route.snapshot.params['threadId']) return false
543 // Otherwise true by default
544 if (!this.user) return true
546 // Be sure the autoPlay is set to false
547 return this.user.autoPlayVideo !== false
550 private flushPlayer () {
551 // Remove player if it exists
553 this.player.dispose()
554 this.player = undefined