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[] = []
44 player: videojs.Player
45 playerElement: HTMLVideoElement
46 userRating: UserVideoRateType = null
47 video: VideoDetails = null
49 descriptionLoading = false
51 completeDescriptionShown = false
52 completeVideoDescription: string
53 shortVideoDescription: string
54 videoHTMLDescription = ''
55 likesBarTooltipText = ''
56 hasAlreadyAcceptedPrivacyConcern = false
58 private otherVideos: Video[] = []
59 private paramsSub: Subscription
62 private elementRef: ElementRef,
63 private route: ActivatedRoute,
64 private router: Router,
65 private videoService: VideoService,
66 private videoBlacklistService: VideoBlacklistService,
67 private confirmService: ConfirmService,
68 private metaService: MetaService,
69 private authService: AuthService,
70 private serverService: ServerService,
71 private notificationsService: NotificationsService,
72 private markdownService: MarkdownService,
74 private redirectService: RedirectService
78 return this.authService.getUser()
83 WebTorrent.WEBRTC_SUPPORT === false ||
84 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
86 this.hasAlreadyAcceptedPrivacyConcern = true
89 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
92 this.otherVideos = data.videos
93 this.updateOtherVideosDisplayed()
96 err => console.error(err)
99 this.paramsSub = this.route.params.subscribe(routeParams => {
104 const uuid = routeParams['uuid']
105 // Video did not change
106 if (this.video && this.video.uuid === uuid) return
108 this.videoService.getVideo(uuid).subscribe(
110 const startTime = this.route.snapshot.queryParams.start
111 this.onVideoFetched(video, startTime)
112 .catch(err => this.handleError(err))
113 this.generateSyndicationList()
117 this.videoNotFound = true
127 // Unsubscribe subscriptions
128 this.paramsSub.unsubscribe()
132 if (this.isUserLoggedIn() === false) return
133 if (this.userRating === 'like') {
134 // Already liked this video
135 this.setRating('none')
137 this.setRating('like')
142 if (this.isUserLoggedIn() === false) return
143 if (this.userRating === 'dislike') {
144 // Already disliked this video
145 this.setRating('none')
147 this.setRating('dislike')
151 async blacklistVideo (event: Event) {
152 event.preventDefault()
154 const res = await this.confirmService.confirm('Do you really want to blacklist this video?', 'Blacklist')
155 if (res === false) return
157 this.videoBlacklistService.blacklistVideo(this.video.id)
160 this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
161 this.redirectService.redirectToHomepage()
164 error => this.notificationsService.error('Error', error.message)
168 showMoreDescription () {
169 if (this.completeVideoDescription === undefined) {
170 return this.loadCompleteDescription()
173 this.updateVideoDescription(this.completeVideoDescription)
174 this.completeDescriptionShown = true
177 showLessDescription () {
178 this.updateVideoDescription(this.shortVideoDescription)
179 this.completeDescriptionShown = false
182 loadCompleteDescription () {
183 this.descriptionLoading = true
185 this.videoService.loadCompleteDescription(this.video.descriptionPath)
188 this.completeDescriptionShown = true
189 this.descriptionLoading = false
191 this.shortVideoDescription = this.video.description
192 this.completeVideoDescription = description
194 this.updateVideoDescription(this.completeVideoDescription)
198 this.descriptionLoading = false
199 this.notificationsService.error('Error', error.message)
204 showReportModal (event: Event) {
205 event.preventDefault()
206 this.videoReportModal.show()
209 showSupportModal () {
210 this.videoSupportModal.show()
214 this.videoShareModal.show()
217 showDownloadModal (event: Event) {
218 event.preventDefault()
219 this.videoDownloadModal.show()
223 return this.authService.isLoggedIn()
226 isVideoUpdatable () {
227 return this.video.isUpdatableBy(this.authService.getUser())
230 isVideoBlacklistable () {
231 return this.video.isBlackistableBy(this.user)
235 return Account.GET_ACCOUNT_AVATAR_URL(this.video.account)
239 if (!this.video) return ''
241 return this.video.previewUrl
245 if (!this.video || Array.isArray(this.video.tags) === false) return []
247 return this.video.tags.join(', ')
250 generateSyndicationList () {
251 this.syndicationItems = this.videoService.getAccountFeedUrls(this.video.account.id)
254 isVideoRemovable () {
255 return this.video.isRemovableBy(this.authService.getUser())
258 async removeVideo (event: Event) {
259 event.preventDefault()
261 const res = await this.confirmService.confirm('Do you really want to delete this video?', 'Delete')
262 if (res === false) return
264 this.videoService.removeVideo(this.video.id)
267 this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
269 // Go back to the video-list.
270 this.redirectService.redirectToHomepage()
273 error => this.notificationsService.error('Error', error.message)
277 acceptedPrivacyConcern () {
278 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
279 this.hasAlreadyAcceptedPrivacyConcern = true
282 private updateVideoDescription (description: string) {
283 this.video.description = description
284 this.setVideoDescriptionHTML()
287 private setVideoDescriptionHTML () {
288 if (!this.video.description) {
289 this.videoHTMLDescription = ''
293 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
296 private setVideoLikesBarTooltipText () {
297 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
300 private handleError (err: any) {
301 const errorMessage: string = typeof err === 'string' ? err : err.message
302 if (!errorMessage) return
306 if (errorMessage.indexOf('http error') !== -1) {
307 message = 'Cannot fetch video from server, maybe down.'
309 message = errorMessage
312 this.notificationsService.error('Error', message)
315 private checkUserRating () {
316 // Unlogged users do not have ratings
317 if (this.isUserLoggedIn() === false) return
319 this.videoService.getUserVideoRating(this.video.id)
323 this.userRating = ratingObject.rating
327 err => this.notificationsService.error('Error', err.message)
331 private async onVideoFetched (video: VideoDetails, startTime = 0) {
334 // Re init attributes
335 this.descriptionLoading = false
336 this.completeDescriptionShown = false
338 this.updateOtherVideosDisplayed()
340 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
341 const res = await this.confirmService.confirm(
342 'This video contains mature or explicit content. Are you sure you want to watch it?',
343 'Mature or explicit content'
345 if (res === false) return this.redirectService.redirectToHomepage()
348 // Flush old player if needed
351 // Build video element, because videojs remove it on dispose
352 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
353 this.playerElement = document.createElement('video')
354 this.playerElement.className = 'video-js vjs-peertube-skin'
355 playerElementWrapper.appendChild(this.playerElement)
357 const videojsOptions = getVideojsOptions({
358 autoplay: this.isAutoplay(),
359 inactivityTimeout: 2500,
360 videoFiles: this.video.files,
361 playerElement: this.playerElement,
362 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
363 videoDuration: this.video.duration,
366 poster: this.video.previewUrl,
371 this.zone.runOutsideAngular(() => {
372 videojs(this.playerElement, videojsOptions, function () {
374 this.on('customError', (event, data) => self.handleError(data.err))
378 this.setVideoDescriptionHTML()
379 this.setVideoLikesBarTooltipText()
381 this.setOpenGraphTags()
382 this.checkUserRating()
385 private setRating (nextRating) {
387 switch (nextRating) {
389 method = this.videoService.setVideoLike
392 method = this.videoService.setVideoDislike
395 method = this.videoService.unsetVideoLike
399 method.call(this.videoService, this.video.id)
402 // Update the video like attribute
403 this.updateVideoRating(this.userRating, nextRating)
404 this.userRating = nextRating
406 err => this.notificationsService.error('Error', err.message)
410 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
411 let likesToIncrement = 0
412 let dislikesToIncrement = 0
415 if (oldRating === 'like') likesToIncrement--
416 if (oldRating === 'dislike') dislikesToIncrement--
419 if (newRating === 'like') likesToIncrement++
420 if (newRating === 'dislike') dislikesToIncrement++
422 this.video.likes += likesToIncrement
423 this.video.dislikes += dislikesToIncrement
425 this.video.buildLikeAndDislikePercents()
426 this.setVideoLikesBarTooltipText()
429 private updateOtherVideosDisplayed () {
430 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
431 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
435 private setOpenGraphTags () {
436 this.metaService.setTitle(this.video.name)
438 this.metaService.setTag('og:type', 'video')
440 this.metaService.setTag('og:title', this.video.name)
441 this.metaService.setTag('name', this.video.name)
443 this.metaService.setTag('og:description', this.video.description)
444 this.metaService.setTag('description', this.video.description)
446 this.metaService.setTag('og:image', this.video.previewPath)
448 this.metaService.setTag('og:duration', this.video.duration.toString())
450 this.metaService.setTag('og:site_name', 'PeerTube')
452 this.metaService.setTag('og:url', window.location.href)
453 this.metaService.setTag('url', window.location.href)
456 private isAutoplay () {
458 if (!this.user) return true
460 // Be sure the autoPlay is set to false
461 return this.user.autoPlayVideo !== false
464 private flushPlayer () {
465 // Remove player if it exists
467 this.player.dispose()
468 this.player = undefined