1 import { catchError } from 'rxjs/operators'
2 import { 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 { ResultList, 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'
31 import { VideoJSCaption } from '../../../assets/player/peertube-videojs-typings'
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
46 otherVideosDisplayed: Video[] = []
48 player: videojs.Player
49 playerElement: HTMLVideoElement
50 userRating: UserVideoRateType = null
51 video: VideoDetails = null
52 descriptionLoading = false
54 completeDescriptionShown = false
55 completeVideoDescription: string
56 shortVideoDescription: string
57 videoHTMLDescription = ''
58 likesBarTooltipText = ''
59 hasAlreadyAcceptedPrivacyConcern = false
61 private videojsLocaleLoaded = false
62 private otherVideos: Video[] = []
63 private paramsSub: Subscription
66 private elementRef: ElementRef,
67 private route: ActivatedRoute,
68 private router: Router,
69 private videoService: VideoService,
70 private videoBlacklistService: VideoBlacklistService,
71 private confirmService: ConfirmService,
72 private metaService: MetaService,
73 private authService: AuthService,
74 private serverService: ServerService,
75 private restExtractor: RestExtractor,
76 private notificationsService: NotificationsService,
77 private markdownService: MarkdownService,
79 private redirectService: RedirectService,
80 private videoCaptionService: VideoCaptionService,
82 @Inject(LOCALE_ID) private localeId: string
86 return this.authService.getUser()
91 WebTorrent.WEBRTC_SUPPORT === false ||
92 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
94 this.hasAlreadyAcceptedPrivacyConcern = true
97 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
100 this.otherVideos = data.videos
101 this.updateOtherVideosDisplayed()
104 err => console.error(err)
107 this.paramsSub = this.route.params.subscribe(routeParams => {
108 const uuid = routeParams[ 'uuid' ]
110 // Video did not change
111 if (this.video && this.video.uuid === uuid) return
113 if (this.player) this.player.pause()
117 this.videoService.getVideo(uuid),
118 this.videoCaptionService.listCaptions(uuid)
121 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ]))
123 .subscribe(([ video, captionsResult ]) => {
124 const startTime = this.route.snapshot.queryParams.start
125 this.onVideoFetched(video, captionsResult.data, startTime)
126 .catch(err => this.handleError(err))
134 // Unsubscribe subscriptions
135 this.paramsSub.unsubscribe()
139 if (this.isUserLoggedIn() === false) return
140 if (this.userRating === 'like') {
141 // Already liked this video
142 this.setRating('none')
144 this.setRating('like')
149 if (this.isUserLoggedIn() === false) return
150 if (this.userRating === 'dislike') {
151 // Already disliked this video
152 this.setRating('none')
154 this.setRating('dislike')
158 async blacklistVideo (event: Event) {
159 event.preventDefault()
161 const res = await this.confirmService.confirm(this.i18n('Do you really want to blacklist this video?'), this.i18n('Blacklist'))
162 if (res === false) return
164 this.videoBlacklistService.blacklistVideo(this.video.id)
167 this.notificationsService.success(
168 this.i18n('Success'),
169 this.i18n('Video {{videoName}} had been blacklisted.', { videoName: this.video.name })
171 this.redirectService.redirectToHomepage()
174 error => this.notificationsService.error(this.i18n('Error'), error.message)
178 showMoreDescription () {
179 if (this.completeVideoDescription === undefined) {
180 return this.loadCompleteDescription()
183 this.updateVideoDescription(this.completeVideoDescription)
184 this.completeDescriptionShown = true
187 showLessDescription () {
188 this.updateVideoDescription(this.shortVideoDescription)
189 this.completeDescriptionShown = false
192 loadCompleteDescription () {
193 this.descriptionLoading = true
195 this.videoService.loadCompleteDescription(this.video.descriptionPath)
198 this.completeDescriptionShown = true
199 this.descriptionLoading = false
201 this.shortVideoDescription = this.video.description
202 this.completeVideoDescription = description
204 this.updateVideoDescription(this.completeVideoDescription)
208 this.descriptionLoading = false
209 this.notificationsService.error(this.i18n('Error'), error.message)
214 showReportModal (event: Event) {
215 event.preventDefault()
216 this.videoReportModal.show()
219 showSupportModal () {
220 this.videoSupportModal.show()
224 this.videoShareModal.show()
227 showDownloadModal (event: Event) {
228 event.preventDefault()
229 this.videoDownloadModal.show()
233 return this.authService.isLoggedIn()
236 isVideoUpdatable () {
237 return this.video.isUpdatableBy(this.authService.getUser())
240 isVideoBlacklistable () {
241 return this.video.isBlackistableBy(this.user)
245 if (!this.video) return ''
247 return this.video.previewUrl
251 if (!this.video || Array.isArray(this.video.tags) === false) return []
253 return this.video.tags.join(', ')
256 isVideoRemovable () {
257 return this.video.isRemovableBy(this.authService.getUser())
260 async removeVideo (event: Event) {
261 event.preventDefault()
263 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
264 if (res === false) return
266 this.videoService.removeVideo(this.video.id)
269 this.notificationsService.success(
270 this.i18n('Success'),
271 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
274 // Go back to the video-list.
275 this.redirectService.redirectToHomepage()
278 error => this.notificationsService.error(this.i18n('Error'), error.message)
282 acceptedPrivacyConcern () {
283 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
284 this.hasAlreadyAcceptedPrivacyConcern = true
287 isVideoToTranscode () {
288 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
291 hasVideoScheduledPublication () {
292 return this.video && this.video.scheduledUpdate !== undefined
295 private updateVideoDescription (description: string) {
296 this.video.description = description
297 this.setVideoDescriptionHTML()
300 private setVideoDescriptionHTML () {
301 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
304 private setVideoLikesBarTooltipText () {
305 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
306 likesNumber: this.video.likes,
307 dislikesNumber: this.video.dislikes
311 private handleError (err: any) {
312 const errorMessage: string = typeof err === 'string' ? err : err.message
313 if (!errorMessage) return
317 if (errorMessage.indexOf('http error') !== -1) {
318 message = this.i18n('Cannot fetch video from server, maybe down.')
320 message = errorMessage
323 this.notificationsService.error(this.i18n('Error'), message)
326 private checkUserRating () {
327 // Unlogged users do not have ratings
328 if (this.isUserLoggedIn() === false) return
330 this.videoService.getUserVideoRating(this.video.id)
334 this.userRating = ratingObject.rating
338 err => this.notificationsService.error(this.i18n('Error'), err.message)
342 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
345 // Re init attributes
346 this.descriptionLoading = false
347 this.completeDescriptionShown = false
349 this.updateOtherVideosDisplayed()
351 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
352 const res = await this.confirmService.confirm(
353 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
354 this.i18n('Mature or explicit content')
356 if (res === false) return this.redirectService.redirectToHomepage()
359 // Flush old player if needed
362 // Build video element, because videojs remove it on dispose
363 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
364 this.playerElement = document.createElement('video')
365 this.playerElement.className = 'video-js vjs-peertube-skin'
366 this.playerElement.setAttribute('playsinline', 'true')
367 playerElementWrapper.appendChild(this.playerElement)
369 const playerCaptions = videoCaptions.map(c => ({
370 label: c.language.label,
371 language: c.language.id,
372 src: environment.apiUrl + c.captionPath
375 const videojsOptions = getVideojsOptions({
376 autoplay: this.isAutoplay(),
377 inactivityTimeout: 2500,
378 videoFiles: this.video.files,
379 videoCaptions: playerCaptions,
380 playerElement: this.playerElement,
381 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
382 videoDuration: this.video.duration,
385 poster: this.video.previewUrl,
390 if (this.videojsLocaleLoaded === false) {
391 await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
392 this.videojsLocaleLoaded = true
396 this.zone.runOutsideAngular(async () => {
397 videojs(this.playerElement, videojsOptions, function () {
399 this.on('customError', (event, data) => self.handleError(data.err))
401 addContextMenu(self.player, self.video.embedUrl)
405 this.setVideoDescriptionHTML()
406 this.setVideoLikesBarTooltipText()
408 this.setOpenGraphTags()
409 this.checkUserRating()
412 private setRating (nextRating) {
414 switch (nextRating) {
416 method = this.videoService.setVideoLike
419 method = this.videoService.setVideoDislike
422 method = this.videoService.unsetVideoLike
426 method.call(this.videoService, this.video.id)
429 // Update the video like attribute
430 this.updateVideoRating(this.userRating, nextRating)
431 this.userRating = nextRating
434 err => this.notificationsService.error(this.i18n('Error'), err.message)
438 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
439 let likesToIncrement = 0
440 let dislikesToIncrement = 0
443 if (oldRating === 'like') likesToIncrement--
444 if (oldRating === 'dislike') dislikesToIncrement--
447 if (newRating === 'like') likesToIncrement++
448 if (newRating === 'dislike') dislikesToIncrement++
450 this.video.likes += likesToIncrement
451 this.video.dislikes += dislikesToIncrement
453 this.video.buildLikeAndDislikePercents()
454 this.setVideoLikesBarTooltipText()
457 private updateOtherVideosDisplayed () {
458 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
459 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
463 private setOpenGraphTags () {
464 this.metaService.setTitle(this.video.name)
466 this.metaService.setTag('og:type', 'video')
468 this.metaService.setTag('og:title', this.video.name)
469 this.metaService.setTag('name', this.video.name)
471 this.metaService.setTag('og:description', this.video.description)
472 this.metaService.setTag('description', this.video.description)
474 this.metaService.setTag('og:image', this.video.previewPath)
476 this.metaService.setTag('og:duration', this.video.duration.toString())
478 this.metaService.setTag('og:site_name', 'PeerTube')
480 this.metaService.setTag('og:url', window.location.href)
481 this.metaService.setTag('url', window.location.href)
484 private isAutoplay () {
485 // We'll jump to the thread id, so do not play the video
486 if (this.route.snapshot.params['threadId']) return false
488 // Otherwise true by default
489 if (!this.user) return true
491 // Be sure the autoPlay is set to false
492 return this.user.autoPlayVideo !== false
495 private flushPlayer () {
496 // Remove player if it exists
498 this.player.dispose()
499 this.player = undefined