Add ability to choose what policy we have for NSFW videos
[oweals/peertube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
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'
26
27 @Component({
28   selector: 'my-video-watch',
29   templateUrl: './video-watch.component.html',
30   styleUrls: [ './video-watch.component.scss' ]
31 })
32 export class VideoWatchComponent implements OnInit, OnDestroy {
33   private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
34
35   @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
36   @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
37   @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
38   @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
39
40   otherVideosDisplayed: Video[] = []
41
42   syndicationItems = {}
43
44   player: videojs.Player
45   playerElement: HTMLVideoElement
46   userRating: UserVideoRateType = null
47   video: VideoDetails = null
48   videoNotFound = false
49   descriptionLoading = false
50
51   completeDescriptionShown = false
52   completeVideoDescription: string
53   shortVideoDescription: string
54   videoHTMLDescription = ''
55   likesBarTooltipText = ''
56   hasAlreadyAcceptedPrivacyConcern = false
57
58   private otherVideos: Video[] = []
59   private paramsSub: Subscription
60
61   constructor (
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,
73     private zone: NgZone,
74     private redirectService: RedirectService
75   ) {}
76
77   get user () {
78     return this.authService.getUser()
79   }
80
81   ngOnInit () {
82     if (
83       WebTorrent.WEBRTC_SUPPORT === false ||
84       peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
85     ) {
86       this.hasAlreadyAcceptedPrivacyConcern = true
87     }
88
89     this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
90       .subscribe(
91         data => {
92           this.otherVideos = data.videos
93           this.updateOtherVideosDisplayed()
94         },
95
96         err => console.error(err)
97       )
98
99     this.paramsSub = this.route.params.subscribe(routeParams => {
100       if (this.player) {
101         this.player.pause()
102       }
103
104       const uuid = routeParams['uuid']
105       // Video did not change
106       if (this.video && this.video.uuid === uuid) return
107       // Video did change
108       this.videoService.getVideo(uuid).subscribe(
109         video => {
110           const startTime = this.route.snapshot.queryParams.start
111           this.onVideoFetched(video, startTime)
112             .catch(err => this.handleError(err))
113           this.generateSyndicationList()
114         },
115
116         error => {
117           this.videoNotFound = true
118           console.error(error)
119         }
120       )
121     })
122   }
123
124   ngOnDestroy () {
125     this.flushPlayer()
126
127     // Unsubscribe subscriptions
128     this.paramsSub.unsubscribe()
129   }
130
131   setLike () {
132     if (this.isUserLoggedIn() === false) return
133     if (this.userRating === 'like') {
134       // Already liked this video
135       this.setRating('none')
136     } else {
137       this.setRating('like')
138     }
139   }
140
141   setDislike () {
142     if (this.isUserLoggedIn() === false) return
143     if (this.userRating === 'dislike') {
144       // Already disliked this video
145       this.setRating('none')
146     } else {
147       this.setRating('dislike')
148     }
149   }
150
151   async blacklistVideo (event: Event) {
152     event.preventDefault()
153
154     const res = await this.confirmService.confirm('Do you really want to blacklist this video?', 'Blacklist')
155     if (res === false) return
156
157     this.videoBlacklistService.blacklistVideo(this.video.id)
158                               .subscribe(
159                                 status => {
160                                   this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
161                                   this.redirectService.redirectToHomepage()
162                                 },
163
164                                 error => this.notificationsService.error('Error', error.message)
165                               )
166   }
167
168   showMoreDescription () {
169     if (this.completeVideoDescription === undefined) {
170       return this.loadCompleteDescription()
171     }
172
173     this.updateVideoDescription(this.completeVideoDescription)
174     this.completeDescriptionShown = true
175   }
176
177   showLessDescription () {
178     this.updateVideoDescription(this.shortVideoDescription)
179     this.completeDescriptionShown = false
180   }
181
182   loadCompleteDescription () {
183     this.descriptionLoading = true
184
185     this.videoService.loadCompleteDescription(this.video.descriptionPath)
186       .subscribe(
187         description => {
188           this.completeDescriptionShown = true
189           this.descriptionLoading = false
190
191           this.shortVideoDescription = this.video.description
192           this.completeVideoDescription = description
193
194           this.updateVideoDescription(this.completeVideoDescription)
195         },
196
197         error => {
198           this.descriptionLoading = false
199           this.notificationsService.error('Error', error.message)
200         }
201       )
202   }
203
204   showReportModal (event: Event) {
205     event.preventDefault()
206     this.videoReportModal.show()
207   }
208
209   showSupportModal () {
210     this.videoSupportModal.show()
211   }
212
213   showShareModal () {
214     this.videoShareModal.show()
215   }
216
217   showDownloadModal (event: Event) {
218     event.preventDefault()
219     this.videoDownloadModal.show()
220   }
221
222   isUserLoggedIn () {
223     return this.authService.isLoggedIn()
224   }
225
226   isVideoUpdatable () {
227     return this.video.isUpdatableBy(this.authService.getUser())
228   }
229
230   isVideoBlacklistable () {
231     return this.video.isBlackistableBy(this.user)
232   }
233
234   getAvatarPath () {
235     return Account.GET_ACCOUNT_AVATAR_URL(this.video.account)
236   }
237
238   getVideoPoster () {
239     if (!this.video) return ''
240
241     return this.video.previewUrl
242   }
243
244   getVideoTags () {
245     if (!this.video || Array.isArray(this.video.tags) === false) return []
246
247     return this.video.tags.join(', ')
248   }
249
250   generateSyndicationList () {
251     this.syndicationItems = this.videoService.getAccountFeedUrls(this.video.account.id)
252   }
253
254   isVideoRemovable () {
255     return this.video.isRemovableBy(this.authService.getUser())
256   }
257
258   async removeVideo (event: Event) {
259     event.preventDefault()
260
261     const res = await this.confirmService.confirm('Do you really want to delete this video?', 'Delete')
262     if (res === false) return
263
264     this.videoService.removeVideo(this.video.id)
265       .subscribe(
266         status => {
267           this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
268
269           // Go back to the video-list.
270           this.redirectService.redirectToHomepage()
271         },
272
273         error => this.notificationsService.error('Error', error.message)
274       )
275   }
276
277   acceptedPrivacyConcern () {
278     peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
279     this.hasAlreadyAcceptedPrivacyConcern = true
280   }
281
282   private updateVideoDescription (description: string) {
283     this.video.description = description
284     this.setVideoDescriptionHTML()
285   }
286
287   private setVideoDescriptionHTML () {
288     if (!this.video.description) {
289       this.videoHTMLDescription = ''
290       return
291     }
292
293     this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
294   }
295
296   private setVideoLikesBarTooltipText () {
297     this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
298   }
299
300   private handleError (err: any) {
301     const errorMessage: string = typeof err === 'string' ? err : err.message
302     if (!errorMessage) return
303
304     let message = ''
305
306     if (errorMessage.indexOf('http error') !== -1) {
307       message = 'Cannot fetch video from server, maybe down.'
308     } else {
309       message = errorMessage
310     }
311
312     this.notificationsService.error('Error', message)
313   }
314
315   private checkUserRating () {
316     // Unlogged users do not have ratings
317     if (this.isUserLoggedIn() === false) return
318
319     this.videoService.getUserVideoRating(this.video.id)
320                      .subscribe(
321                        ratingObject => {
322                          if (ratingObject) {
323                            this.userRating = ratingObject.rating
324                          }
325                        },
326
327                        err => this.notificationsService.error('Error', err.message)
328                       )
329   }
330
331   private async onVideoFetched (video: VideoDetails, startTime = 0) {
332     this.video = video
333
334     // Re init attributes
335     this.descriptionLoading = false
336     this.completeDescriptionShown = false
337
338     this.updateOtherVideosDisplayed()
339
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'
344       )
345       if (res === false) return this.redirectService.redirectToHomepage()
346     }
347
348     // Flush old player if needed
349     this.flushPlayer()
350
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)
356
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,
364       enableHotkeys: true,
365       peertubeLink: false,
366       poster: this.video.previewUrl,
367       startTime
368     })
369
370     const self = this
371     this.zone.runOutsideAngular(() => {
372       videojs(this.playerElement, videojsOptions, function () {
373         self.player = this
374         this.on('customError', (event, data) => self.handleError(data.err))
375       })
376     })
377
378     this.setVideoDescriptionHTML()
379     this.setVideoLikesBarTooltipText()
380
381     this.setOpenGraphTags()
382     this.checkUserRating()
383   }
384
385   private setRating (nextRating) {
386     let method
387     switch (nextRating) {
388       case 'like':
389         method = this.videoService.setVideoLike
390         break
391       case 'dislike':
392         method = this.videoService.setVideoDislike
393         break
394       case 'none':
395         method = this.videoService.unsetVideoLike
396         break
397     }
398
399     method.call(this.videoService, this.video.id)
400      .subscribe(
401       () => {
402         // Update the video like attribute
403         this.updateVideoRating(this.userRating, nextRating)
404         this.userRating = nextRating
405       },
406       err => this.notificationsService.error('Error', err.message)
407      )
408   }
409
410   private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
411     let likesToIncrement = 0
412     let dislikesToIncrement = 0
413
414     if (oldRating) {
415       if (oldRating === 'like') likesToIncrement--
416       if (oldRating === 'dislike') dislikesToIncrement--
417     }
418
419     if (newRating === 'like') likesToIncrement++
420     if (newRating === 'dislike') dislikesToIncrement++
421
422     this.video.likes += likesToIncrement
423     this.video.dislikes += dislikesToIncrement
424
425     this.video.buildLikeAndDislikePercents()
426     this.setVideoLikesBarTooltipText()
427   }
428
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)
432     }
433   }
434
435   private setOpenGraphTags () {
436     this.metaService.setTitle(this.video.name)
437
438     this.metaService.setTag('og:type', 'video')
439
440     this.metaService.setTag('og:title', this.video.name)
441     this.metaService.setTag('name', this.video.name)
442
443     this.metaService.setTag('og:description', this.video.description)
444     this.metaService.setTag('description', this.video.description)
445
446     this.metaService.setTag('og:image', this.video.previewPath)
447
448     this.metaService.setTag('og:duration', this.video.duration.toString())
449
450     this.metaService.setTag('og:site_name', 'PeerTube')
451
452     this.metaService.setTag('og:url', window.location.href)
453     this.metaService.setTag('url', window.location.href)
454   }
455
456   private isAutoplay () {
457     // True by default
458     if (!this.user) return true
459
460     // Be sure the autoPlay is set to false
461     return this.user.autoPlayVideo !== false
462   }
463
464   private flushPlayer () {
465     // Remove player if it exists
466     if (this.player) {
467       this.player.dispose()
468       this.player = undefined
469     }
470   }
471 }