Merge branch 'release/beta-10' into develop
[oweals/peertube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
1 import { catchError } from 'rxjs/operators'
2 import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
3 import { ActivatedRoute, Router } from '@angular/router'
4 import { RedirectService } from '@app/core/routing/redirect.service'
5 import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
6 import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
7 import { MetaService } from '@ngx-meta/core'
8 import { NotificationsService } from 'angular2-notifications'
9 import { forkJoin, Subscription } from 'rxjs'
10 import * as videojs from 'video.js'
11 import 'videojs-hotkeys'
12 import * as WebTorrent from 'webtorrent'
13 import { UserVideoRateType, VideoPrivacy, VideoRateType, VideoState } from '../../../../../shared'
14 import '../../../assets/player/peertube-videojs-plugin'
15 import { AuthService, ConfirmService } from '../../core'
16 import { RestExtractor, VideoBlacklistService } from '../../shared'
17 import { VideoDetails } from '../../shared/video/video-details.model'
18 import { Video } from '../../shared/video/video.model'
19 import { VideoService } from '../../shared/video/video.service'
20 import { MarkdownService } from '../shared'
21 import { VideoDownloadComponent } from './modal/video-download.component'
22 import { VideoReportComponent } from './modal/video-report.component'
23 import { VideoShareComponent } from './modal/video-share.component'
24 import { addContextMenu, getVideojsOptions, loadLocale } from '../../../assets/player/peertube-player'
25 import { ServerService } from '@app/core'
26 import { I18n } from '@ngx-translate/i18n-polyfill'
27 import { environment } from '../../../environments/environment'
28 import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
29 import { VideoCaptionService } from '@app/shared/video-caption'
30 import { VideoCaption } from '../../../../../shared/models/videos/video-caption.model'
31
32 @Component({
33   selector: 'my-video-watch',
34   templateUrl: './video-watch.component.html',
35   styleUrls: [ './video-watch.component.scss' ]
36 })
37 export class VideoWatchComponent implements OnInit, OnDestroy {
38   private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
39
40   @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
41   @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
42   @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
43   @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
44
45   otherVideosDisplayed: Video[] = []
46
47   player: videojs.Player
48   playerElement: HTMLVideoElement
49   userRating: UserVideoRateType = null
50   video: VideoDetails = null
51   descriptionLoading = false
52
53   completeDescriptionShown = false
54   completeVideoDescription: string
55   shortVideoDescription: string
56   videoHTMLDescription = ''
57   likesBarTooltipText = ''
58   hasAlreadyAcceptedPrivacyConcern = false
59   remoteServerDown = false
60
61   private videojsLocaleLoaded = false
62   private otherVideos: Video[] = []
63   private paramsSub: Subscription
64
65   constructor (
66     private elementRef: ElementRef,
67     private changeDetector: ChangeDetectorRef,
68     private route: ActivatedRoute,
69     private router: Router,
70     private videoService: VideoService,
71     private videoBlacklistService: VideoBlacklistService,
72     private confirmService: ConfirmService,
73     private metaService: MetaService,
74     private authService: AuthService,
75     private serverService: ServerService,
76     private restExtractor: RestExtractor,
77     private notificationsService: NotificationsService,
78     private markdownService: MarkdownService,
79     private zone: NgZone,
80     private redirectService: RedirectService,
81     private videoCaptionService: VideoCaptionService,
82     private i18n: I18n,
83     @Inject(LOCALE_ID) private localeId: string
84   ) {}
85
86   get user () {
87     return this.authService.getUser()
88   }
89
90   ngOnInit () {
91     if (
92       WebTorrent.WEBRTC_SUPPORT === false ||
93       peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
94     ) {
95       this.hasAlreadyAcceptedPrivacyConcern = true
96     }
97
98     this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
99         .subscribe(
100           data => {
101             this.otherVideos = data.videos
102             this.updateOtherVideosDisplayed()
103           },
104
105           err => console.error(err)
106         )
107
108     this.paramsSub = this.route.params.subscribe(routeParams => {
109       const uuid = routeParams[ 'uuid' ]
110
111       // Video did not change
112       if (this.video && this.video.uuid === uuid) return
113
114       if (this.player) this.player.pause()
115
116       // Video did change
117       forkJoin(
118         this.videoService.getVideo(uuid),
119         this.videoCaptionService.listCaptions(uuid)
120       )
121         .pipe(
122           catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ]))
123         )
124         .subscribe(([ video, captionsResult ]) => {
125           const startTime = this.route.snapshot.queryParams.start
126           this.onVideoFetched(video, captionsResult.data, startTime)
127               .catch(err => this.handleError(err))
128         })
129     })
130   }
131
132   ngOnDestroy () {
133     this.flushPlayer()
134
135     // Unsubscribe subscriptions
136     this.paramsSub.unsubscribe()
137   }
138
139   setLike () {
140     if (this.isUserLoggedIn() === false) return
141     if (this.userRating === 'like') {
142       // Already liked this video
143       this.setRating('none')
144     } else {
145       this.setRating('like')
146     }
147   }
148
149   setDislike () {
150     if (this.isUserLoggedIn() === false) return
151     if (this.userRating === 'dislike') {
152       // Already disliked this video
153       this.setRating('none')
154     } else {
155       this.setRating('dislike')
156     }
157   }
158
159   async blacklistVideo (event: Event) {
160     event.preventDefault()
161
162     const res = await this.confirmService.confirm(this.i18n('Do you really want to blacklist this video?'), this.i18n('Blacklist'))
163     if (res === false) return
164
165     this.videoBlacklistService.blacklistVideo(this.video.id)
166         .subscribe(
167           () => {
168             this.notificationsService.success(
169               this.i18n('Success'),
170               this.i18n('Video {{videoName}} had been blacklisted.', { videoName: this.video.name })
171             )
172             this.redirectService.redirectToHomepage()
173           },
174
175           error => this.notificationsService.error(this.i18n('Error'), error.message)
176         )
177   }
178
179   showMoreDescription () {
180     if (this.completeVideoDescription === undefined) {
181       return this.loadCompleteDescription()
182     }
183
184     this.updateVideoDescription(this.completeVideoDescription)
185     this.completeDescriptionShown = true
186   }
187
188   showLessDescription () {
189     this.updateVideoDescription(this.shortVideoDescription)
190     this.completeDescriptionShown = false
191   }
192
193   loadCompleteDescription () {
194     this.descriptionLoading = true
195
196     this.videoService.loadCompleteDescription(this.video.descriptionPath)
197         .subscribe(
198           description => {
199             this.completeDescriptionShown = true
200             this.descriptionLoading = false
201
202             this.shortVideoDescription = this.video.description
203             this.completeVideoDescription = description
204
205             this.updateVideoDescription(this.completeVideoDescription)
206           },
207
208           error => {
209             this.descriptionLoading = false
210             this.notificationsService.error(this.i18n('Error'), error.message)
211           }
212         )
213   }
214
215   showReportModal (event: Event) {
216     event.preventDefault()
217     this.videoReportModal.show()
218   }
219
220   showSupportModal () {
221     this.videoSupportModal.show()
222   }
223
224   showShareModal () {
225     this.videoShareModal.show()
226   }
227
228   showDownloadModal (event: Event) {
229     event.preventDefault()
230     this.videoDownloadModal.show()
231   }
232
233   isUserLoggedIn () {
234     return this.authService.isLoggedIn()
235   }
236
237   isVideoUpdatable () {
238     return this.video.isUpdatableBy(this.authService.getUser())
239   }
240
241   isVideoBlacklistable () {
242     return this.video.isBlackistableBy(this.user)
243   }
244
245   getVideoPoster () {
246     if (!this.video) return ''
247
248     return this.video.previewUrl
249   }
250
251   getVideoTags () {
252     if (!this.video || Array.isArray(this.video.tags) === false) return []
253
254     return this.video.tags
255   }
256
257   isVideoRemovable () {
258     return this.video.isRemovableBy(this.authService.getUser())
259   }
260
261   async removeVideo (event: Event) {
262     event.preventDefault()
263
264     const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
265     if (res === false) return
266
267     this.videoService.removeVideo(this.video.id)
268         .subscribe(
269           status => {
270             this.notificationsService.success(
271               this.i18n('Success'),
272               this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
273             )
274
275             // Go back to the video-list.
276             this.redirectService.redirectToHomepage()
277           },
278
279           error => this.notificationsService.error(this.i18n('Error'), error.message)
280         )
281   }
282
283   acceptedPrivacyConcern () {
284     peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
285     this.hasAlreadyAcceptedPrivacyConcern = true
286   }
287
288   isVideoToTranscode () {
289     return this.video && this.video.state.id === VideoState.TO_TRANSCODE
290   }
291
292   isVideoToImport () {
293     return this.video && this.video.state.id === VideoState.TO_IMPORT
294   }
295
296   hasVideoScheduledPublication () {
297     return this.video && this.video.scheduledUpdate !== undefined
298   }
299
300   private updateVideoDescription (description: string) {
301     this.video.description = description
302     this.setVideoDescriptionHTML()
303   }
304
305   private setVideoDescriptionHTML () {
306     this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
307   }
308
309   private setVideoLikesBarTooltipText () {
310     this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
311       likesNumber: this.video.likes,
312       dislikesNumber: this.video.dislikes
313     })
314   }
315
316   private handleError (err: any) {
317     const errorMessage: string = typeof err === 'string' ? err : err.message
318     if (!errorMessage) return
319
320     // Display a message in the video player instead of a notification
321     if (errorMessage.indexOf('from xs param') !== -1) {
322       this.flushPlayer()
323       this.remoteServerDown = true
324       this.changeDetector.detectChanges()
325
326       return
327     }
328
329     this.notificationsService.error(this.i18n('Error'), errorMessage)
330   }
331
332   private checkUserRating () {
333     // Unlogged users do not have ratings
334     if (this.isUserLoggedIn() === false) return
335
336     this.videoService.getUserVideoRating(this.video.id)
337         .subscribe(
338           ratingObject => {
339             if (ratingObject) {
340               this.userRating = ratingObject.rating
341             }
342           },
343
344           err => this.notificationsService.error(this.i18n('Error'), err.message)
345         )
346   }
347
348   private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
349     this.video = video
350
351     // Re init attributes
352     this.descriptionLoading = false
353     this.completeDescriptionShown = false
354     this.remoteServerDown = false
355
356     this.updateOtherVideosDisplayed()
357
358     if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
359       const res = await this.confirmService.confirm(
360         this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
361         this.i18n('Mature or explicit content')
362       )
363       if (res === false) return this.redirectService.redirectToHomepage()
364     }
365
366     // Flush old player if needed
367     this.flushPlayer()
368
369     // Build video element, because videojs remove it on dispose
370     const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
371     this.playerElement = document.createElement('video')
372     this.playerElement.className = 'video-js vjs-peertube-skin'
373     this.playerElement.setAttribute('playsinline', 'true')
374     playerElementWrapper.appendChild(this.playerElement)
375
376     const playerCaptions = videoCaptions.map(c => ({
377       label: c.language.label,
378       language: c.language.id,
379       src: environment.apiUrl + c.captionPath
380     }))
381
382     const videojsOptions = getVideojsOptions({
383       autoplay: this.isAutoplay(),
384       inactivityTimeout: 2500,
385       videoFiles: this.video.files,
386       videoCaptions: playerCaptions,
387       playerElement: this.playerElement,
388       videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
389       videoDuration: this.video.duration,
390       enableHotkeys: true,
391       peertubeLink: false,
392       poster: this.video.previewUrl,
393       startTime,
394       theaterMode: true
395     })
396
397     if (this.videojsLocaleLoaded === false) {
398       await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
399       this.videojsLocaleLoaded = true
400     }
401
402     const self = this
403     this.zone.runOutsideAngular(async () => {
404       videojs(this.playerElement, videojsOptions, function () {
405         self.player = this
406         this.on('customError', (event, data) => self.handleError(data.err))
407
408         addContextMenu(self.player, self.video.embedUrl)
409       })
410     })
411
412     this.setVideoDescriptionHTML()
413     this.setVideoLikesBarTooltipText()
414
415     this.setOpenGraphTags()
416     this.checkUserRating()
417   }
418
419   private setRating (nextRating) {
420     let method
421     switch (nextRating) {
422       case 'like':
423         method = this.videoService.setVideoLike
424         break
425       case 'dislike':
426         method = this.videoService.setVideoDislike
427         break
428       case 'none':
429         method = this.videoService.unsetVideoLike
430         break
431     }
432
433     method.call(this.videoService, this.video.id)
434           .subscribe(
435             () => {
436               // Update the video like attribute
437               this.updateVideoRating(this.userRating, nextRating)
438               this.userRating = nextRating
439             },
440
441             err => this.notificationsService.error(this.i18n('Error'), err.message)
442           )
443   }
444
445   private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
446     let likesToIncrement = 0
447     let dislikesToIncrement = 0
448
449     if (oldRating) {
450       if (oldRating === 'like') likesToIncrement--
451       if (oldRating === 'dislike') dislikesToIncrement--
452     }
453
454     if (newRating === 'like') likesToIncrement++
455     if (newRating === 'dislike') dislikesToIncrement++
456
457     this.video.likes += likesToIncrement
458     this.video.dislikes += dislikesToIncrement
459
460     this.video.buildLikeAndDislikePercents()
461     this.setVideoLikesBarTooltipText()
462   }
463
464   private updateOtherVideosDisplayed () {
465     if (this.video && this.otherVideos && this.otherVideos.length > 0) {
466       this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
467     }
468   }
469
470   private setOpenGraphTags () {
471     this.metaService.setTitle(this.video.name)
472
473     this.metaService.setTag('og:type', 'video')
474
475     this.metaService.setTag('og:title', this.video.name)
476     this.metaService.setTag('name', this.video.name)
477
478     this.metaService.setTag('og:description', this.video.description)
479     this.metaService.setTag('description', this.video.description)
480
481     this.metaService.setTag('og:image', this.video.previewPath)
482
483     this.metaService.setTag('og:duration', this.video.duration.toString())
484
485     this.metaService.setTag('og:site_name', 'PeerTube')
486
487     this.metaService.setTag('og:url', window.location.href)
488     this.metaService.setTag('url', window.location.href)
489   }
490
491   private isAutoplay () {
492     // We'll jump to the thread id, so do not play the video
493     if (this.route.snapshot.params['threadId']) return false
494
495     // Otherwise true by default
496     if (!this.user) return true
497
498     // Be sure the autoPlay is set to false
499     return this.user.autoPlayVideo !== false
500   }
501
502   private flushPlayer () {
503     // Remove player if it exists
504     if (this.player) {
505       this.player.dispose()
506       this.player = undefined
507     }
508   }
509 }