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