1 import { catchError } from 'rxjs/operators'
2 import { Component, ElementRef, 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 { 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 } from '../../../assets/player/peertube-player'
25 import { ServerService } from '@app/core'
28 selector: 'my-video-watch',
29 templateUrl: './video-watch.component.html',
30 styleUrls: [ './video-watch.component.scss' ]
32 export class VideoWatchComponent implements OnInit, OnDestroy {
33 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
35 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
36 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
37 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
38 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
40 otherVideosDisplayed: Video[] = []
42 player: videojs.Player
43 playerElement: HTMLVideoElement
44 userRating: UserVideoRateType = null
45 video: VideoDetails = null
47 descriptionLoading = false
49 completeDescriptionShown = false
50 completeVideoDescription: string
51 shortVideoDescription: string
52 videoHTMLDescription = ''
53 likesBarTooltipText = ''
54 hasAlreadyAcceptedPrivacyConcern = false
56 private otherVideos: Video[] = []
57 private paramsSub: Subscription
60 private elementRef: ElementRef,
61 private route: ActivatedRoute,
62 private router: Router,
63 private videoService: VideoService,
64 private videoBlacklistService: VideoBlacklistService,
65 private confirmService: ConfirmService,
66 private metaService: MetaService,
67 private authService: AuthService,
68 private serverService: ServerService,
69 private restExtractor: RestExtractor,
70 private notificationsService: NotificationsService,
71 private markdownService: MarkdownService,
73 private redirectService: RedirectService
77 return this.authService.getUser()
82 WebTorrent.WEBRTC_SUPPORT === false ||
83 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
85 this.hasAlreadyAcceptedPrivacyConcern = true
88 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
91 this.otherVideos = data.videos
92 this.updateOtherVideosDisplayed()
95 err => console.error(err)
98 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
110 .pipe(catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ])))
113 const startTime = this.route.snapshot.queryParams.start
114 this.onVideoFetched(video, startTime)
115 .catch(err => this.handleError(err))
119 this.videoNotFound = true
129 // Unsubscribe subscriptions
130 this.paramsSub.unsubscribe()
134 if (this.isUserLoggedIn() === false) return
135 if (this.userRating === 'like') {
136 // Already liked this video
137 this.setRating('none')
139 this.setRating('like')
144 if (this.isUserLoggedIn() === false) return
145 if (this.userRating === 'dislike') {
146 // Already disliked this video
147 this.setRating('none')
149 this.setRating('dislike')
153 async blacklistVideo (event: Event) {
154 event.preventDefault()
156 const res = await this.confirmService.confirm('Do you really want to blacklist this video?', 'Blacklist')
157 if (res === false) return
159 this.videoBlacklistService.blacklistVideo(this.video.id)
162 this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
163 this.redirectService.redirectToHomepage()
166 error => this.notificationsService.error('Error', error.message)
170 showMoreDescription () {
171 if (this.completeVideoDescription === undefined) {
172 return this.loadCompleteDescription()
175 this.updateVideoDescription(this.completeVideoDescription)
176 this.completeDescriptionShown = true
179 showLessDescription () {
180 this.updateVideoDescription(this.shortVideoDescription)
181 this.completeDescriptionShown = false
184 loadCompleteDescription () {
185 this.descriptionLoading = true
187 this.videoService.loadCompleteDescription(this.video.descriptionPath)
190 this.completeDescriptionShown = true
191 this.descriptionLoading = false
193 this.shortVideoDescription = this.video.description
194 this.completeVideoDescription = description
196 this.updateVideoDescription(this.completeVideoDescription)
200 this.descriptionLoading = false
201 this.notificationsService.error('Error', error.message)
206 showReportModal (event: Event) {
207 event.preventDefault()
208 this.videoReportModal.show()
211 showSupportModal () {
212 this.videoSupportModal.show()
216 this.videoShareModal.show()
219 showDownloadModal (event: Event) {
220 event.preventDefault()
221 this.videoDownloadModal.show()
225 return this.authService.isLoggedIn()
228 isVideoUpdatable () {
229 return this.video.isUpdatableBy(this.authService.getUser())
232 isVideoBlacklistable () {
233 return this.video.isBlackistableBy(this.user)
237 if (!this.video) return ''
239 return this.video.previewUrl
243 if (!this.video || Array.isArray(this.video.tags) === false) return []
245 return this.video.tags.join(', ')
248 isVideoRemovable () {
249 return this.video.isRemovableBy(this.authService.getUser())
252 async removeVideo (event: Event) {
253 event.preventDefault()
255 const res = await this.confirmService.confirm('Do you really want to delete this video?', 'Delete')
256 if (res === false) return
258 this.videoService.removeVideo(this.video.id)
261 this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
263 // Go back to the video-list.
264 this.redirectService.redirectToHomepage()
267 error => this.notificationsService.error('Error', error.message)
271 acceptedPrivacyConcern () {
272 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
273 this.hasAlreadyAcceptedPrivacyConcern = true
276 private updateVideoDescription (description: string) {
277 this.video.description = description
278 this.setVideoDescriptionHTML()
281 private setVideoDescriptionHTML () {
282 if (!this.video.description) {
283 this.videoHTMLDescription = ''
287 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
290 private setVideoLikesBarTooltipText () {
291 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
294 private handleError (err: any) {
295 const errorMessage: string = typeof err === 'string' ? err : err.message
296 if (!errorMessage) return
300 if (errorMessage.indexOf('http error') !== -1) {
301 message = 'Cannot fetch video from server, maybe down.'
303 message = errorMessage
306 this.notificationsService.error('Error', message)
309 private checkUserRating () {
310 // Unlogged users do not have ratings
311 if (this.isUserLoggedIn() === false) return
313 this.videoService.getUserVideoRating(this.video.id)
317 this.userRating = ratingObject.rating
321 err => this.notificationsService.error('Error', err.message)
325 private async onVideoFetched (video: VideoDetails, startTime = 0) {
328 // Re init attributes
329 this.descriptionLoading = false
330 this.completeDescriptionShown = false
332 this.updateOtherVideosDisplayed()
334 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
335 const res = await this.confirmService.confirm(
336 'This video contains mature or explicit content. Are you sure you want to watch it?',
337 'Mature or explicit content'
339 if (res === false) return this.redirectService.redirectToHomepage()
342 // Flush old player if needed
345 // Build video element, because videojs remove it on dispose
346 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
347 this.playerElement = document.createElement('video')
348 this.playerElement.className = 'video-js vjs-peertube-skin'
349 this.playerElement.setAttribute('playsinline', 'true')
350 playerElementWrapper.appendChild(this.playerElement)
352 const videojsOptions = getVideojsOptions({
353 autoplay: this.isAutoplay(),
354 inactivityTimeout: 2500,
355 videoFiles: this.video.files,
356 playerElement: this.playerElement,
357 videoEmbedUrl: this.video.embedUrl,
358 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
359 videoDuration: this.video.duration,
362 poster: this.video.previewUrl,
367 this.zone.runOutsideAngular(() => {
368 videojs(this.playerElement, videojsOptions, function () {
370 this.on('customError', (event, data) => self.handleError(data.err))
374 this.setVideoDescriptionHTML()
375 this.setVideoLikesBarTooltipText()
377 this.setOpenGraphTags()
378 this.checkUserRating()
381 private setRating (nextRating) {
383 switch (nextRating) {
385 method = this.videoService.setVideoLike
388 method = this.videoService.setVideoDislike
391 method = this.videoService.unsetVideoLike
395 method.call(this.videoService, this.video.id)
398 // Update the video like attribute
399 this.updateVideoRating(this.userRating, nextRating)
400 this.userRating = nextRating
402 err => this.notificationsService.error('Error', err.message)
406 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
407 let likesToIncrement = 0
408 let dislikesToIncrement = 0
411 if (oldRating === 'like') likesToIncrement--
412 if (oldRating === 'dislike') dislikesToIncrement--
415 if (newRating === 'like') likesToIncrement++
416 if (newRating === 'dislike') dislikesToIncrement++
418 this.video.likes += likesToIncrement
419 this.video.dislikes += dislikesToIncrement
421 this.video.buildLikeAndDislikePercents()
422 this.setVideoLikesBarTooltipText()
425 private updateOtherVideosDisplayed () {
426 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
427 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
431 private setOpenGraphTags () {
432 this.metaService.setTitle(this.video.name)
434 this.metaService.setTag('og:type', 'video')
436 this.metaService.setTag('og:title', this.video.name)
437 this.metaService.setTag('name', this.video.name)
439 this.metaService.setTag('og:description', this.video.description)
440 this.metaService.setTag('description', this.video.description)
442 this.metaService.setTag('og:image', this.video.previewPath)
444 this.metaService.setTag('og:duration', this.video.duration.toString())
446 this.metaService.setTag('og:site_name', 'PeerTube')
448 this.metaService.setTag('og:url', window.location.href)
449 this.metaService.setTag('url', window.location.href)
452 private isAutoplay () {
454 if (!this.user) return true
456 // Be sure the autoPlay is set to false
457 return this.user.autoPlayVideo !== false
460 private flushPlayer () {
461 // Remove player if it exists
463 this.player.dispose()
464 this.player = undefined