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 { addContextMenu, getVideojsOptions, loadLocale } 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'
30 import { VideoCaption } from '../../../../../shared/models/videos/video-caption.model'
33 selector: 'my-video-watch',
34 templateUrl: './video-watch.component.html',
35 styleUrls: [ './video-watch.component.scss' ]
37 export class VideoWatchComponent implements OnInit, OnDestroy {
38 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
40 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
41 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
42 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
43 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
45 otherVideosDisplayed: Video[] = []
47 player: videojs.Player
48 playerElement: HTMLVideoElement
49 userRating: UserVideoRateType = null
50 video: VideoDetails = null
51 descriptionLoading = false
53 completeDescriptionShown = false
54 completeVideoDescription: string
55 shortVideoDescription: string
56 videoHTMLDescription = ''
57 likesBarTooltipText = ''
58 hasAlreadyAcceptedPrivacyConcern = false
59 remoteServerDown = false
61 private videojsLocaleLoaded = false
62 private otherVideos: Video[] = []
63 private paramsSub: Subscription
66 private elementRef: ElementRef,
67 private changeDetector: ChangeDetectorRef,
68 private route: ActivatedRoute,
69 private router: Router,
70 private videoService: VideoService,
71 private videoBlacklistService: VideoBlacklistService,
72 private confirmService: ConfirmService,
73 private metaService: MetaService,
74 private authService: AuthService,
75 private serverService: ServerService,
76 private restExtractor: RestExtractor,
77 private notificationsService: NotificationsService,
78 private markdownService: MarkdownService,
80 private redirectService: RedirectService,
81 private videoCaptionService: VideoCaptionService,
83 @Inject(LOCALE_ID) private localeId: string
87 return this.authService.getUser()
92 WebTorrent.WEBRTC_SUPPORT === false ||
93 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
95 this.hasAlreadyAcceptedPrivacyConcern = true
98 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
101 this.otherVideos = data.videos
102 this.updateOtherVideosDisplayed()
105 err => console.error(err)
108 this.paramsSub = this.route.params.subscribe(routeParams => {
109 const uuid = routeParams[ 'uuid' ]
111 // Video did not change
112 if (this.video && this.video.uuid === uuid) return
114 if (this.player) this.player.pause()
118 this.videoService.getVideo(uuid),
119 this.videoCaptionService.listCaptions(uuid)
122 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ]))
124 .subscribe(([ video, captionsResult ]) => {
125 const startTime = this.route.snapshot.queryParams.start
126 this.onVideoFetched(video, captionsResult.data, startTime)
127 .catch(err => this.handleError(err))
135 // Unsubscribe subscriptions
136 this.paramsSub.unsubscribe()
140 if (this.isUserLoggedIn() === false) return
141 if (this.userRating === 'like') {
142 // Already liked this video
143 this.setRating('none')
145 this.setRating('like')
150 if (this.isUserLoggedIn() === false) return
151 if (this.userRating === 'dislike') {
152 // Already disliked this video
153 this.setRating('none')
155 this.setRating('dislike')
159 async blacklistVideo (event: Event) {
160 event.preventDefault()
162 const res = await this.confirmService.confirm(this.i18n('Do you really want to blacklist this video?'), this.i18n('Blacklist'))
163 if (res === false) return
165 this.videoBlacklistService.blacklistVideo(this.video.id)
168 this.notificationsService.success(
169 this.i18n('Success'),
170 this.i18n('Video {{videoName}} had been blacklisted.', { videoName: this.video.name })
172 this.redirectService.redirectToHomepage()
175 error => this.notificationsService.error(this.i18n('Error'), error.message)
179 showMoreDescription () {
180 if (this.completeVideoDescription === undefined) {
181 return this.loadCompleteDescription()
184 this.updateVideoDescription(this.completeVideoDescription)
185 this.completeDescriptionShown = true
188 showLessDescription () {
189 this.updateVideoDescription(this.shortVideoDescription)
190 this.completeDescriptionShown = false
193 loadCompleteDescription () {
194 this.descriptionLoading = true
196 this.videoService.loadCompleteDescription(this.video.descriptionPath)
199 this.completeDescriptionShown = true
200 this.descriptionLoading = false
202 this.shortVideoDescription = this.video.description
203 this.completeVideoDescription = description
205 this.updateVideoDescription(this.completeVideoDescription)
209 this.descriptionLoading = false
210 this.notificationsService.error(this.i18n('Error'), error.message)
215 showReportModal (event: Event) {
216 event.preventDefault()
217 this.videoReportModal.show()
220 showSupportModal () {
221 this.videoSupportModal.show()
225 this.videoShareModal.show()
228 showDownloadModal (event: Event) {
229 event.preventDefault()
230 this.videoDownloadModal.show()
234 return this.authService.isLoggedIn()
237 isVideoUpdatable () {
238 return this.video.isUpdatableBy(this.authService.getUser())
241 isVideoBlacklistable () {
242 return this.video.isBlackistableBy(this.user)
246 if (!this.video) return ''
248 return this.video.previewUrl
252 if (!this.video || Array.isArray(this.video.tags) === false) return []
254 return this.video.tags
257 isVideoRemovable () {
258 return this.video.isRemovableBy(this.authService.getUser())
261 async removeVideo (event: Event) {
262 event.preventDefault()
264 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
265 if (res === false) return
267 this.videoService.removeVideo(this.video.id)
270 this.notificationsService.success(
271 this.i18n('Success'),
272 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
275 // Go back to the video-list.
276 this.redirectService.redirectToHomepage()
279 error => this.notificationsService.error(this.i18n('Error'), error.message)
283 acceptedPrivacyConcern () {
284 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
285 this.hasAlreadyAcceptedPrivacyConcern = true
288 isVideoToTranscode () {
289 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
293 return this.video && this.video.state.id === VideoState.TO_IMPORT
296 hasVideoScheduledPublication () {
297 return this.video && this.video.scheduledUpdate !== undefined
300 private updateVideoDescription (description: string) {
301 this.video.description = description
302 this.setVideoDescriptionHTML()
305 private setVideoDescriptionHTML () {
306 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
309 private setVideoLikesBarTooltipText () {
310 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
311 likesNumber: this.video.likes,
312 dislikesNumber: this.video.dislikes
316 private handleError (err: any) {
317 const errorMessage: string = typeof err === 'string' ? err : err.message
318 if (!errorMessage) return
320 // Display a message in the video player instead of a notification
321 if (errorMessage.indexOf('from xs param') !== -1) {
323 this.remoteServerDown = true
324 this.changeDetector.detectChanges()
329 this.notificationsService.error(this.i18n('Error'), errorMessage)
332 private checkUserRating () {
333 // Unlogged users do not have ratings
334 if (this.isUserLoggedIn() === false) return
336 this.videoService.getUserVideoRating(this.video.id)
340 this.userRating = ratingObject.rating
344 err => this.notificationsService.error(this.i18n('Error'), err.message)
348 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
351 // Re init attributes
352 this.descriptionLoading = false
353 this.completeDescriptionShown = false
354 this.remoteServerDown = false
356 this.updateOtherVideosDisplayed()
358 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
359 const res = await this.confirmService.confirm(
360 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
361 this.i18n('Mature or explicit content')
363 if (res === false) return this.redirectService.redirectToHomepage()
366 // Flush old player if needed
369 // Build video element, because videojs remove it on dispose
370 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
371 this.playerElement = document.createElement('video')
372 this.playerElement.className = 'video-js vjs-peertube-skin'
373 this.playerElement.setAttribute('playsinline', 'true')
374 playerElementWrapper.appendChild(this.playerElement)
376 const playerCaptions = videoCaptions.map(c => ({
377 label: c.language.label,
378 language: c.language.id,
379 src: environment.apiUrl + c.captionPath
382 const videojsOptions = getVideojsOptions({
383 autoplay: this.isAutoplay(),
384 inactivityTimeout: 2500,
385 videoFiles: this.video.files,
386 videoCaptions: playerCaptions,
387 playerElement: this.playerElement,
388 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
389 videoDuration: this.video.duration,
392 poster: this.video.previewUrl,
397 if (this.videojsLocaleLoaded === false) {
398 await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
399 this.videojsLocaleLoaded = true
403 this.zone.runOutsideAngular(async () => {
404 videojs(this.playerElement, videojsOptions, function () {
406 this.on('customError', (event, data) => self.handleError(data.err))
408 addContextMenu(self.player, self.video.embedUrl)
412 this.setVideoDescriptionHTML()
413 this.setVideoLikesBarTooltipText()
415 this.setOpenGraphTags()
416 this.checkUserRating()
419 private setRating (nextRating) {
421 switch (nextRating) {
423 method = this.videoService.setVideoLike
426 method = this.videoService.setVideoDislike
429 method = this.videoService.unsetVideoLike
433 method.call(this.videoService, this.video.id)
436 // Update the video like attribute
437 this.updateVideoRating(this.userRating, nextRating)
438 this.userRating = nextRating
441 err => this.notificationsService.error(this.i18n('Error'), err.message)
445 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
446 let likesToIncrement = 0
447 let dislikesToIncrement = 0
450 if (oldRating === 'like') likesToIncrement--
451 if (oldRating === 'dislike') dislikesToIncrement--
454 if (newRating === 'like') likesToIncrement++
455 if (newRating === 'dislike') dislikesToIncrement++
457 this.video.likes += likesToIncrement
458 this.video.dislikes += dislikesToIncrement
460 this.video.buildLikeAndDislikePercents()
461 this.setVideoLikesBarTooltipText()
464 private updateOtherVideosDisplayed () {
465 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
466 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
470 private setOpenGraphTags () {
471 this.metaService.setTitle(this.video.name)
473 this.metaService.setTag('og:type', 'video')
475 this.metaService.setTag('og:title', this.video.name)
476 this.metaService.setTag('name', this.video.name)
478 this.metaService.setTag('og:description', this.video.description)
479 this.metaService.setTag('description', this.video.description)
481 this.metaService.setTag('og:image', this.video.previewPath)
483 this.metaService.setTag('og:duration', this.video.duration.toString())
485 this.metaService.setTag('og:site_name', 'PeerTube')
487 this.metaService.setTag('og:url', window.location.href)
488 this.metaService.setTag('url', window.location.href)
491 private isAutoplay () {
492 // We'll jump to the thread id, so do not play the video
493 if (this.route.snapshot.params['threadId']) return false
495 // Otherwise true by default
496 if (!this.user) return true
498 // Be sure the autoPlay is set to false
499 return this.user.autoPlayVideo !== false
502 private flushPlayer () {
503 // Remove player if it exists
505 this.player.dispose()
506 this.player = undefined