Fix video play promise error on non supported browsers
[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   getVideoTags () {
215     if (!this.video || Array.isArray(this.video.tags) === false) return []
216
217     return this.video.tags.join(', ')
218   }
219
220   isVideoRemovable () {
221     return this.video.isRemovableBy(this.authService.getUser())
222   }
223
224   removeVideo (event: Event) {
225     event.preventDefault()
226
227     this.confirmService.confirm('Do you really want to delete this video?', 'Delete')
228       .subscribe(
229         res => {
230           if (res === false) return
231
232           this.videoService.removeVideo(this.video.id)
233             .subscribe(
234               status => {
235                 this.notificationsService.success('Success', `Video ${this.video.name} deleted.`)
236
237                 // Go back to the video-list.
238                 this.router.navigate([ '/videos/list' ])
239               },
240
241               error => this.notificationsService.error('Error', error.message)
242             )
243         }
244       )
245   }
246
247   private updateVideoDescription (description: string) {
248     this.video.description = description
249     this.setVideoDescriptionHTML()
250   }
251
252   private setVideoDescriptionHTML () {
253     if (!this.video.description) {
254       this.videoHTMLDescription = ''
255       return
256     }
257
258     this.videoHTMLDescription = this.markdownService.markdownToHTML(this.video.description)
259   }
260
261   private setVideoLikesBarTooltipText () {
262     this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
263   }
264
265   private handleError (err: any) {
266     const errorMessage: string = typeof err === 'string' ? err : err.message
267     let message = ''
268
269     if (errorMessage.indexOf('http error') !== -1) {
270       message = 'Cannot fetch video from server, maybe down.'
271     } else {
272       message = errorMessage
273     }
274
275     this.notificationsService.error('Error', message)
276   }
277
278   private checkUserRating () {
279     // Unlogged users do not have ratings
280     if (this.isUserLoggedIn() === false) return
281
282     this.videoService.getUserVideoRating(this.video.id)
283                      .subscribe(
284                        ratingObject => {
285                          if (ratingObject) {
286                            this.userRating = ratingObject.rating
287                          }
288                        },
289
290                        err => this.notificationsService.error('Error', err.message)
291                       )
292   }
293
294   private onVideoFetched (video: VideoDetails) {
295     this.video = video
296
297     this.updateOtherVideosDisplayed()
298
299     let observable
300     if (this.video.isVideoNSFWForUser(this.user)) {
301       observable = this.confirmService.confirm(
302         'This video contains mature or explicit content. Are you sure you want to watch it?',
303         'Mature or explicit content'
304       )
305     } else {
306       observable = Observable.of(true)
307     }
308
309     observable.subscribe(
310       res => {
311         if (res === false) {
312
313           return this.router.navigate([ '/videos/list' ])
314         }
315
316         // Player was already loaded
317         if (this.videoPlayerLoaded !== true) {
318           this.playerElement = this.elementRef.nativeElement.querySelector('#video-element')
319
320           // If autoplay is true, we don't really need a poster
321           if (this.isAutoplay() === false) {
322             this.playerElement.poster = this.video.previewUrl
323           }
324
325           const videojsOptions = {
326             controls: true,
327             autoplay: this.isAutoplay(),
328             plugins: {
329               peertube: {
330                 videoFiles: this.video.files,
331                 playerElement: this.playerElement,
332                 peerTubeLink: false,
333                 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
334                 videoDuration: this.video.duration
335               },
336               hotkeys: {
337                 enableVolumeScroll: false
338               }
339             }
340           }
341
342           this.videoPlayerLoaded = true
343
344           const self = this
345           this.zone.runOutsideAngular(() => {
346             videojs(this.playerElement, videojsOptions, function () {
347               self.player = this
348               this.on('customError', (event, data) => {
349                 self.handleError(data.err)
350               })
351             })
352           })
353         } else {
354           const videoViewUrl = this.videoService.getVideoViewUrl(this.video.uuid)
355           this.player.peertube().setVideoFiles(this.video.files, videoViewUrl, this.video.duration)
356         }
357
358         this.setVideoDescriptionHTML()
359         this.setVideoLikesBarTooltipText()
360
361         this.setOpenGraphTags()
362         this.checkUserRating()
363       }
364     )
365   }
366
367   private setRating (nextRating) {
368     let method
369     switch (nextRating) {
370       case 'like':
371         method = this.videoService.setVideoLike
372         break
373       case 'dislike':
374         method = this.videoService.setVideoDislike
375         break
376       case 'none':
377         method = this.videoService.unsetVideoLike
378         break
379     }
380
381     method.call(this.videoService, this.video.id)
382      .subscribe(
383       () => {
384         // Update the video like attribute
385         this.updateVideoRating(this.userRating, nextRating)
386         this.userRating = nextRating
387       },
388       err => this.notificationsService.error('Error', err.message)
389      )
390   }
391
392   private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
393     let likesToIncrement = 0
394     let dislikesToIncrement = 0
395
396     if (oldRating) {
397       if (oldRating === 'like') likesToIncrement--
398       if (oldRating === 'dislike') dislikesToIncrement--
399     }
400
401     if (newRating === 'like') likesToIncrement++
402     if (newRating === 'dislike') dislikesToIncrement++
403
404     this.video.likes += likesToIncrement
405     this.video.dislikes += dislikesToIncrement
406   }
407
408   private updateOtherVideosDisplayed () {
409     if (this.video && this.otherVideos && this.otherVideos.length > 0) {
410       this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
411     }
412   }
413
414   private setOpenGraphTags () {
415     this.metaService.setTitle(this.video.name)
416
417     this.metaService.setTag('og:type', 'video')
418
419     this.metaService.setTag('og:title', this.video.name)
420     this.metaService.setTag('name', this.video.name)
421
422     this.metaService.setTag('og:description', this.video.description)
423     this.metaService.setTag('description', this.video.description)
424
425     this.metaService.setTag('og:image', this.video.previewPath)
426
427     this.metaService.setTag('og:duration', this.video.duration.toString())
428
429     this.metaService.setTag('og:site_name', 'PeerTube')
430
431     this.metaService.setTag('og:url', window.location.href)
432     this.metaService.setTag('url', window.location.href)
433   }
434
435   private isAutoplay () {
436     // True by default
437     if (!this.user) return true
438
439     // Be sure the autoPlay is set to false
440     return this.user.autoPlayVideo !== false
441   }
442 }