1 import { catchError } from 'rxjs/operators'
2 import { Component, ElementRef, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild, Inject } 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 { Subscription } from 'rxjs'
10 import * as videojs from 'video.js'
11 import 'videojs-hotkeys'
12 import * as WebTorrent from 'webtorrent'
13 import { UserVideoRateType, VideoRateType } 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 { getVideojsOptions, loadLocale, addContextMenu } 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'
31 selector: 'my-video-watch',
32 templateUrl: './video-watch.component.html',
33 styleUrls: [ './video-watch.component.scss' ]
35 export class VideoWatchComponent implements OnInit, OnDestroy {
36 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
38 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
39 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
40 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
41 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
43 otherVideosDisplayed: Video[] = []
45 player: videojs.Player
46 playerElement: HTMLVideoElement
47 userRating: UserVideoRateType = null
48 video: VideoDetails = null
50 descriptionLoading = false
52 completeDescriptionShown = false
53 completeVideoDescription: string
54 shortVideoDescription: string
55 videoHTMLDescription = ''
56 likesBarTooltipText = ''
57 hasAlreadyAcceptedPrivacyConcern = false
59 private videojsLocaleLoaded = false
60 private otherVideos: Video[] = []
61 private paramsSub: Subscription
64 private elementRef: ElementRef,
65 private route: ActivatedRoute,
66 private router: Router,
67 private videoService: VideoService,
68 private videoBlacklistService: VideoBlacklistService,
69 private confirmService: ConfirmService,
70 private metaService: MetaService,
71 private authService: AuthService,
72 private serverService: ServerService,
73 private restExtractor: RestExtractor,
74 private notificationsService: NotificationsService,
75 private markdownService: MarkdownService,
77 private redirectService: RedirectService,
79 @Inject(LOCALE_ID) private localeId: string
83 return this.authService.getUser()
88 WebTorrent.WEBRTC_SUPPORT === false ||
89 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
91 this.hasAlreadyAcceptedPrivacyConcern = true
94 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
97 this.otherVideos = data.videos
98 this.updateOtherVideosDisplayed()
101 err => console.error(err)
104 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
116 .pipe(catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ])))
119 const startTime = this.route.snapshot.queryParams.start
120 this.onVideoFetched(video, startTime)
121 .catch(err => this.handleError(err))
125 this.videoNotFound = true
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.join(', ')
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 private updateVideoDescription (description: string) {
289 this.video.description = description
290 this.setVideoDescriptionHTML()
293 private setVideoDescriptionHTML () {
294 if (!this.video.description) {
295 this.videoHTMLDescription = ''
299 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
302 private setVideoLikesBarTooltipText () {
303 this.likesBarTooltipText = this.i18n(
304 '{{likesNumber}} likes / {{dislikesNumber}} dislikes',
305 { likesNumber: this.video.likes, dislikes: this.video.dislikes }
309 private handleError (err: any) {
310 const errorMessage: string = typeof err === 'string' ? err : err.message
311 if (!errorMessage) return
315 if (errorMessage.indexOf('http error') !== -1) {
316 message = this.i18n('Cannot fetch video from server, maybe down.')
318 message = errorMessage
321 this.notificationsService.error(this.i18n('Error'), message)
324 private checkUserRating () {
325 // Unlogged users do not have ratings
326 if (this.isUserLoggedIn() === false) return
328 this.videoService.getUserVideoRating(this.video.id)
332 this.userRating = ratingObject.rating
336 err => this.notificationsService.error(this.i18n('Error'), err.message)
340 private async onVideoFetched (video: VideoDetails, startTime = 0) {
343 // Re init attributes
344 this.descriptionLoading = false
345 this.completeDescriptionShown = false
347 this.updateOtherVideosDisplayed()
349 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
350 const res = await this.confirmService.confirm(
351 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
352 this.i18n('Mature or explicit content')
354 if (res === false) return this.redirectService.redirectToHomepage()
357 // Flush old player if needed
360 // Build video element, because videojs remove it on dispose
361 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
362 this.playerElement = document.createElement('video')
363 this.playerElement.className = 'video-js vjs-peertube-skin'
364 this.playerElement.setAttribute('playsinline', 'true')
365 playerElementWrapper.appendChild(this.playerElement)
367 const videojsOptions = getVideojsOptions({
368 autoplay: this.isAutoplay(),
369 inactivityTimeout: 2500,
370 videoFiles: this.video.files,
371 playerElement: this.playerElement,
372 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
373 videoDuration: this.video.duration,
376 poster: this.video.previewUrl,
380 if (this.videojsLocaleLoaded === false) {
381 await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
382 this.videojsLocaleLoaded = true
386 this.zone.runOutsideAngular(async () => {
387 videojs(this.playerElement, videojsOptions, function () {
389 this.on('customError', (event, data) => self.handleError(data.err))
391 addContextMenu(self.player, self.video.embedUrl)
395 this.setVideoDescriptionHTML()
396 this.setVideoLikesBarTooltipText()
398 this.setOpenGraphTags()
399 this.checkUserRating()
402 private setRating (nextRating) {
404 switch (nextRating) {
406 method = this.videoService.setVideoLike
409 method = this.videoService.setVideoDislike
412 method = this.videoService.unsetVideoLike
416 method.call(this.videoService, this.video.id)
419 // Update the video like attribute
420 this.updateVideoRating(this.userRating, nextRating)
421 this.userRating = nextRating
423 err => this.notificationsService.error(this.i18n('Error'), err.message)
427 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
428 let likesToIncrement = 0
429 let dislikesToIncrement = 0
432 if (oldRating === 'like') likesToIncrement--
433 if (oldRating === 'dislike') dislikesToIncrement--
436 if (newRating === 'like') likesToIncrement++
437 if (newRating === 'dislike') dislikesToIncrement++
439 this.video.likes += likesToIncrement
440 this.video.dislikes += dislikesToIncrement
442 this.video.buildLikeAndDislikePercents()
443 this.setVideoLikesBarTooltipText()
446 private updateOtherVideosDisplayed () {
447 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
448 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
452 private setOpenGraphTags () {
453 this.metaService.setTitle(this.video.name)
455 this.metaService.setTag('og:type', 'video')
457 this.metaService.setTag('og:title', this.video.name)
458 this.metaService.setTag('name', this.video.name)
460 this.metaService.setTag('og:description', this.video.description)
461 this.metaService.setTag('description', this.video.description)
463 this.metaService.setTag('og:image', this.video.previewPath)
465 this.metaService.setTag('og:duration', this.video.duration.toString())
467 this.metaService.setTag('og:site_name', 'PeerTube')
469 this.metaService.setTag('og:url', window.location.href)
470 this.metaService.setTag('url', window.location.href)
473 private isAutoplay () {
475 if (!this.user) return true
477 // Be sure the autoPlay is set to false
478 return this.user.autoPlayVideo !== false
481 private flushPlayer () {
482 // Remove player if it exists
484 this.player.dispose()
485 this.player = undefined