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'
26 import { I18n } from '@ngx-translate/i18n-polyfill'
29 selector: 'my-video-watch',
30 templateUrl: './video-watch.component.html',
31 styleUrls: [ './video-watch.component.scss' ]
33 export class VideoWatchComponent implements OnInit, OnDestroy {
34 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
36 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
37 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
38 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
39 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
41 otherVideosDisplayed: Video[] = []
43 player: videojs.Player
44 playerElement: HTMLVideoElement
45 userRating: UserVideoRateType = null
46 video: VideoDetails = null
48 descriptionLoading = false
50 completeDescriptionShown = false
51 completeVideoDescription: string
52 shortVideoDescription: string
53 videoHTMLDescription = ''
54 likesBarTooltipText = ''
55 hasAlreadyAcceptedPrivacyConcern = false
57 private otherVideos: Video[] = []
58 private paramsSub: Subscription
61 private elementRef: ElementRef,
62 private route: ActivatedRoute,
63 private router: Router,
64 private videoService: VideoService,
65 private videoBlacklistService: VideoBlacklistService,
66 private confirmService: ConfirmService,
67 private metaService: MetaService,
68 private authService: AuthService,
69 private serverService: ServerService,
70 private restExtractor: RestExtractor,
71 private notificationsService: NotificationsService,
72 private markdownService: MarkdownService,
74 private redirectService: RedirectService,
79 return this.authService.getUser()
84 WebTorrent.WEBRTC_SUPPORT === false ||
85 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
87 this.hasAlreadyAcceptedPrivacyConcern = true
90 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
93 this.otherVideos = data.videos
94 this.updateOtherVideosDisplayed()
97 err => console.error(err)
100 this.paramsSub = this.route.params.subscribe(routeParams => {
105 const uuid = routeParams['uuid']
107 // Video did not change
108 if (this.video && this.video.uuid === uuid) return
112 .pipe(catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ])))
115 const startTime = this.route.snapshot.queryParams.start
116 this.onVideoFetched(video, startTime)
117 .catch(err => this.handleError(err))
121 this.videoNotFound = true
131 // Unsubscribe subscriptions
132 this.paramsSub.unsubscribe()
136 if (this.isUserLoggedIn() === false) return
137 if (this.userRating === 'like') {
138 // Already liked this video
139 this.setRating('none')
141 this.setRating('like')
146 if (this.isUserLoggedIn() === false) return
147 if (this.userRating === 'dislike') {
148 // Already disliked this video
149 this.setRating('none')
151 this.setRating('dislike')
155 async blacklistVideo (event: Event) {
156 event.preventDefault()
158 const res = await this.confirmService.confirm(this.i18n('Do you really want to blacklist this video?'), this.i18n('Blacklist'))
159 if (res === false) return
161 this.videoBlacklistService.blacklistVideo(this.video.id)
164 this.notificationsService.success(
165 this.i18n('Success'),
166 this.i18n('Video {{videoName}} had been blacklisted.', { videoName: this.video.name })
168 this.redirectService.redirectToHomepage()
171 error => this.notificationsService.error(this.i18n('Error'), error.message)
175 showMoreDescription () {
176 if (this.completeVideoDescription === undefined) {
177 return this.loadCompleteDescription()
180 this.updateVideoDescription(this.completeVideoDescription)
181 this.completeDescriptionShown = true
184 showLessDescription () {
185 this.updateVideoDescription(this.shortVideoDescription)
186 this.completeDescriptionShown = false
189 loadCompleteDescription () {
190 this.descriptionLoading = true
192 this.videoService.loadCompleteDescription(this.video.descriptionPath)
195 this.completeDescriptionShown = true
196 this.descriptionLoading = false
198 this.shortVideoDescription = this.video.description
199 this.completeVideoDescription = description
201 this.updateVideoDescription(this.completeVideoDescription)
205 this.descriptionLoading = false
206 this.notificationsService.error(this.i18n('Error'), error.message)
211 showReportModal (event: Event) {
212 event.preventDefault()
213 this.videoReportModal.show()
216 showSupportModal () {
217 this.videoSupportModal.show()
221 this.videoShareModal.show()
224 showDownloadModal (event: Event) {
225 event.preventDefault()
226 this.videoDownloadModal.show()
230 return this.authService.isLoggedIn()
233 isVideoUpdatable () {
234 return this.video.isUpdatableBy(this.authService.getUser())
237 isVideoBlacklistable () {
238 return this.video.isBlackistableBy(this.user)
242 if (!this.video) return ''
244 return this.video.previewUrl
248 if (!this.video || Array.isArray(this.video.tags) === false) return []
250 return this.video.tags.join(', ')
253 isVideoRemovable () {
254 return this.video.isRemovableBy(this.authService.getUser())
257 async removeVideo (event: Event) {
258 event.preventDefault()
260 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
261 if (res === false) return
263 this.videoService.removeVideo(this.video.id)
266 this.notificationsService.success(
267 this.i18n('Success'),
268 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
271 // Go back to the video-list.
272 this.redirectService.redirectToHomepage()
275 error => this.notificationsService.error(this.i18n('Error'), error.message)
279 acceptedPrivacyConcern () {
280 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
281 this.hasAlreadyAcceptedPrivacyConcern = true
284 private updateVideoDescription (description: string) {
285 this.video.description = description
286 this.setVideoDescriptionHTML()
289 private setVideoDescriptionHTML () {
290 if (!this.video.description) {
291 this.videoHTMLDescription = ''
295 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
298 private setVideoLikesBarTooltipText () {
299 this.likesBarTooltipText = this.i18n(
300 '{{likesNumber}} likes / {{dislikesNumber}} dislikes',
301 { likesNumber: this.video.likes, dislikes: this.video.dislikes }
305 private handleError (err: any) {
306 const errorMessage: string = typeof err === 'string' ? err : err.message
307 if (!errorMessage) return
311 if (errorMessage.indexOf('http error') !== -1) {
312 message = this.i18n('Cannot fetch video from server, maybe down.')
314 message = errorMessage
317 this.notificationsService.error(this.i18n('Error'), message)
320 private checkUserRating () {
321 // Unlogged users do not have ratings
322 if (this.isUserLoggedIn() === false) return
324 this.videoService.getUserVideoRating(this.video.id)
328 this.userRating = ratingObject.rating
332 err => this.notificationsService.error(this.i18n('Error'), err.message)
336 private async onVideoFetched (video: VideoDetails, startTime = 0) {
339 // Re init attributes
340 this.descriptionLoading = false
341 this.completeDescriptionShown = false
343 this.updateOtherVideosDisplayed()
345 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
346 const res = await this.confirmService.confirm(
347 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
348 this.i18n('Mature or explicit content')
350 if (res === false) return this.redirectService.redirectToHomepage()
353 // Flush old player if needed
356 // Build video element, because videojs remove it on dispose
357 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
358 this.playerElement = document.createElement('video')
359 this.playerElement.className = 'video-js vjs-peertube-skin'
360 this.playerElement.setAttribute('playsinline', 'true')
361 playerElementWrapper.appendChild(this.playerElement)
363 const videojsOptions = getVideojsOptions({
364 autoplay: this.isAutoplay(),
365 inactivityTimeout: 2500,
366 videoFiles: this.video.files,
367 playerElement: this.playerElement,
368 videoEmbedUrl: this.video.embedUrl,
369 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
370 videoDuration: this.video.duration,
373 poster: this.video.previewUrl,
378 this.zone.runOutsideAngular(() => {
379 videojs(this.playerElement, videojsOptions, function () {
381 this.on('customError', (event, data) => self.handleError(data.err))
385 this.setVideoDescriptionHTML()
386 this.setVideoLikesBarTooltipText()
388 this.setOpenGraphTags()
389 this.checkUserRating()
392 private setRating (nextRating) {
394 switch (nextRating) {
396 method = this.videoService.setVideoLike
399 method = this.videoService.setVideoDislike
402 method = this.videoService.unsetVideoLike
406 method.call(this.videoService, this.video.id)
409 // Update the video like attribute
410 this.updateVideoRating(this.userRating, nextRating)
411 this.userRating = nextRating
413 err => this.notificationsService.error(this.i18n('Error'), err.message)
417 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
418 let likesToIncrement = 0
419 let dislikesToIncrement = 0
422 if (oldRating === 'like') likesToIncrement--
423 if (oldRating === 'dislike') dislikesToIncrement--
426 if (newRating === 'like') likesToIncrement++
427 if (newRating === 'dislike') dislikesToIncrement++
429 this.video.likes += likesToIncrement
430 this.video.dislikes += dislikesToIncrement
432 this.video.buildLikeAndDislikePercents()
433 this.setVideoLikesBarTooltipText()
436 private updateOtherVideosDisplayed () {
437 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
438 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
442 private setOpenGraphTags () {
443 this.metaService.setTitle(this.video.name)
445 this.metaService.setTag('og:type', 'video')
447 this.metaService.setTag('og:title', this.video.name)
448 this.metaService.setTag('name', this.video.name)
450 this.metaService.setTag('og:description', this.video.description)
451 this.metaService.setTag('description', this.video.description)
453 this.metaService.setTag('og:image', this.video.previewPath)
455 this.metaService.setTag('og:duration', this.video.duration.toString())
457 this.metaService.setTag('og:site_name', 'PeerTube')
459 this.metaService.setTag('og:url', window.location.href)
460 this.metaService.setTag('url', window.location.href)
463 private isAutoplay () {
465 if (!this.user) return true
467 // Be sure the autoPlay is set to false
468 return this.user.autoPlayVideo !== false
471 private flushPlayer () {
472 // Remove player if it exists
474 this.player.dispose()
475 this.player = undefined