Add ability to update thumbnail and preview on client
[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 { MetaService } from '@ngx-meta/core'
4 import { NotificationsService } from 'angular2-notifications'
5 import { Observable } from 'rxjs/Observable'
6 import { Subscription } from 'rxjs/Subscription'
7 import * as videojs from 'video.js'
8 import 'videojs-hotkeys'
9 import { UserVideoRateType, VideoRateType } from '../../../../../shared'
10 import '../../../assets/player/peertube-videojs-plugin'
11 import { AuthService, ConfirmService } from '../../core'
12 import { VideoBlacklistService } from '../../shared'
13 import { Account } from '../../shared/account/account.model'
14 import { VideoDetails } from '../../shared/video/video-details.model'
15 import { Video } from '../../shared/video/video.model'
16 import { VideoService } from '../../shared/video/video.service'
17 import { MarkdownService } from '../shared'
18 import { VideoDownloadComponent } from './modal/video-download.component'
19 import { VideoReportComponent } from './modal/video-report.component'
20 import { VideoShareComponent } from './modal/video-share.component'
21
22 @Component({
23   selector: 'my-video-watch',
24   templateUrl: './video-watch.component.html',
25   styleUrls: [ './video-watch.component.scss' ]
26 })
27 export class VideoWatchComponent implements OnInit, OnDestroy {
28   @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
29   @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
30   @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
31
32   otherVideosDisplayed: Video[] = []
33
34   error = false
35   player: videojs.Player
36   playerElement: HTMLVideoElement
37   userRating: UserVideoRateType = null
38   video: VideoDetails = null
39   videoPlayerLoaded = false
40   videoNotFound = false
41   descriptionLoading = false
42
43   completeDescriptionShown = false
44   completeVideoDescription: string
45   shortVideoDescription: string
46   videoHTMLDescription = ''
47   likesBarTooltipText = ''
48
49   private otherVideos: Video[] = []
50   private paramsSub: Subscription
51
52   constructor (
53     private elementRef: ElementRef,
54     private route: ActivatedRoute,
55     private router: Router,
56     private videoService: VideoService,
57     private videoBlacklistService: VideoBlacklistService,
58     private confirmService: ConfirmService,
59     private metaService: MetaService,
60     private authService: AuthService,
61     private notificationsService: NotificationsService,
62     private markdownService: MarkdownService,
63     private zone: NgZone
64   ) {}
65
66   get user () {
67     return this.authService.getUser()
68   }
69
70   ngOnInit () {
71     this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
72       .subscribe(
73         data => {
74           this.otherVideos = data.videos
75           this.updateOtherVideosDisplayed()
76         },
77
78         err => console.error(err)
79       )
80
81     this.paramsSub = this.route.params.subscribe(routeParams => {
82       if (this.videoPlayerLoaded) {
83         this.player.pause()
84       }
85
86       let uuid = routeParams['uuid']
87       this.videoService.getVideo(uuid).subscribe(
88         video => this.onVideoFetched(video),
89
90         error => {
91           this.videoNotFound = true
92           console.error(error)
93         }
94       )
95     })
96   }
97
98   ngOnDestroy () {
99     // Remove player if it exists
100     if (this.videoPlayerLoaded === true) {
101       videojs(this.playerElement).dispose()
102     }
103
104     // Unsubscribe subscriptions
105     this.paramsSub.unsubscribe()
106   }
107
108   setLike () {
109     if (this.isUserLoggedIn() === false) return
110     if (this.userRating === 'like') {
111       // Already liked this video
112       this.setRating('none')
113     } else {
114       this.setRating('like')
115     }
116   }
117
118   setDislike () {
119     if (this.isUserLoggedIn() === false) return
120     if (this.userRating === 'dislike') {
121       // Already disliked this video
122       this.setRating('none')
123     } else {
124       this.setRating('dislike')
125     }
126   }
127
128   blacklistVideo (event: Event) {
129     event.preventDefault()
130
131     this.confirmService.confirm('Do you really want to blacklist this video?', 'Blacklist').subscribe(
132       res => {
133         if (res === false) return
134
135         this.videoBlacklistService.blacklistVideo(this.video.id)
136                                   .subscribe(
137                                     status => {
138                                       this.notificationsService.success('Success', `Video ${this.video.name} had been blacklisted.`)
139                                       this.router.navigate(['/videos/list'])
140                                     },
141
142                                     error => this.notificationsService.error('Error', error.message)
143                                   )
144       }
145     )
146   }
147
148   showMoreDescription () {
149     if (this.completeVideoDescription === undefined) {
150       return this.loadCompleteDescription()
151     }
152
153     this.updateVideoDescription(this.completeVideoDescription)
154     this.completeDescriptionShown = true
155   }
156
157   showLessDescription () {
158     this.updateVideoDescription(this.shortVideoDescription)
159     this.completeDescriptionShown = false
160   }
161
162   loadCompleteDescription () {
163     this.descriptionLoading = true
164
165     this.videoService.loadCompleteDescription(this.video.descriptionPath)
166       .subscribe(
167         description => {
168           this.completeDescriptionShown = true
169           this.descriptionLoading = false
170
171           this.shortVideoDescription = this.video.description
172           this.completeVideoDescription = description
173
174           this.updateVideoDescription(this.completeVideoDescription)
175         },
176
177         error => {
178           this.descriptionLoading = false
179           this.notificationsService.error('Error', error.message)
180         }
181       )
182   }
183
184   showReportModal (event: Event) {
185     event.preventDefault()
186     this.videoReportModal.show()
187   }
188
189   showShareModal () {
190     this.videoShareModal.show()
191   }
192
193   showDownloadModal (event: Event) {
194     event.preventDefault()
195     this.videoDownloadModal.show()
196   }
197
198   isUserLoggedIn () {
199     return this.authService.isLoggedIn()
200   }
201
202   isVideoUpdatable () {
203     return this.video.isUpdatableBy(this.authService.getUser())
204   }
205
206   isVideoBlacklistable () {
207     return this.video.isBlackistableBy(this.user)
208   }
209
210   getAvatarPath () {
211     return Account.GET_ACCOUNT_AVATAR_URL(this.video.account)
212   }
213
214   getVideoPoster () {
215     if (!this.video) return ''
216
217     return this.video.previewUrl
218   }
219
220   getVideoTags () {
221     if (!this.video || Array.isArray(this.video.tags) === false) return []
222
223     return this.video.tags.join(', ')
224   }
225
226   isVideoRemovable () {
227     return this.video.isRemovableBy(this.authService.getUser())
228   }
229
230   removeVideo (event: Event) {
231     event.preventDefault()
232
233     this.confirmService.confirm('Do you really want to delete this video?', 'Delete')
234       .subscribe(
235         res => {
236           if (res === false) return
237
238           this.videoService.removeVideo(this.video.id)
239             .subscribe(
240               status => {
241                 this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
242
243                 // Go back to the video-list.
244                 this.router.navigate([ '/videos/list' ])
245               },
246
247               error => this.notificationsService.error('Error', error.message)
248             )
249         }
250       )
251   }
252
253   private updateVideoDescription (description: string) {
254     this.video.description = description
255     this.setVideoDescriptionHTML()
256   }
257
258   private setVideoDescriptionHTML () {
259     if (!this.video.description) {
260       this.videoHTMLDescription = ''
261       return
262     }
263
264     this.videoHTMLDescription = this.markdownService.markdownToHTML(this.video.description)
265   }
266
267   private setVideoLikesBarTooltipText () {
268     this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
269   }
270
271   private handleError (err: any) {
272     const errorMessage: string = typeof err === 'string' ? err : err.message
273     let message = ''
274
275     if (errorMessage.indexOf('http error') !== -1) {
276       message = 'Cannot fetch video from server, maybe down.'
277     } else {
278       message = errorMessage
279     }
280
281     this.notificationsService.error('Error', message)
282   }
283
284   private checkUserRating () {
285     // Unlogged users do not have ratings
286     if (this.isUserLoggedIn() === false) return
287
288     this.videoService.getUserVideoRating(this.video.id)
289                      .subscribe(
290                        ratingObject => {
291                          if (ratingObject) {
292                            this.userRating = ratingObject.rating
293                          }
294                        },
295
296                        err => this.notificationsService.error('Error', err.message)
297                       )
298   }
299
300   private onVideoFetched (video: VideoDetails) {
301     this.video = video
302
303     this.updateOtherVideosDisplayed()
304
305     let observable
306     if (this.video.isVideoNSFWForUser(this.user)) {
307       observable = this.confirmService.confirm(
308         'This video contains mature or explicit content. Are you sure you want to watch it?',
309         'Mature or explicit content'
310       )
311     } else {
312       observable = Observable.of(true)
313     }
314
315     observable.subscribe(
316       res => {
317         if (res === false) {
318
319           return this.router.navigate([ '/videos/list' ])
320         }
321
322         // Player was already loaded
323         if (this.videoPlayerLoaded !== true) {
324           this.playerElement = this.elementRef.nativeElement.querySelector('#video-element')
325
326           // If autoplay is true, we don't really need a poster
327           if (this.isAutoplay() === false) {
328             this.playerElement.poster = this.video.previewUrl
329           }
330
331           const videojsOptions = {
332             controls: true,
333             autoplay: this.isAutoplay(),
334             plugins: {
335               peertube: {
336                 videoFiles: this.video.files,
337                 playerElement: this.playerElement,
338                 peerTubeLink: false,
339                 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
340                 videoDuration: this.video.duration
341               },
342               hotkeys: {
343                 enableVolumeScroll: false
344               }
345             }
346           }
347
348           this.videoPlayerLoaded = true
349
350           const self = this
351           this.zone.runOutsideAngular(() => {
352             videojs(this.playerElement, videojsOptions, function () {
353               self.player = this
354               this.on('customError', (event, data) => {
355                 self.handleError(data.err)
356               })
357             })
358           })
359         } else {
360           const videoViewUrl = this.videoService.getVideoViewUrl(this.video.uuid)
361           this.player.peertube().setVideoFiles(this.video.files, videoViewUrl, this.video.duration)
362         }
363
364         this.setVideoDescriptionHTML()
365         this.setVideoLikesBarTooltipText()
366
367         this.setOpenGraphTags()
368         this.checkUserRating()
369       }
370     )
371   }
372
373   private setRating (nextRating) {
374     let method
375     switch (nextRating) {
376       case 'like':
377         method = this.videoService.setVideoLike
378         break
379       case 'dislike':
380         method = this.videoService.setVideoDislike
381         break
382       case 'none':
383         method = this.videoService.unsetVideoLike
384         break
385     }
386
387     method.call(this.videoService, this.video.id)
388      .subscribe(
389       () => {
390         // Update the video like attribute
391         this.updateVideoRating(this.userRating, nextRating)
392         this.userRating = nextRating
393       },
394       err => this.notificationsService.error('Error', err.message)
395      )
396   }
397
398   private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
399     let likesToIncrement = 0
400     let dislikesToIncrement = 0
401
402     if (oldRating) {
403       if (oldRating === 'like') likesToIncrement--
404       if (oldRating === 'dislike') dislikesToIncrement--
405     }
406
407     if (newRating === 'like') likesToIncrement++
408     if (newRating === 'dislike') dislikesToIncrement++
409
410     this.video.likes += likesToIncrement
411     this.video.dislikes += dislikesToIncrement
412   }
413
414   private updateOtherVideosDisplayed () {
415     if (this.video && this.otherVideos && this.otherVideos.length > 0) {
416       this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
417     }
418   }
419
420   private setOpenGraphTags () {
421     this.metaService.setTitle(this.video.name)
422
423     this.metaService.setTag('og:type', 'video')
424
425     this.metaService.setTag('og:title', this.video.name)
426     this.metaService.setTag('name', this.video.name)
427
428     this.metaService.setTag('og:description', this.video.description)
429     this.metaService.setTag('description', this.video.description)
430
431     this.metaService.setTag('og:image', this.video.previewPath)
432
433     this.metaService.setTag('og:duration', this.video.duration.toString())
434
435     this.metaService.setTag('og:site_name', 'PeerTube')
436
437     this.metaService.setTag('og:url', window.location.href)
438     this.metaService.setTag('url', window.location.href)
439   }
440
441   private isAutoplay () {
442     // True by default
443     if (!this.user) return true
444
445     // Be sure the autoPlay is set to false
446     return this.user.autoPlayVideo !== false
447   }
448 }