Design second video upload step
[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 { VideoDetails } from '../../shared/video/video-details.model'
15 import { Video } from '../../shared/video/video.model'
16 import { MarkdownService } from '../shared'
17 import { VideoDownloadComponent } from './video-download.component'
18 import { VideoReportComponent } from './video-report.component'
19 import { VideoShareComponent } from './video-share.component'
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   isVideoBlacklistable () {
203     return this.video.isBlackistableBy(this.authService.getUser())
204   }
205
206   getAvatarPath () {
207     return Account.GET_ACCOUNT_AVATAR_PATH(this.video.account)
208   }
209
210   getVideoTags () {
211     if (!this.video || Array.isArray(this.video.tags) === false) return []
212
213     return this.video.tags.join(', ')
214   }
215
216   private updateVideoDescription (description: string) {
217     this.video.description = description
218     this.setVideoDescriptionHTML()
219   }
220
221   private setVideoDescriptionHTML () {
222     if (!this.video.description) {
223       this.videoHTMLDescription = ''
224       return
225     }
226
227     this.videoHTMLDescription = this.markdownService.markdownToHTML(this.video.description)
228   }
229
230   private handleError (err: any) {
231     const errorMessage: string = typeof err === 'string' ? err : err.message
232     let message = ''
233
234     if (errorMessage.indexOf('http error') !== -1) {
235       message = 'Cannot fetch video from server, maybe down.'
236     } else {
237       message = errorMessage
238     }
239
240     this.notificationsService.error('Error', message)
241   }
242
243   private checkUserRating () {
244     // Unlogged users do not have ratings
245     if (this.isUserLoggedIn() === false) return
246
247     this.videoService.getUserVideoRating(this.video.id)
248                      .subscribe(
249                        ratingObject => {
250                          if (ratingObject) {
251                            this.userRating = ratingObject.rating
252                          }
253                        },
254
255                        err => this.notificationsService.error('Error', err.message)
256                       )
257   }
258
259   private onVideoFetched (video: VideoDetails) {
260     this.video = video
261
262     let observable
263     if (this.video.isVideoNSFWForUser(this.authService.getUser())) {
264       observable = this.confirmService.confirm(
265         'This video contains mature or explicit content. Are you sure you want to watch it?',
266         'Mature or explicit content'
267       )
268     } else {
269       observable = Observable.of(true)
270     }
271
272     observable.subscribe(
273       res => {
274         if (res === false) {
275
276           return this.router.navigate([ '/videos/list' ])
277         }
278
279         this.playerElement = this.elementRef.nativeElement.querySelector('#video-element')
280
281         const videojsOptions = {
282           controls: true,
283           autoplay: true,
284           plugins: {
285             peertube: {
286               videoFiles: this.video.files,
287               playerElement: this.playerElement,
288               autoplay: true,
289               peerTubeLink: false
290             }
291           }
292         }
293
294         this.videoPlayerLoaded = true
295
296         const self = this
297         videojs(this.playerElement, videojsOptions, function () {
298           self.player = this
299           this.on('customError', (event, data) => {
300             self.handleError(data.err)
301           })
302         })
303
304         this.setVideoDescriptionHTML()
305
306         this.setOpenGraphTags()
307         this.checkUserRating()
308
309         this.prepareViewAdd()
310       }
311     )
312   }
313
314   private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
315     let likesToIncrement = 0
316     let dislikesToIncrement = 0
317
318     if (oldRating) {
319       if (oldRating === 'like') likesToIncrement--
320       if (oldRating === 'dislike') dislikesToIncrement--
321     }
322
323     if (newRating === 'like') likesToIncrement++
324     if (newRating === 'dislike') dislikesToIncrement++
325
326     this.video.likes += likesToIncrement
327     this.video.dislikes += dislikesToIncrement
328   }
329
330   private setOpenGraphTags () {
331     this.metaService.setTitle(this.video.name)
332
333     this.metaService.setTag('og:type', 'video')
334
335     this.metaService.setTag('og:title', this.video.name)
336     this.metaService.setTag('name', this.video.name)
337
338     this.metaService.setTag('og:description', this.video.description)
339     this.metaService.setTag('description', this.video.description)
340
341     this.metaService.setTag('og:image', this.video.previewPath)
342
343     this.metaService.setTag('og:duration', this.video.duration.toString())
344
345     this.metaService.setTag('og:site_name', 'PeerTube')
346
347     this.metaService.setTag('og:url', window.location.href)
348     this.metaService.setTag('url', window.location.href)
349   }
350
351   private prepareViewAdd () {
352     // After 30 seconds (or 3/4 of the video), increment add a view
353     let viewTimeoutSeconds = 30
354     if (this.video.duration < viewTimeoutSeconds) viewTimeoutSeconds = (this.video.duration * 3) / 4
355
356     setTimeout(() => {
357       this.videoService
358         .viewVideo(this.video.uuid)
359         .subscribe()
360
361     }, viewTimeoutSeconds * 1000)
362   }
363 }