Begin video watch design
[oweals/peertube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
1 import { Component, ElementRef, 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 { VideoService } from 'app/shared/video/video.service'
6 import { Observable } from 'rxjs/Observable'
7 import { Subscription } from 'rxjs/Subscription'
8 import videojs from 'video.js'
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 { Video } from '../../shared/video/video.model'
15 import { MarkdownService } from '../shared'
16 import { VideoDownloadComponent } from './video-download.component'
17 import { VideoReportComponent } from './video-report.component'
18 import { VideoShareComponent } from './video-share.component'
19 import { VideoDetails } from '../../shared/video/video-details.model'
20
21 @Component({
22   selector: 'my-video-watch',
23   templateUrl: './video-watch.component.html',
24   styleUrls: [ './video-watch.component.scss' ]
25 })
26 export class VideoWatchComponent implements OnInit, OnDestroy {
27   @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
28   @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
29   @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
30
31   otherVideos: Video[] = []
32
33   error = false
34   loading = false
35   player: videojs.Player
36   playerElement: HTMLMediaElement
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
48   private paramsSub: Subscription
49
50   constructor (
51     private elementRef: ElementRef,
52     private route: ActivatedRoute,
53     private router: Router,
54     private videoService: VideoService,
55     private videoBlacklistService: VideoBlacklistService,
56     private confirmService: ConfirmService,
57     private metaService: MetaService,
58     private authService: AuthService,
59     private notificationsService: NotificationsService,
60     private markdownService: MarkdownService
61   ) {}
62
63   ngOnInit () {
64     this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
65       .subscribe(
66         data => this.otherVideos = data.videos,
67
68     err => console.error(err)
69       )
70
71     this.paramsSub = this.route.params.subscribe(routeParams => {
72       let uuid = routeParams['uuid']
73       this.videoService.getVideo(uuid).subscribe(
74         video => this.onVideoFetched(video),
75
76         error => {
77           this.videoNotFound = true
78           console.error(error)
79         }
80       )
81     })
82   }
83
84   ngOnDestroy () {
85     // Remove player if it exists
86     if (this.videoPlayerLoaded === true) {
87       videojs(this.playerElement).dispose()
88     }
89
90     // Unsubscribe subscriptions
91     this.paramsSub.unsubscribe()
92   }
93
94   setLike () {
95     if (this.isUserLoggedIn() === false) return
96     // Already liked this video
97     if (this.userRating === 'like') return
98
99     this.videoService.setVideoLike(this.video.id)
100                      .subscribe(
101                       () => {
102                         // Update the video like attribute
103                         this.updateVideoRating(this.userRating, 'like')
104                         this.userRating = 'like'
105                       },
106
107                       err => this.notificationsService.error('Error', err.message)
108                      )
109   }
110
111   setDislike () {
112     if (this.isUserLoggedIn() === false) return
113     // Already disliked this video
114     if (this.userRating === 'dislike') return
115
116     this.videoService.setVideoDislike(this.video.id)
117                      .subscribe(
118                       () => {
119                         // Update the video dislike attribute
120                         this.updateVideoRating(this.userRating, 'dislike')
121                         this.userRating = 'dislike'
122                       },
123
124                       err => this.notificationsService.error('Error', err.message)
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.text)
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.text)
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   canUserUpdateVideo () {
203     return this.video.isUpdatableBy(this.authService.getUser())
204   }
205
206   isVideoRemovable () {
207     return this.video.isRemovableBy(this.authService.getUser())
208   }
209
210   isVideoBlacklistable () {
211     return this.video.isBlackistableBy(this.authService.getUser())
212   }
213
214   getAvatarPath () {
215     return Account.GET_ACCOUNT_AVATAR_PATH(this.video.account)
216   }
217
218   getVideoTags () {
219     if (!this.video || Array.isArray(this.video.tags) === false) return []
220
221     return this.video.tags.join(', ')
222   }
223
224   private updateVideoDescription (description: string) {
225     this.video.description = description
226     this.setVideoDescriptionHTML()
227   }
228
229   private setVideoDescriptionHTML () {
230     this.videoHTMLDescription = this.markdownService.markdownToHTML(this.video.description)
231   }
232
233   private handleError (err: any) {
234     const errorMessage: string = typeof err === 'string' ? err : err.message
235     let message = ''
236
237     if (errorMessage.indexOf('http error') !== -1) {
238       message = 'Cannot fetch video from server, maybe down.'
239     } else {
240       message = errorMessage
241     }
242
243     this.notificationsService.error('Error', message)
244   }
245
246   private checkUserRating () {
247     // Unlogged users do not have ratings
248     if (this.isUserLoggedIn() === false) return
249
250     this.videoService.getUserVideoRating(this.video.id)
251                      .subscribe(
252                        ratingObject => {
253                          if (ratingObject) {
254                            this.userRating = ratingObject.rating
255                          }
256                        },
257
258                        err => this.notificationsService.error('Error', err.message)
259                       )
260   }
261
262   private onVideoFetched (video: VideoDetails) {
263     this.video = video
264
265     let observable
266     if (this.video.isVideoNSFWForUser(this.authService.getUser())) {
267       observable = this.confirmService.confirm(
268         'This video contains mature or explicit content. Are you sure you want to watch it?',
269         'Mature or explicit content'
270       )
271     } else {
272       observable = Observable.of(true)
273     }
274
275     observable.subscribe(
276       res => {
277         if (res === false) {
278
279           return this.router.navigate([ '/videos/list' ])
280         }
281
282         this.playerElement = this.elementRef.nativeElement.querySelector('#video-element')
283
284         const videojsOptions = {
285           controls: true,
286           autoplay: true,
287           plugins: {
288             peertube: {
289               videoFiles: this.video.files,
290               playerElement: this.playerElement,
291               autoplay: true,
292               peerTubeLink: false
293             }
294           }
295         }
296
297         this.videoPlayerLoaded = true
298
299         const self = this
300         videojs(this.playerElement, videojsOptions, function () {
301           self.player = this
302           this.on('customError', (event, data) => {
303             self.handleError(data.err)
304           })
305         })
306
307         this.setVideoDescriptionHTML()
308
309         this.setOpenGraphTags()
310         this.checkUserRating()
311
312         this.prepareViewAdd()
313       }
314     )
315   }
316
317   private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
318     let likesToIncrement = 0
319     let dislikesToIncrement = 0
320
321     if (oldRating) {
322       if (oldRating === 'like') likesToIncrement--
323       if (oldRating === 'dislike') dislikesToIncrement--
324     }
325
326     if (newRating === 'like') likesToIncrement++
327     if (newRating === 'dislike') dislikesToIncrement++
328
329     this.video.likes += likesToIncrement
330     this.video.dislikes += dislikesToIncrement
331   }
332
333   private setOpenGraphTags () {
334     this.metaService.setTitle(this.video.name)
335
336     this.metaService.setTag('og:type', 'video')
337
338     this.metaService.setTag('og:title', this.video.name)
339     this.metaService.setTag('name', this.video.name)
340
341     this.metaService.setTag('og:description', this.video.description)
342     this.metaService.setTag('description', this.video.description)
343
344     this.metaService.setTag('og:image', this.video.previewPath)
345
346     this.metaService.setTag('og:duration', this.video.duration.toString())
347
348     this.metaService.setTag('og:site_name', 'PeerTube')
349
350     this.metaService.setTag('og:url', window.location.href)
351     this.metaService.setTag('url', window.location.href)
352   }
353
354   private prepareViewAdd () {
355     // After 30 seconds (or 3/4 of the video), increment add a view
356     let viewTimeoutSeconds = 30
357     if (this.video.duration < viewTimeoutSeconds) viewTimeoutSeconds = (this.video.duration * 3) / 4
358
359     setTimeout(() => {
360       this.videoService
361         .viewVideo(this.video.uuid)
362         .subscribe()
363
364     }, viewTimeoutSeconds * 1000)
365   }
366 }