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, 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 { Video } from '../../shared/video/video.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 { addContextMenu, getVideojsOptions, loadLocale } from '../../../assets/player/peertube-player'
26 import { ServerService } from '@app/core'
27 import { I18n } from '@ngx-translate/i18n-polyfill'
28 import { environment } from '../../../environments/environment'
29 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
30 import { VideoCaptionService } from '@app/shared/video-caption'
31 import { VideoCaption } from '../../../../../shared/models/videos/video-caption.model'
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
47 otherVideosDisplayed: Video[] = []
49 player: videojs.Player
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
63 private videojsLocaleLoaded = false
64 private otherVideos: Video[] = []
65 private paramsSub: Subscription
68 private elementRef: ElementRef,
69 private changeDetector: ChangeDetectorRef,
70 private route: ActivatedRoute,
71 private router: Router,
72 private videoService: VideoService,
73 private videoBlacklistService: VideoBlacklistService,
74 private confirmService: ConfirmService,
75 private metaService: MetaService,
76 private authService: AuthService,
77 private serverService: ServerService,
78 private restExtractor: RestExtractor,
79 private notificationsService: NotificationsService,
80 private markdownService: MarkdownService,
82 private redirectService: RedirectService,
83 private videoCaptionService: VideoCaptionService,
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.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
103 this.otherVideos = data.videos
104 this.updateOtherVideosDisplayed()
107 err => console.error(err)
110 this.paramsSub = this.route.params.subscribe(routeParams => {
111 const uuid = routeParams[ 'uuid' ]
113 // Video did not change
114 if (this.video && this.video.uuid === uuid) return
116 if (this.player) this.player.pause()
120 this.videoService.getVideo(uuid),
121 this.videoCaptionService.listCaptions(uuid)
124 // If 401, the video is private or blacklisted so redirect to 404
125 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 404 ]))
127 .subscribe(([ video, captionsResult ]) => {
128 const startTime = this.route.snapshot.queryParams.start
129 this.onVideoFetched(video, captionsResult.data, startTime)
130 .catch(err => this.handleError(err))
138 // Unsubscribe subscriptions
139 this.paramsSub.unsubscribe()
143 if (this.isUserLoggedIn() === false) return
144 if (this.userRating === 'like') {
145 // Already liked this video
146 this.setRating('none')
148 this.setRating('like')
153 if (this.isUserLoggedIn() === false) return
154 if (this.userRating === 'dislike') {
155 // Already disliked this video
156 this.setRating('none')
158 this.setRating('dislike')
162 showMoreDescription () {
163 if (this.completeVideoDescription === undefined) {
164 return this.loadCompleteDescription()
167 this.updateVideoDescription(this.completeVideoDescription)
168 this.completeDescriptionShown = true
171 showLessDescription () {
172 this.updateVideoDescription(this.shortVideoDescription)
173 this.completeDescriptionShown = false
176 loadCompleteDescription () {
177 this.descriptionLoading = true
179 this.videoService.loadCompleteDescription(this.video.descriptionPath)
182 this.completeDescriptionShown = true
183 this.descriptionLoading = false
185 this.shortVideoDescription = this.video.description
186 this.completeVideoDescription = description
188 this.updateVideoDescription(this.completeVideoDescription)
192 this.descriptionLoading = false
193 this.notificationsService.error(this.i18n('Error'), error.message)
198 showReportModal (event: Event) {
199 event.preventDefault()
200 this.videoReportModal.show()
203 showSupportModal () {
204 this.videoSupportModal.show()
208 this.videoShareModal.show()
211 showDownloadModal (event: Event) {
212 event.preventDefault()
213 this.videoDownloadModal.show()
216 showBlacklistModal (event: Event) {
217 event.preventDefault()
218 this.videoBlacklistModal.show()
221 async unblacklistVideo (event: Event) {
222 event.preventDefault()
224 const confirmMessage = this.i18n(
225 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
228 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
229 if (res === false) return
231 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
233 this.notificationsService.success(
234 this.i18n('Success'),
235 this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name })
238 this.video.blacklisted = false
239 this.video.blacklistedReason = null
242 err => this.notificationsService.error(this.i18n('Error'), err.message)
247 return this.authService.isLoggedIn()
250 isVideoUpdatable () {
251 return this.video.isUpdatableBy(this.authService.getUser())
254 isVideoBlacklistable () {
255 return this.video.isBlackistableBy(this.user)
258 isVideoUnblacklistable () {
259 return this.video.isUnblacklistableBy(this.user)
263 if (!this.video) return ''
265 return this.video.previewUrl
269 if (!this.video || Array.isArray(this.video.tags) === false) return []
271 return this.video.tags
274 isVideoRemovable () {
275 return this.video.isRemovableBy(this.authService.getUser())
278 async removeVideo (event: Event) {
279 event.preventDefault()
281 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
282 if (res === false) return
284 this.videoService.removeVideo(this.video.id)
287 this.notificationsService.success(
288 this.i18n('Success'),
289 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
292 // Go back to the video-list.
293 this.redirectService.redirectToHomepage()
296 error => this.notificationsService.error(this.i18n('Error'), error.message)
300 acceptedPrivacyConcern () {
301 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
302 this.hasAlreadyAcceptedPrivacyConcern = true
305 isVideoToTranscode () {
306 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
310 return this.video && this.video.state.id === VideoState.TO_IMPORT
313 hasVideoScheduledPublication () {
314 return this.video && this.video.scheduledUpdate !== undefined
317 private updateVideoDescription (description: string) {
318 this.video.description = description
319 this.setVideoDescriptionHTML()
322 private setVideoDescriptionHTML () {
323 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
326 private setVideoLikesBarTooltipText () {
327 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
328 likesNumber: this.video.likes,
329 dislikesNumber: this.video.dislikes
333 private handleError (err: any) {
334 const errorMessage: string = typeof err === 'string' ? err : err.message
335 if (!errorMessage) return
337 // Display a message in the video player instead of a notification
338 if (errorMessage.indexOf('from xs param') !== -1) {
340 this.remoteServerDown = true
341 this.changeDetector.detectChanges()
346 this.notificationsService.error(this.i18n('Error'), errorMessage)
349 private checkUserRating () {
350 // Unlogged users do not have ratings
351 if (this.isUserLoggedIn() === false) return
353 this.videoService.getUserVideoRating(this.video.id)
357 this.userRating = ratingObject.rating
361 err => this.notificationsService.error(this.i18n('Error'), err.message)
365 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
368 // Re init attributes
369 this.descriptionLoading = false
370 this.completeDescriptionShown = false
371 this.remoteServerDown = false
373 this.updateOtherVideosDisplayed()
375 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
376 const res = await this.confirmService.confirm(
377 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
378 this.i18n('Mature or explicit content')
380 if (res === false) return this.redirectService.redirectToHomepage()
383 // Flush old player if needed
386 // Build video element, because videojs remove it on dispose
387 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
388 this.playerElement = document.createElement('video')
389 this.playerElement.className = 'video-js vjs-peertube-skin'
390 this.playerElement.setAttribute('playsinline', 'true')
391 playerElementWrapper.appendChild(this.playerElement)
393 const playerCaptions = videoCaptions.map(c => ({
394 label: c.language.label,
395 language: c.language.id,
396 src: environment.apiUrl + c.captionPath
399 const videojsOptions = getVideojsOptions({
400 autoplay: this.isAutoplay(),
401 inactivityTimeout: 2500,
402 videoFiles: this.video.files,
403 videoCaptions: playerCaptions,
404 playerElement: this.playerElement,
405 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
406 videoDuration: this.video.duration,
409 poster: this.video.previewUrl,
414 if (this.videojsLocaleLoaded === false) {
415 await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
416 this.videojsLocaleLoaded = true
420 this.zone.runOutsideAngular(async () => {
421 videojs(this.playerElement, videojsOptions, function () {
423 this.on('customError', (event, data) => self.handleError(data.err))
425 addContextMenu(self.player, self.video.embedUrl)
429 this.setVideoDescriptionHTML()
430 this.setVideoLikesBarTooltipText()
432 this.setOpenGraphTags()
433 this.checkUserRating()
436 private setRating (nextRating) {
438 switch (nextRating) {
440 method = this.videoService.setVideoLike
443 method = this.videoService.setVideoDislike
446 method = this.videoService.unsetVideoLike
450 method.call(this.videoService, this.video.id)
453 // Update the video like attribute
454 this.updateVideoRating(this.userRating, nextRating)
455 this.userRating = nextRating
458 err => this.notificationsService.error(this.i18n('Error'), err.message)
462 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
463 let likesToIncrement = 0
464 let dislikesToIncrement = 0
467 if (oldRating === 'like') likesToIncrement--
468 if (oldRating === 'dislike') dislikesToIncrement--
471 if (newRating === 'like') likesToIncrement++
472 if (newRating === 'dislike') dislikesToIncrement++
474 this.video.likes += likesToIncrement
475 this.video.dislikes += dislikesToIncrement
477 this.video.buildLikeAndDislikePercents()
478 this.setVideoLikesBarTooltipText()
481 private updateOtherVideosDisplayed () {
482 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
483 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
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