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 // 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, VideoRateType, 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 { ServerService } from '@app/core'
30 import { I18n } from '@ngx-translate/i18n-polyfill'
31 import { environment } from '../../../environments/environment'
32 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
33 import { VideoCaptionService } from '@app/shared/video-caption'
36 selector: 'my-video-watch',
37 templateUrl: './video-watch.component.html',
38 styleUrls: [ './video-watch.component.scss' ]
40 export class VideoWatchComponent implements OnInit, OnDestroy {
41 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
43 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
44 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
45 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
46 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
47 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
48 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
50 player: videojs.Player
51 playerElement: HTMLVideoElement
52 userRating: UserVideoRateType = null
53 video: VideoDetails = null
54 descriptionLoading = false
56 completeDescriptionShown = false
57 completeVideoDescription: string
58 shortVideoDescription: string
59 videoHTMLDescription = ''
60 likesBarTooltipText = ''
61 hasAlreadyAcceptedPrivacyConcern = false
62 remoteServerDown = false
65 private videojsLocaleLoaded = false
66 private paramsSub: Subscription
69 private elementRef: ElementRef,
70 private changeDetector: ChangeDetectorRef,
71 private route: ActivatedRoute,
72 private router: Router,
73 private videoService: VideoService,
74 private videoBlacklistService: VideoBlacklistService,
75 private confirmService: ConfirmService,
76 private metaService: MetaService,
77 private authService: AuthService,
78 private serverService: ServerService,
79 private restExtractor: RestExtractor,
80 private notificationsService: NotificationsService,
81 private markdownService: MarkdownService,
83 private redirectService: RedirectService,
84 private videoCaptionService: VideoCaptionService,
86 private hotkeysService: HotkeysService,
87 @Inject(LOCALE_ID) private localeId: string
91 return this.authService.getUser()
96 WebTorrent.WEBRTC_SUPPORT === false ||
97 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
99 this.hasAlreadyAcceptedPrivacyConcern = true
102 this.paramsSub = this.route.params.subscribe(routeParams => {
103 const uuid = routeParams[ 'uuid' ]
105 // Video did not change
106 if (this.video && this.video.uuid === uuid) return
108 if (this.player) this.player.pause()
112 this.videoService.getVideo(uuid),
113 this.videoCaptionService.listCaptions(uuid)
116 // If 401, the video is private or blacklisted so redirect to 404
117 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
119 .subscribe(([ video, captionsResult ]) => {
120 const startTime = this.route.snapshot.queryParams.start
121 this.onVideoFetched(video, captionsResult.data, startTime)
122 .catch(err => this.handleError(err))
127 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
130 }, undefined, this.i18n('Like the video')),
131 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
134 }, undefined, this.i18n('Dislike the video')),
135 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
136 this.subscribeButton.subscribed ?
137 this.subscribeButton.unsubscribe() :
138 this.subscribeButton.subscribe()
140 }, undefined, this.i18n('Subscribe to the account'))
142 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
148 // Unsubscribe subscriptions
149 this.paramsSub.unsubscribe()
152 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
156 if (this.isUserLoggedIn() === false) return
157 if (this.userRating === 'like') {
158 // Already liked this video
159 this.setRating('none')
161 this.setRating('like')
166 if (this.isUserLoggedIn() === false) return
167 if (this.userRating === 'dislike') {
168 // Already disliked this video
169 this.setRating('none')
171 this.setRating('dislike')
175 showMoreDescription () {
176 if (this.completeVideoDescription === undefined) {
177 return this.loadCompleteDescription()
180 this.updateVideoDescription(this.completeVideoDescription)
181 this.completeDescriptionShown = true
184 showLessDescription () {
185 this.updateVideoDescription(this.shortVideoDescription)
186 this.completeDescriptionShown = false
189 loadCompleteDescription () {
190 this.descriptionLoading = true
192 this.videoService.loadCompleteDescription(this.video.descriptionPath)
195 this.completeDescriptionShown = true
196 this.descriptionLoading = false
198 this.shortVideoDescription = this.video.description
199 this.completeVideoDescription = description
201 this.updateVideoDescription(this.completeVideoDescription)
205 this.descriptionLoading = false
206 this.notificationsService.error(this.i18n('Error'), error.message)
211 showReportModal (event: Event) {
212 event.preventDefault()
213 this.videoReportModal.show()
216 showSupportModal () {
217 this.videoSupportModal.show()
221 const currentTime = this.player ? this.player.currentTime() : undefined
223 this.videoShareModal.show(currentTime)
226 showDownloadModal (event: Event) {
227 event.preventDefault()
228 this.videoDownloadModal.show()
231 showBlacklistModal (event: Event) {
232 event.preventDefault()
233 this.videoBlacklistModal.show()
236 async unblacklistVideo (event: Event) {
237 event.preventDefault()
239 const confirmMessage = this.i18n(
240 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
243 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
244 if (res === false) return
246 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
248 this.notificationsService.success(
249 this.i18n('Success'),
250 this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name })
253 this.video.blacklisted = false
254 this.video.blacklistedReason = null
257 err => this.notificationsService.error(this.i18n('Error'), err.message)
262 return this.authService.isLoggedIn()
265 isVideoUpdatable () {
266 return this.video.isUpdatableBy(this.authService.getUser())
269 isVideoBlacklistable () {
270 return this.video.isBlackistableBy(this.user)
273 isVideoUnblacklistable () {
274 return this.video.isUnblacklistableBy(this.user)
278 if (!this.video || Array.isArray(this.video.tags) === false) return []
280 return this.video.tags
283 isVideoRemovable () {
284 return this.video.isRemovableBy(this.authService.getUser())
287 async removeVideo (event: Event) {
288 event.preventDefault()
290 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
291 if (res === false) return
293 this.videoService.removeVideo(this.video.id)
296 this.notificationsService.success(
297 this.i18n('Success'),
298 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
301 // Go back to the video-list.
302 this.redirectService.redirectToHomepage()
305 error => this.notificationsService.error(this.i18n('Error'), error.message)
309 acceptedPrivacyConcern () {
310 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
311 this.hasAlreadyAcceptedPrivacyConcern = true
314 isVideoToTranscode () {
315 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
319 return this.video && this.video.state.id === VideoState.TO_IMPORT
322 hasVideoScheduledPublication () {
323 return this.video && this.video.scheduledUpdate !== undefined
326 private updateVideoDescription (description: string) {
327 this.video.description = description
328 this.setVideoDescriptionHTML()
331 private setVideoDescriptionHTML () {
332 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
335 private setVideoLikesBarTooltipText () {
336 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
337 likesNumber: this.video.likes,
338 dislikesNumber: this.video.dislikes
342 private handleError (err: any) {
343 const errorMessage: string = typeof err === 'string' ? err : err.message
344 if (!errorMessage) return
346 // Display a message in the video player instead of a notification
347 if (errorMessage.indexOf('from xs param') !== -1) {
349 this.remoteServerDown = true
350 this.changeDetector.detectChanges()
355 this.notificationsService.error(this.i18n('Error'), errorMessage)
358 private checkUserRating () {
359 // Unlogged users do not have ratings
360 if (this.isUserLoggedIn() === false) return
362 this.videoService.getUserVideoRating(this.video.id)
366 this.userRating = ratingObject.rating
370 err => this.notificationsService.error(this.i18n('Error'), err.message)
374 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTimeFromUrl: number) {
377 // Re init attributes
378 this.descriptionLoading = false
379 this.completeDescriptionShown = false
380 this.remoteServerDown = false
382 let startTime = startTimeFromUrl || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
383 // Don't start the video if we are at the end
384 if (this.video.duration - startTime <= 1) startTime = 0
386 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
387 const res = await this.confirmService.confirm(
388 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
389 this.i18n('Mature or explicit content')
391 if (res === false) return this.redirectService.redirectToHomepage()
394 // Flush old player if needed
397 // Build video element, because videojs remove it on dispose
398 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
399 this.playerElement = document.createElement('video')
400 this.playerElement.className = 'video-js vjs-peertube-skin'
401 this.playerElement.setAttribute('playsinline', 'true')
402 playerElementWrapper.appendChild(this.playerElement)
404 const playerCaptions = videoCaptions.map(c => ({
405 label: c.language.label,
406 language: c.language.id,
407 src: environment.apiUrl + c.captionPath
410 const videojsOptions = getVideojsOptions({
411 autoplay: this.isAutoplay(),
412 inactivityTimeout: 2500,
413 videoFiles: this.video.files,
414 videoCaptions: playerCaptions,
415 playerElement: this.playerElement,
416 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
417 videoDuration: this.video.duration,
420 poster: this.video.previewUrl,
423 language: this.localeId,
425 userWatching: this.user ? {
426 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
427 authorizationHeader: this.authService.getRequestHeaderValue()
431 if (this.videojsLocaleLoaded === false) {
432 await loadLocaleInVideoJS(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
433 this.videojsLocaleLoaded = true
437 this.zone.runOutsideAngular(async () => {
438 videojs(this.playerElement, videojsOptions, function (this: videojs.Player) {
440 this.on('customError', ({ err }: { err: any }) => self.handleError(err))
442 addContextMenu(self.player, self.video.embedUrl)
446 this.setVideoDescriptionHTML()
447 this.setVideoLikesBarTooltipText()
449 this.setOpenGraphTags()
450 this.checkUserRating()
453 private setRating (nextRating: UserVideoRateType) {
455 switch (nextRating) {
457 method = this.videoService.setVideoLike
460 method = this.videoService.setVideoDislike
463 method = this.videoService.unsetVideoLike
467 method.call(this.videoService, this.video.id)
470 // Update the video like attribute
471 this.updateVideoRating(this.userRating, nextRating)
472 this.userRating = nextRating
475 (err: { message: string }) => this.notificationsService.error(this.i18n('Error'), err.message)
479 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
480 let likesToIncrement = 0
481 let dislikesToIncrement = 0
484 if (oldRating === 'like') likesToIncrement--
485 if (oldRating === 'dislike') dislikesToIncrement--
488 if (newRating === 'like') likesToIncrement++
489 if (newRating === 'dislike') dislikesToIncrement++
491 this.video.likes += likesToIncrement
492 this.video.dislikes += dislikesToIncrement
494 this.video.buildLikeAndDislikePercents()
495 this.setVideoLikesBarTooltipText()
498 private setOpenGraphTags () {
499 this.metaService.setTitle(this.video.name)
501 this.metaService.setTag('og:type', 'video')
503 this.metaService.setTag('og:title', this.video.name)
504 this.metaService.setTag('name', this.video.name)
506 this.metaService.setTag('og:description', this.video.description)
507 this.metaService.setTag('description', this.video.description)
509 this.metaService.setTag('og:image', this.video.previewPath)
511 this.metaService.setTag('og:duration', this.video.duration.toString())
513 this.metaService.setTag('og:site_name', 'PeerTube')
515 this.metaService.setTag('og:url', window.location.href)
516 this.metaService.setTag('url', window.location.href)
519 private isAutoplay () {
520 // We'll jump to the thread id, so do not play the video
521 if (this.route.snapshot.params['threadId']) return false
523 // Otherwise true by default
524 if (!this.user) return true
526 // Be sure the autoPlay is set to false
527 return this.user.autoPlayVideo !== false
530 private flushPlayer () {
531 // Remove player if it exists
533 this.player.dispose()
534 this.player = undefined