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 { NotificationsService } from 'angular2-notifications'
9 import { forkJoin, Subscription } from 'rxjs'
10 import * as videojs from 'video.js'
11 import 'videojs-hotkeys'
12 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
13 import * as WebTorrent from 'webtorrent'
14 import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoRateType, VideoState } from '../../../../../shared'
15 import '../../../assets/player/peertube-videojs-plugin'
16 import { AuthService, ConfirmService } from '../../core'
17 import { RestExtractor, VideoBlacklistService } from '../../shared'
18 import { VideoDetails } from '../../shared/video/video-details.model'
19 import { VideoService } from '../../shared/video/video.service'
20 import { MarkdownService } from '../shared'
21 import { VideoDownloadComponent } from './modal/video-download.component'
22 import { VideoReportComponent } from './modal/video-report.component'
23 import { VideoShareComponent } from './modal/video-share.component'
24 import { VideoBlacklistComponent } from './modal/video-blacklist.component'
25 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
26 import { addContextMenu, getVideojsOptions, loadLocaleInVideoJS } from '../../../assets/player/peertube-player'
27 import { ServerService } from '@app/core'
28 import { I18n } from '@ngx-translate/i18n-polyfill'
29 import { environment } from '../../../environments/environment'
30 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
31 import { VideoCaptionService } from '@app/shared/video-caption'
34 selector: 'my-video-watch',
35 templateUrl: './video-watch.component.html',
36 styleUrls: [ './video-watch.component.scss' ]
38 export class VideoWatchComponent implements OnInit, OnDestroy {
39 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
41 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
42 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
43 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
44 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
45 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
46 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
48 player: videojs.Player
49 playerElement: HTMLVideoElement
50 userRating: UserVideoRateType = null
51 video: VideoDetails = null
52 descriptionLoading = false
54 completeDescriptionShown = false
55 completeVideoDescription: string
56 shortVideoDescription: string
57 videoHTMLDescription = ''
58 likesBarTooltipText = ''
59 hasAlreadyAcceptedPrivacyConcern = false
60 remoteServerDown = false
63 private videojsLocaleLoaded = 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 notificationsService: NotificationsService,
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, 404 ]))
117 .subscribe(([ video, captionsResult ]) => {
118 const startTime = this.route.snapshot.queryParams.start
119 this.onVideoFetched(video, captionsResult.data, startTime)
120 .catch(err => this.handleError(err))
125 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
128 }, undefined, 'Like the video'),
129 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
132 }, undefined, 'Dislike the video'),
133 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
134 this.subscribeButton.subscribed ?
135 this.subscribeButton.unsubscribe() :
136 this.subscribeButton.subscribe()
138 }, undefined, 'Subscribe to the account')
140 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
146 // Unsubscribe subscriptions
147 this.paramsSub.unsubscribe()
150 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
154 if (this.isUserLoggedIn() === false) return
155 if (this.userRating === 'like') {
156 // Already liked this video
157 this.setRating('none')
159 this.setRating('like')
164 if (this.isUserLoggedIn() === false) return
165 if (this.userRating === 'dislike') {
166 // Already disliked this video
167 this.setRating('none')
169 this.setRating('dislike')
173 showMoreDescription () {
174 if (this.completeVideoDescription === undefined) {
175 return this.loadCompleteDescription()
178 this.updateVideoDescription(this.completeVideoDescription)
179 this.completeDescriptionShown = true
182 showLessDescription () {
183 this.updateVideoDescription(this.shortVideoDescription)
184 this.completeDescriptionShown = false
187 loadCompleteDescription () {
188 this.descriptionLoading = true
190 this.videoService.loadCompleteDescription(this.video.descriptionPath)
193 this.completeDescriptionShown = true
194 this.descriptionLoading = false
196 this.shortVideoDescription = this.video.description
197 this.completeVideoDescription = description
199 this.updateVideoDescription(this.completeVideoDescription)
203 this.descriptionLoading = false
204 this.notificationsService.error(this.i18n('Error'), error.message)
209 showReportModal (event: Event) {
210 event.preventDefault()
211 this.videoReportModal.show()
214 showSupportModal () {
215 this.videoSupportModal.show()
219 const currentTime = this.player ? this.player.currentTime() : undefined
221 this.videoShareModal.show(currentTime)
224 showDownloadModal (event: Event) {
225 event.preventDefault()
226 this.videoDownloadModal.show()
229 showBlacklistModal (event: Event) {
230 event.preventDefault()
231 this.videoBlacklistModal.show()
234 async unblacklistVideo (event: Event) {
235 event.preventDefault()
237 const confirmMessage = this.i18n(
238 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
241 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
242 if (res === false) return
244 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
246 this.notificationsService.success(
247 this.i18n('Success'),
248 this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name })
251 this.video.blacklisted = false
252 this.video.blacklistedReason = null
255 err => this.notificationsService.error(this.i18n('Error'), err.message)
260 return this.authService.isLoggedIn()
263 isVideoUpdatable () {
264 return this.video.isUpdatableBy(this.authService.getUser())
267 isVideoBlacklistable () {
268 return this.video.isBlackistableBy(this.user)
271 isVideoUnblacklistable () {
272 return this.video.isUnblacklistableBy(this.user)
276 if (!this.video || Array.isArray(this.video.tags) === false) return []
278 return this.video.tags
281 isVideoRemovable () {
282 return this.video.isRemovableBy(this.authService.getUser())
285 async removeVideo (event: Event) {
286 event.preventDefault()
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
291 this.videoService.removeVideo(this.video.id)
294 this.notificationsService.success(
295 this.i18n('Success'),
296 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
299 // Go back to the video-list.
300 this.redirectService.redirectToHomepage()
303 error => this.notificationsService.error(this.i18n('Error'), error.message)
307 acceptedPrivacyConcern () {
308 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
309 this.hasAlreadyAcceptedPrivacyConcern = true
312 isVideoToTranscode () {
313 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
317 return this.video && this.video.state.id === VideoState.TO_IMPORT
320 hasVideoScheduledPublication () {
321 return this.video && this.video.scheduledUpdate !== undefined
324 private updateVideoDescription (description: string) {
325 this.video.description = description
326 this.setVideoDescriptionHTML()
329 private setVideoDescriptionHTML () {
330 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
333 private setVideoLikesBarTooltipText () {
334 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
335 likesNumber: this.video.likes,
336 dislikesNumber: this.video.dislikes
340 private handleError (err: any) {
341 const errorMessage: string = typeof err === 'string' ? err : err.message
342 if (!errorMessage) return
344 // Display a message in the video player instead of a notification
345 if (errorMessage.indexOf('from xs param') !== -1) {
347 this.remoteServerDown = true
348 this.changeDetector.detectChanges()
353 this.notificationsService.error(this.i18n('Error'), errorMessage)
356 private checkUserRating () {
357 // Unlogged users do not have ratings
358 if (this.isUserLoggedIn() === false) return
360 this.videoService.getUserVideoRating(this.video.id)
364 this.userRating = ratingObject.rating
368 err => this.notificationsService.error(this.i18n('Error'), err.message)
372 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
375 // Re init attributes
376 this.descriptionLoading = false
377 this.completeDescriptionShown = false
378 this.remoteServerDown = false
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 videojsOptions = getVideojsOptions({
405 autoplay: this.isAutoplay(),
406 inactivityTimeout: 2500,
407 videoFiles: this.video.files,
408 videoCaptions: playerCaptions,
409 playerElement: this.playerElement,
410 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
411 videoDuration: this.video.duration,
414 poster: this.video.previewUrl,
417 language: this.localeId
420 if (this.videojsLocaleLoaded === false) {
421 await loadLocaleInVideoJS(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
422 this.videojsLocaleLoaded = true
426 this.zone.runOutsideAngular(async () => {
427 videojs(this.playerElement, videojsOptions, function () {
429 this.on('customError', (event, data) => self.handleError(data.err))
431 addContextMenu(self.player, self.video.embedUrl)
435 this.setVideoDescriptionHTML()
436 this.setVideoLikesBarTooltipText()
438 this.setOpenGraphTags()
439 this.checkUserRating()
442 private setRating (nextRating) {
444 switch (nextRating) {
446 method = this.videoService.setVideoLike
449 method = this.videoService.setVideoDislike
452 method = this.videoService.unsetVideoLike
456 method.call(this.videoService, this.video.id)
459 // Update the video like attribute
460 this.updateVideoRating(this.userRating, nextRating)
461 this.userRating = nextRating
464 err => this.notificationsService.error(this.i18n('Error'), err.message)
468 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
469 let likesToIncrement = 0
470 let dislikesToIncrement = 0
473 if (oldRating === 'like') likesToIncrement--
474 if (oldRating === 'dislike') dislikesToIncrement--
477 if (newRating === 'like') likesToIncrement++
478 if (newRating === 'dislike') dislikesToIncrement++
480 this.video.likes += likesToIncrement
481 this.video.dislikes += dislikesToIncrement
483 this.video.buildLikeAndDislikePercents()
484 this.setVideoLikesBarTooltipText()
487 private setOpenGraphTags () {
488 this.metaService.setTitle(this.video.name)
490 this.metaService.setTag('og:type', 'video')
492 this.metaService.setTag('og:title', this.video.name)
493 this.metaService.setTag('name', this.video.name)
495 this.metaService.setTag('og:description', this.video.description)
496 this.metaService.setTag('description', this.video.description)
498 this.metaService.setTag('og:image', this.video.previewPath)
500 this.metaService.setTag('og:duration', this.video.duration.toString())
502 this.metaService.setTag('og:site_name', 'PeerTube')
504 this.metaService.setTag('og:url', window.location.href)
505 this.metaService.setTag('url', window.location.href)
508 private isAutoplay () {
509 // We'll jump to the thread id, so do not play the video
510 if (this.route.snapshot.params['threadId']) return false
512 // Otherwise true by default
513 if (!this.user) return true
515 // Be sure the autoPlay is set to false
516 return this.user.autoPlayVideo !== false
519 private flushPlayer () {
520 // Remove player if it exists
522 this.player.dispose()
523 this.player = undefined