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