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