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