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 // FIXME: something weird with our path definition in tsconfig and typings
12 import videojs from 'video.js'
13 import 'videojs-hotkeys'
14 import { Hotkey, HotkeysService } from 'angular2-hotkeys'
15 import * as WebTorrent from 'webtorrent'
16 import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
17 import '../../../assets/player/peertube-videojs-plugin'
18 import { AuthService, ConfirmService } from '../../core'
19 import { RestExtractor, VideoBlacklistService } from '../../shared'
20 import { VideoDetails } from '../../shared/video/video-details.model'
21 import { VideoService } from '../../shared/video/video.service'
22 import { MarkdownService } from '../shared'
23 import { VideoDownloadComponent } from './modal/video-download.component'
24 import { VideoReportComponent } from './modal/video-report.component'
25 import { VideoShareComponent } from './modal/video-share.component'
26 import { VideoBlacklistComponent } from './modal/video-blacklist.component'
27 import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
28 import { addContextMenu, getVideojsOptions, loadLocaleInVideoJS } from '../../../assets/player/peertube-player'
29 import { I18n } from '@ngx-translate/i18n-polyfill'
30 import { environment } from '../../../environments/environment'
31 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
32 import { VideoCaptionService } from '@app/shared/video-caption'
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
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
64 private videojsLocaleLoaded = false
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 notifier: Notifier,
80 private markdownService: MarkdownService,
82 private redirectService: RedirectService,
83 private videoCaptionService: VideoCaptionService,
85 private hotkeysService: HotkeysService,
86 @Inject(LOCALE_ID) private localeId: string
90 return this.authService.getUser()
95 WebTorrent.WEBRTC_SUPPORT === false ||
96 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
98 this.hasAlreadyAcceptedPrivacyConcern = true
101 this.paramsSub = this.route.params.subscribe(routeParams => {
102 const uuid = routeParams[ 'uuid' ]
104 // Video did not change
105 if (this.video && this.video.uuid === uuid) return
107 if (this.player) this.player.pause()
111 this.videoService.getVideo(uuid),
112 this.videoCaptionService.listCaptions(uuid)
115 // If 401, the video is private or blacklisted so redirect to 404
116 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
118 .subscribe(([ video, captionsResult ]) => {
119 const startTime = this.route.snapshot.queryParams.start
120 const subtitle = this.route.snapshot.queryParams.subtitle
122 this.onVideoFetched(video, captionsResult.data, { startTime, subtitle })
123 .catch(err => this.handleError(err))
128 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
131 }, undefined, this.i18n('Like the video')),
132 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
135 }, undefined, this.i18n('Dislike the video')),
136 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
137 this.subscribeButton.subscribed ?
138 this.subscribeButton.unsubscribe() :
139 this.subscribeButton.subscribe()
141 }, undefined, this.i18n('Subscribe to the account'))
143 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
149 // Unsubscribe subscriptions
150 this.paramsSub.unsubscribe()
153 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
157 if (this.isUserLoggedIn() === false) return
158 if (this.userRating === 'like') {
159 // Already liked this video
160 this.setRating('none')
162 this.setRating('like')
167 if (this.isUserLoggedIn() === false) return
168 if (this.userRating === 'dislike') {
169 // Already disliked this video
170 this.setRating('none')
172 this.setRating('dislike')
176 showMoreDescription () {
177 if (this.completeVideoDescription === undefined) {
178 return this.loadCompleteDescription()
181 this.updateVideoDescription(this.completeVideoDescription)
182 this.completeDescriptionShown = true
185 showLessDescription () {
186 this.updateVideoDescription(this.shortVideoDescription)
187 this.completeDescriptionShown = false
190 loadCompleteDescription () {
191 this.descriptionLoading = true
193 this.videoService.loadCompleteDescription(this.video.descriptionPath)
196 this.completeDescriptionShown = true
197 this.descriptionLoading = false
199 this.shortVideoDescription = this.video.description
200 this.completeVideoDescription = description
202 this.updateVideoDescription(this.completeVideoDescription)
206 this.descriptionLoading = false
207 this.notifier.error(error.message)
212 showReportModal (event: Event) {
213 event.preventDefault()
214 this.videoReportModal.show()
217 showSupportModal () {
218 this.videoSupportModal.show()
222 const currentTime = this.player ? this.player.currentTime() : undefined
224 this.videoShareModal.show(currentTime)
227 showDownloadModal (event: Event) {
228 event.preventDefault()
229 this.videoDownloadModal.show()
232 showBlacklistModal (event: Event) {
233 event.preventDefault()
234 this.videoBlacklistModal.show()
237 async unblacklistVideo (event: Event) {
238 event.preventDefault()
240 const confirmMessage = this.i18n(
241 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
244 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
245 if (res === false) return
247 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
249 this.notifier.success(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.notifier.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.notifier.success(this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name }))
296 // Go back to the video-list.
297 this.redirectService.redirectToHomepage()
300 error => this.notifier.error(error.message)
304 acceptedPrivacyConcern () {
305 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
306 this.hasAlreadyAcceptedPrivacyConcern = true
309 isVideoToTranscode () {
310 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
314 return this.video && this.video.state.id === VideoState.TO_IMPORT
317 hasVideoScheduledPublication () {
318 return this.video && this.video.scheduledUpdate !== undefined
321 private updateVideoDescription (description: string) {
322 this.video.description = description
323 this.setVideoDescriptionHTML()
326 private setVideoDescriptionHTML () {
327 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
330 private setVideoLikesBarTooltipText () {
331 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
332 likesNumber: this.video.likes,
333 dislikesNumber: this.video.dislikes
337 private handleError (err: any) {
338 const errorMessage: string = typeof err === 'string' ? err : err.message
339 if (!errorMessage) return
341 // Display a message in the video player instead of a notification
342 if (errorMessage.indexOf('from xs param') !== -1) {
344 this.remoteServerDown = true
345 this.changeDetector.detectChanges()
350 this.notifier.error(errorMessage)
353 private checkUserRating () {
354 // Unlogged users do not have ratings
355 if (this.isUserLoggedIn() === false) return
357 this.videoService.getUserVideoRating(this.video.id)
361 this.userRating = ratingObject.rating
365 err => this.notifier.error(err.message)
369 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], urlOptions: { startTime: number, subtitle: string }) {
372 // Re init attributes
373 this.descriptionLoading = false
374 this.completeDescriptionShown = false
375 this.remoteServerDown = false
377 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
378 // If we are at the end of the video, reset the timer
379 if (this.video.duration - startTime <= 1) startTime = 0
381 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
382 const res = await this.confirmService.confirm(
383 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
384 this.i18n('Mature or explicit content')
386 if (res === false) return this.redirectService.redirectToHomepage()
389 // Flush old player if needed
392 // Build video element, because videojs remove it on dispose
393 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
394 this.playerElement = document.createElement('video')
395 this.playerElement.className = 'video-js vjs-peertube-skin'
396 this.playerElement.setAttribute('playsinline', 'true')
397 playerElementWrapper.appendChild(this.playerElement)
399 const playerCaptions = videoCaptions.map(c => ({
400 label: c.language.label,
401 language: c.language.id,
402 src: environment.apiUrl + c.captionPath
405 const videojsOptions = getVideojsOptions({
406 autoplay: this.isAutoplay(),
407 inactivityTimeout: 2500,
408 videoFiles: this.video.files,
409 videoCaptions: playerCaptions,
410 playerElement: this.playerElement,
411 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
412 videoDuration: this.video.duration,
415 poster: this.video.previewUrl,
417 subtitle: urlOptions.subtitle,
419 language: this.localeId,
421 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
422 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
423 authorizationHeader: this.authService.getRequestHeaderValue()
427 if (this.videojsLocaleLoaded === false) {
428 await loadLocaleInVideoJS(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
429 this.videojsLocaleLoaded = true
433 this.zone.runOutsideAngular(async () => {
434 videojs(this.playerElement, videojsOptions, function (this: videojs.Player) {
436 this.on('customError', ({ err }: { err: any }) => self.handleError(err))
438 addContextMenu(self.player, self.video.embedUrl)
442 this.setVideoDescriptionHTML()
443 this.setVideoLikesBarTooltipText()
445 this.setOpenGraphTags()
446 this.checkUserRating()
449 private setRating (nextRating: UserVideoRateType) {
451 switch (nextRating) {
453 method = this.videoService.setVideoLike
456 method = this.videoService.setVideoDislike
459 method = this.videoService.unsetVideoLike
463 method.call(this.videoService, this.video.id)
466 // Update the video like attribute
467 this.updateVideoRating(this.userRating, nextRating)
468 this.userRating = nextRating
471 (err: { message: string }) => this.notifier.error(err.message)
475 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
476 let likesToIncrement = 0
477 let dislikesToIncrement = 0
480 if (oldRating === 'like') likesToIncrement--
481 if (oldRating === 'dislike') dislikesToIncrement--
484 if (newRating === 'like') likesToIncrement++
485 if (newRating === 'dislike') dislikesToIncrement++
487 this.video.likes += likesToIncrement
488 this.video.dislikes += dislikesToIncrement
490 this.video.buildLikeAndDislikePercents()
491 this.setVideoLikesBarTooltipText()
494 private setOpenGraphTags () {
495 this.metaService.setTitle(this.video.name)
497 this.metaService.setTag('og:type', 'video')
499 this.metaService.setTag('og:title', this.video.name)
500 this.metaService.setTag('name', this.video.name)
502 this.metaService.setTag('og:description', this.video.description)
503 this.metaService.setTag('description', this.video.description)
505 this.metaService.setTag('og:image', this.video.previewPath)
507 this.metaService.setTag('og:duration', this.video.duration.toString())
509 this.metaService.setTag('og:site_name', 'PeerTube')
511 this.metaService.setTag('og:url', window.location.href)
512 this.metaService.setTag('url', window.location.href)
515 private isAutoplay () {
516 // We'll jump to the thread id, so do not play the video
517 if (this.route.snapshot.params['threadId']) return false
519 // Otherwise true by default
520 if (!this.user) return true
522 // Be sure the autoPlay is set to false
523 return this.user.autoPlayVideo !== false
526 private flushPlayer () {
527 // Remove player if it exists
529 this.player.dispose()
530 this.player = undefined