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 * as WebTorrent from 'webtorrent'
13 import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoRateType, VideoState } from '../../../../../shared'
14 import '../../../assets/player/peertube-videojs-plugin'
15 import { AuthService, ConfirmService } from '../../core'
16 import { RestExtractor, VideoBlacklistService } from '../../shared'
17 import { VideoDetails } from '../../shared/video/video-details.model'
18 import { VideoService } from '../../shared/video/video.service'
19 import { MarkdownService } from '../shared'
20 import { VideoDownloadComponent } from './modal/video-download.component'
21 import { VideoReportComponent } from './modal/video-report.component'
22 import { VideoShareComponent } from './modal/video-share.component'
23 import { VideoBlacklistComponent } from './modal/video-blacklist.component'
24 import { addContextMenu, getVideojsOptions, loadLocaleInVideoJS } from '../../../assets/player/peertube-player'
25 import { ServerService } from '@app/core'
26 import { I18n } from '@ngx-translate/i18n-polyfill'
27 import { environment } from '../../../environments/environment'
28 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
29 import { VideoCaptionService } from '@app/shared/video-caption'
32 selector: 'my-video-watch',
33 templateUrl: './video-watch.component.html',
34 styleUrls: [ './video-watch.component.scss' ]
36 export class VideoWatchComponent implements OnInit, OnDestroy {
37 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
39 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
40 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
41 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
42 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
43 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
45 player: videojs.Player
46 playerElement: HTMLVideoElement
47 userRating: UserVideoRateType = null
48 video: VideoDetails = null
49 descriptionLoading = false
51 completeDescriptionShown = false
52 completeVideoDescription: string
53 shortVideoDescription: string
54 videoHTMLDescription = ''
55 likesBarTooltipText = ''
56 hasAlreadyAcceptedPrivacyConcern = false
57 remoteServerDown = false
59 private videojsLocaleLoaded = false
60 private paramsSub: Subscription
63 private elementRef: ElementRef,
64 private changeDetector: ChangeDetectorRef,
65 private route: ActivatedRoute,
66 private router: Router,
67 private videoService: VideoService,
68 private videoBlacklistService: VideoBlacklistService,
69 private confirmService: ConfirmService,
70 private metaService: MetaService,
71 private authService: AuthService,
72 private serverService: ServerService,
73 private restExtractor: RestExtractor,
74 private notificationsService: NotificationsService,
75 private markdownService: MarkdownService,
77 private redirectService: RedirectService,
78 private videoCaptionService: VideoCaptionService,
80 @Inject(LOCALE_ID) private localeId: string
84 return this.authService.getUser()
89 WebTorrent.WEBRTC_SUPPORT === false ||
90 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
92 this.hasAlreadyAcceptedPrivacyConcern = true
95 this.paramsSub = this.route.params.subscribe(routeParams => {
96 const uuid = routeParams[ 'uuid' ]
98 // Video did not change
99 if (this.video && this.video.uuid === uuid) return
101 if (this.player) this.player.pause()
105 this.videoService.getVideo(uuid),
106 this.videoCaptionService.listCaptions(uuid)
109 // If 401, the video is private or blacklisted so redirect to 404
110 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 404 ]))
112 .subscribe(([ video, captionsResult ]) => {
113 const startTime = this.route.snapshot.queryParams.start
114 this.onVideoFetched(video, captionsResult.data, startTime)
115 .catch(err => this.handleError(err))
123 // Unsubscribe subscriptions
124 this.paramsSub.unsubscribe()
128 if (this.isUserLoggedIn() === false) return
129 if (this.userRating === 'like') {
130 // Already liked this video
131 this.setRating('none')
133 this.setRating('like')
138 if (this.isUserLoggedIn() === false) return
139 if (this.userRating === 'dislike') {
140 // Already disliked this video
141 this.setRating('none')
143 this.setRating('dislike')
147 showMoreDescription () {
148 if (this.completeVideoDescription === undefined) {
149 return this.loadCompleteDescription()
152 this.updateVideoDescription(this.completeVideoDescription)
153 this.completeDescriptionShown = true
156 showLessDescription () {
157 this.updateVideoDescription(this.shortVideoDescription)
158 this.completeDescriptionShown = false
161 loadCompleteDescription () {
162 this.descriptionLoading = true
164 this.videoService.loadCompleteDescription(this.video.descriptionPath)
167 this.completeDescriptionShown = true
168 this.descriptionLoading = false
170 this.shortVideoDescription = this.video.description
171 this.completeVideoDescription = description
173 this.updateVideoDescription(this.completeVideoDescription)
177 this.descriptionLoading = false
178 this.notificationsService.error(this.i18n('Error'), error.message)
183 showReportModal (event: Event) {
184 event.preventDefault()
185 this.videoReportModal.show()
188 showSupportModal () {
189 this.videoSupportModal.show()
193 const currentTime = this.player ? this.player.currentTime() : undefined
195 this.videoShareModal.show(currentTime)
198 showDownloadModal (event: Event) {
199 event.preventDefault()
200 this.videoDownloadModal.show()
203 showBlacklistModal (event: Event) {
204 event.preventDefault()
205 this.videoBlacklistModal.show()
208 async unblacklistVideo (event: Event) {
209 event.preventDefault()
211 const confirmMessage = this.i18n(
212 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
215 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
216 if (res === false) return
218 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
220 this.notificationsService.success(
221 this.i18n('Success'),
222 this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name })
225 this.video.blacklisted = false
226 this.video.blacklistedReason = null
229 err => this.notificationsService.error(this.i18n('Error'), err.message)
234 return this.authService.isLoggedIn()
237 isVideoUpdatable () {
238 return this.video.isUpdatableBy(this.authService.getUser())
241 isVideoBlacklistable () {
242 return this.video.isBlackistableBy(this.user)
245 isVideoUnblacklistable () {
246 return this.video.isUnblacklistableBy(this.user)
250 if (!this.video || Array.isArray(this.video.tags) === false) return []
252 return this.video.tags
255 isVideoRemovable () {
256 return this.video.isRemovableBy(this.authService.getUser())
259 async removeVideo (event: Event) {
260 event.preventDefault()
262 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
263 if (res === false) return
265 this.videoService.removeVideo(this.video.id)
268 this.notificationsService.success(
269 this.i18n('Success'),
270 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
273 // Go back to the video-list.
274 this.redirectService.redirectToHomepage()
277 error => this.notificationsService.error(this.i18n('Error'), error.message)
281 acceptedPrivacyConcern () {
282 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
283 this.hasAlreadyAcceptedPrivacyConcern = true
286 isVideoToTranscode () {
287 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
291 return this.video && this.video.state.id === VideoState.TO_IMPORT
294 hasVideoScheduledPublication () {
295 return this.video && this.video.scheduledUpdate !== undefined
298 private updateVideoDescription (description: string) {
299 this.video.description = description
300 this.setVideoDescriptionHTML()
303 private setVideoDescriptionHTML () {
304 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
307 private setVideoLikesBarTooltipText () {
308 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
309 likesNumber: this.video.likes,
310 dislikesNumber: this.video.dislikes
314 private handleError (err: any) {
315 const errorMessage: string = typeof err === 'string' ? err : err.message
316 if (!errorMessage) return
318 // Display a message in the video player instead of a notification
319 if (errorMessage.indexOf('from xs param') !== -1) {
321 this.remoteServerDown = true
322 this.changeDetector.detectChanges()
327 this.notificationsService.error(this.i18n('Error'), errorMessage)
330 private checkUserRating () {
331 // Unlogged users do not have ratings
332 if (this.isUserLoggedIn() === false) return
334 this.videoService.getUserVideoRating(this.video.id)
338 this.userRating = ratingObject.rating
342 err => this.notificationsService.error(this.i18n('Error'), err.message)
346 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
349 // Re init attributes
350 this.descriptionLoading = false
351 this.completeDescriptionShown = false
352 this.remoteServerDown = false
354 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
355 const res = await this.confirmService.confirm(
356 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
357 this.i18n('Mature or explicit content')
359 if (res === false) return this.redirectService.redirectToHomepage()
362 // Flush old player if needed
365 // Build video element, because videojs remove it on dispose
366 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
367 this.playerElement = document.createElement('video')
368 this.playerElement.className = 'video-js vjs-peertube-skin'
369 this.playerElement.setAttribute('playsinline', 'true')
370 playerElementWrapper.appendChild(this.playerElement)
372 const playerCaptions = videoCaptions.map(c => ({
373 label: c.language.label,
374 language: c.language.id,
375 src: environment.apiUrl + c.captionPath
378 const videojsOptions = getVideojsOptions({
379 autoplay: this.isAutoplay(),
380 inactivityTimeout: 2500,
381 videoFiles: this.video.files,
382 videoCaptions: playerCaptions,
383 playerElement: this.playerElement,
384 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
385 videoDuration: this.video.duration,
388 poster: this.video.previewUrl,
391 language: this.localeId
394 if (this.videojsLocaleLoaded === false) {
395 await loadLocaleInVideoJS(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
396 this.videojsLocaleLoaded = true
400 this.zone.runOutsideAngular(async () => {
401 videojs(this.playerElement, videojsOptions, function () {
403 this.on('customError', (event, data) => self.handleError(data.err))
405 addContextMenu(self.player, self.video.embedUrl)
409 this.setVideoDescriptionHTML()
410 this.setVideoLikesBarTooltipText()
412 this.setOpenGraphTags()
413 this.checkUserRating()
416 private setRating (nextRating) {
418 switch (nextRating) {
420 method = this.videoService.setVideoLike
423 method = this.videoService.setVideoDislike
426 method = this.videoService.unsetVideoLike
430 method.call(this.videoService, this.video.id)
433 // Update the video like attribute
434 this.updateVideoRating(this.userRating, nextRating)
435 this.userRating = nextRating
438 err => this.notificationsService.error(this.i18n('Error'), err.message)
442 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
443 let likesToIncrement = 0
444 let dislikesToIncrement = 0
447 if (oldRating === 'like') likesToIncrement--
448 if (oldRating === 'dislike') dislikesToIncrement--
451 if (newRating === 'like') likesToIncrement++
452 if (newRating === 'dislike') dislikesToIncrement++
454 this.video.likes += likesToIncrement
455 this.video.dislikes += dislikesToIncrement
457 this.video.buildLikeAndDislikePercents()
458 this.setVideoLikesBarTooltipText()
461 private setOpenGraphTags () {
462 this.metaService.setTitle(this.video.name)
464 this.metaService.setTag('og:type', 'video')
466 this.metaService.setTag('og:title', this.video.name)
467 this.metaService.setTag('name', this.video.name)
469 this.metaService.setTag('og:description', this.video.description)
470 this.metaService.setTag('description', this.video.description)
472 this.metaService.setTag('og:image', this.video.previewPath)
474 this.metaService.setTag('og:duration', this.video.duration.toString())
476 this.metaService.setTag('og:site_name', 'PeerTube')
478 this.metaService.setTag('og:url', window.location.href)
479 this.metaService.setTag('url', window.location.href)
482 private isAutoplay () {
483 // We'll jump to the thread id, so do not play the video
484 if (this.route.snapshot.params['threadId']) return false
486 // Otherwise true by default
487 if (!this.user) return true
489 // Be sure the autoPlay is set to false
490 return this.user.autoPlayVideo !== false
493 private flushPlayer () {
494 // Remove player if it exists
496 this.player.dispose()
497 this.player = undefined