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