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