1 import { Component, ElementRef, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
2 import { ActivatedRoute, Router } from '@angular/router'
3 import { RedirectService } from '@app/core/routing/redirect.service'
4 import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
5 import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
6 import { MetaService } from '@ngx-meta/core'
7 import { NotificationsService } from 'angular2-notifications'
8 import { Subscription } from 'rxjs/Subscription'
9 import * as videojs from 'video.js'
10 import 'videojs-hotkeys'
11 import * as WebTorrent from 'webtorrent'
12 import { UserVideoRateType, VideoRateType } from '../../../../../shared'
13 import '../../../assets/player/peertube-videojs-plugin'
14 import { AuthService, ConfirmService } from '../../core'
15 import { VideoBlacklistService } from '../../shared'
16 import { Account } from '../../shared/account/account.model'
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 notificationsService: NotificationsService,
70 private markdownService: MarkdownService,
72 private redirectService: RedirectService
76 return this.authService.getUser()
81 WebTorrent.WEBRTC_SUPPORT === false ||
82 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
84 this.hasAlreadyAcceptedPrivacyConcern = true
87 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
90 this.otherVideos = data.videos
91 this.updateOtherVideosDisplayed()
94 err => console.error(err)
97 this.paramsSub = this.route.params.subscribe(routeParams => {
102 const uuid = routeParams['uuid']
103 // Video did not change
104 if (this.video && this.video.uuid === uuid) return
106 this.videoService.getVideo(uuid).subscribe(
108 const startTime = this.route.snapshot.queryParams.start
109 this.onVideoFetched(video, startTime)
110 .catch(err => this.handleError(err))
114 this.videoNotFound = true
124 // Unsubscribe subscriptions
125 this.paramsSub.unsubscribe()
129 if (this.isUserLoggedIn() === false) return
130 if (this.userRating === 'like') {
131 // Already liked this video
132 this.setRating('none')
134 this.setRating('like')
139 if (this.isUserLoggedIn() === false) return
140 if (this.userRating === 'dislike') {
141 // Already disliked this video
142 this.setRating('none')
144 this.setRating('dislike')
148 async blacklistVideo (event: Event) {
149 event.preventDefault()
151 const res = await this.confirmService.confirm('Do you really want to blacklist this video?', 'Blacklist')
152 if (res === false) return
154 this.videoBlacklistService.blacklistVideo(this.video.id)
157 this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
158 this.redirectService.redirectToHomepage()
161 error => this.notificationsService.error('Error', error.message)
165 showMoreDescription () {
166 if (this.completeVideoDescription === undefined) {
167 return this.loadCompleteDescription()
170 this.updateVideoDescription(this.completeVideoDescription)
171 this.completeDescriptionShown = true
174 showLessDescription () {
175 this.updateVideoDescription(this.shortVideoDescription)
176 this.completeDescriptionShown = false
179 loadCompleteDescription () {
180 this.descriptionLoading = true
182 this.videoService.loadCompleteDescription(this.video.descriptionPath)
185 this.completeDescriptionShown = true
186 this.descriptionLoading = false
188 this.shortVideoDescription = this.video.description
189 this.completeVideoDescription = description
191 this.updateVideoDescription(this.completeVideoDescription)
195 this.descriptionLoading = false
196 this.notificationsService.error('Error', error.message)
201 showReportModal (event: Event) {
202 event.preventDefault()
203 this.videoReportModal.show()
206 showSupportModal () {
207 this.videoSupportModal.show()
211 this.videoShareModal.show()
214 showDownloadModal (event: Event) {
215 event.preventDefault()
216 this.videoDownloadModal.show()
220 return this.authService.isLoggedIn()
223 isVideoUpdatable () {
224 return this.video.isUpdatableBy(this.authService.getUser())
227 isVideoBlacklistable () {
228 return this.video.isBlackistableBy(this.user)
232 if (!this.video) return ''
234 return this.video.previewUrl
238 if (!this.video || Array.isArray(this.video.tags) === false) return []
240 return this.video.tags.join(', ')
243 isVideoRemovable () {
244 return this.video.isRemovableBy(this.authService.getUser())
247 async removeVideo (event: Event) {
248 event.preventDefault()
250 const res = await this.confirmService.confirm('Do you really want to delete this video?', 'Delete')
251 if (res === false) return
253 this.videoService.removeVideo(this.video.id)
256 this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
258 // Go back to the video-list.
259 this.redirectService.redirectToHomepage()
262 error => this.notificationsService.error('Error', error.message)
266 acceptedPrivacyConcern () {
267 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
268 this.hasAlreadyAcceptedPrivacyConcern = true
271 private updateVideoDescription (description: string) {
272 this.video.description = description
273 this.setVideoDescriptionHTML()
276 private setVideoDescriptionHTML () {
277 if (!this.video.description) {
278 this.videoHTMLDescription = ''
282 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
285 private setVideoLikesBarTooltipText () {
286 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
289 private handleError (err: any) {
290 const errorMessage: string = typeof err === 'string' ? err : err.message
291 if (!errorMessage) return
295 if (errorMessage.indexOf('http error') !== -1) {
296 message = 'Cannot fetch video from server, maybe down.'
298 message = errorMessage
301 this.notificationsService.error('Error', message)
304 private checkUserRating () {
305 // Unlogged users do not have ratings
306 if (this.isUserLoggedIn() === false) return
308 this.videoService.getUserVideoRating(this.video.id)
312 this.userRating = ratingObject.rating
316 err => this.notificationsService.error('Error', err.message)
320 private async onVideoFetched (video: VideoDetails, startTime = 0) {
323 // Re init attributes
324 this.descriptionLoading = false
325 this.completeDescriptionShown = false
327 this.updateOtherVideosDisplayed()
329 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
330 const res = await this.confirmService.confirm(
331 'This video contains mature or explicit content. Are you sure you want to watch it?',
332 'Mature or explicit content'
334 if (res === false) return this.redirectService.redirectToHomepage()
337 // Flush old player if needed
340 // Build video element, because videojs remove it on dispose
341 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
342 this.playerElement = document.createElement('video')
343 this.playerElement.className = 'video-js vjs-peertube-skin'
344 playerElementWrapper.appendChild(this.playerElement)
346 const videojsOptions = getVideojsOptions({
347 autoplay: this.isAutoplay(),
348 inactivityTimeout: 2500,
349 videoFiles: this.video.files,
350 playerElement: this.playerElement,
351 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
352 videoDuration: this.video.duration,
355 poster: this.video.previewUrl,
360 this.zone.runOutsideAngular(() => {
361 videojs(this.playerElement, videojsOptions, function () {
363 this.on('customError', (event, data) => self.handleError(data.err))
367 this.setVideoDescriptionHTML()
368 this.setVideoLikesBarTooltipText()
370 this.setOpenGraphTags()
371 this.checkUserRating()
374 private setRating (nextRating) {
376 switch (nextRating) {
378 method = this.videoService.setVideoLike
381 method = this.videoService.setVideoDislike
384 method = this.videoService.unsetVideoLike
388 method.call(this.videoService, this.video.id)
391 // Update the video like attribute
392 this.updateVideoRating(this.userRating, nextRating)
393 this.userRating = nextRating
395 err => this.notificationsService.error('Error', err.message)
399 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
400 let likesToIncrement = 0
401 let dislikesToIncrement = 0
404 if (oldRating === 'like') likesToIncrement--
405 if (oldRating === 'dislike') dislikesToIncrement--
408 if (newRating === 'like') likesToIncrement++
409 if (newRating === 'dislike') dislikesToIncrement++
411 this.video.likes += likesToIncrement
412 this.video.dislikes += dislikesToIncrement
414 this.video.buildLikeAndDislikePercents()
415 this.setVideoLikesBarTooltipText()
418 private updateOtherVideosDisplayed () {
419 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
420 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
424 private setOpenGraphTags () {
425 this.metaService.setTitle(this.video.name)
427 this.metaService.setTag('og:type', 'video')
429 this.metaService.setTag('og:title', this.video.name)
430 this.metaService.setTag('name', this.video.name)
432 this.metaService.setTag('og:description', this.video.description)
433 this.metaService.setTag('description', this.video.description)
435 this.metaService.setTag('og:image', this.video.previewPath)
437 this.metaService.setTag('og:duration', this.video.duration.toString())
439 this.metaService.setTag('og:site_name', 'PeerTube')
441 this.metaService.setTag('og:url', window.location.href)
442 this.metaService.setTag('url', window.location.href)
445 private isAutoplay () {
447 if (!this.user) return true
449 // Be sure the autoPlay is set to false
450 return this.user.autoPlayVideo !== false
453 private flushPlayer () {
454 // Remove player if it exists
456 this.player.dispose()
457 this.player = undefined