]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Merge branch 'develop' into pr/1217
[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 isVideoDownloadable () {
312 return this.video && this.video.downloadEnabled
313 }
314
315 isVideoToImport () {
316 return this.video && this.video.state.id === VideoState.TO_IMPORT
317 }
318
319 hasVideoScheduledPublication () {
320 return this.video && this.video.scheduledUpdate !== undefined
321 }
322
323 private updateVideoDescription (description: string) {
324 this.video.description = description
325 this.setVideoDescriptionHTML()
326 }
327
328 private setVideoDescriptionHTML () {
329 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
330 }
331
332 private setVideoLikesBarTooltipText () {
333 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
334 likesNumber: this.video.likes,
335 dislikesNumber: this.video.dislikes
336 })
337 }
338
339 private handleError (err: any) {
340 const errorMessage: string = typeof err === 'string' ? err : err.message
341 if (!errorMessage) return
342
343 // Display a message in the video player instead of a notification
344 if (errorMessage.indexOf('from xs param') !== -1) {
345 this.flushPlayer()
346 this.remoteServerDown = true
347 this.changeDetector.detectChanges()
348
349 return
350 }
351
352 this.notifier.error(errorMessage)
353 }
354
355 private checkUserRating () {
356 // Unlogged users do not have ratings
357 if (this.isUserLoggedIn() === false) return
358
359 this.videoService.getUserVideoRating(this.video.id)
360 .subscribe(
361 ratingObject => {
362 if (ratingObject) {
363 this.userRating = ratingObject.rating
364 }
365 },
366
367 err => this.notifier.error(err.message)
368 )
369 }
370
371 private async onVideoFetched (
372 video: VideoDetails,
373 videoCaptions: VideoCaption[],
374 urlOptions: { startTime?: number, subtitle?: string, playerMode?: string }
375 ) {
376 this.video = video
377
378 // Re init attributes
379 this.descriptionLoading = false
380 this.completeDescriptionShown = false
381 this.remoteServerDown = false
382
383 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
384 // If we are at the end of the video, reset the timer
385 if (this.video.duration - startTime <= 1) startTime = 0
386
387 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
388 const res = await this.confirmService.confirm(
389 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
390 this.i18n('Mature or explicit content')
391 )
392 if (res === false) return this.redirectService.redirectToHomepage()
393 }
394
395 // Flush old player if needed
396 this.flushPlayer()
397
398 // Build video element, because videojs remove it on dispose
399 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
400 this.playerElement = document.createElement('video')
401 this.playerElement.className = 'video-js vjs-peertube-skin'
402 this.playerElement.setAttribute('playsinline', 'true')
403 playerElementWrapper.appendChild(this.playerElement)
404
405 const playerCaptions = videoCaptions.map(c => ({
406 label: c.language.label,
407 language: c.language.id,
408 src: environment.apiUrl + c.captionPath
409 }))
410
411 const options: PeertubePlayerManagerOptions = {
412 common: {
413 autoplay: this.isAutoplay(),
414
415 playerElement: this.playerElement,
416 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
417
418 videoDuration: this.video.duration,
419 enableHotkeys: true,
420 inactivityTimeout: 2500,
421 poster: this.video.previewUrl,
422 startTime,
423
424 theaterMode: true,
425 captions: videoCaptions.length !== 0,
426 peertubeLink: false,
427
428 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
429 embedUrl: this.video.embedUrl,
430
431 language: this.localeId,
432
433 subtitle: urlOptions.subtitle,
434
435 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
436 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
437 authorizationHeader: this.authService.getRequestHeaderValue()
438 } : undefined,
439
440 serverUrl: environment.apiUrl,
441
442 videoCaptions: playerCaptions
443 },
444
445 webtorrent: {
446 videoFiles: this.video.files
447 }
448 }
449
450 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
451
452 if (mode === 'p2p-media-loader') {
453 const hlsPlaylist = this.video.getHlsPlaylist()
454
455 const p2pMediaLoader = {
456 playlistUrl: hlsPlaylist.playlistUrl,
457 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
458 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
459 trackerAnnounce: this.video.trackerUrls,
460 videoFiles: this.video.files
461 } as P2PMediaLoaderOptions
462
463 Object.assign(options, { p2pMediaLoader })
464 }
465
466 this.zone.runOutsideAngular(async () => {
467 this.player = await PeertubePlayerManager.initialize(mode, options)
468 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
469 })
470
471 this.setVideoDescriptionHTML()
472 this.setVideoLikesBarTooltipText()
473
474 this.setOpenGraphTags()
475 this.checkUserRating()
476 }
477
478 private setRating (nextRating: UserVideoRateType) {
479 let method
480 switch (nextRating) {
481 case 'like':
482 method = this.videoService.setVideoLike
483 break
484 case 'dislike':
485 method = this.videoService.setVideoDislike
486 break
487 case 'none':
488 method = this.videoService.unsetVideoLike
489 break
490 }
491
492 method.call(this.videoService, this.video.id)
493 .subscribe(
494 () => {
495 // Update the video like attribute
496 this.updateVideoRating(this.userRating, nextRating)
497 this.userRating = nextRating
498 },
499
500 (err: { message: string }) => this.notifier.error(err.message)
501 )
502 }
503
504 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
505 let likesToIncrement = 0
506 let dislikesToIncrement = 0
507
508 if (oldRating) {
509 if (oldRating === 'like') likesToIncrement--
510 if (oldRating === 'dislike') dislikesToIncrement--
511 }
512
513 if (newRating === 'like') likesToIncrement++
514 if (newRating === 'dislike') dislikesToIncrement++
515
516 this.video.likes += likesToIncrement
517 this.video.dislikes += dislikesToIncrement
518
519 this.video.buildLikeAndDislikePercents()
520 this.setVideoLikesBarTooltipText()
521 }
522
523 private setOpenGraphTags () {
524 this.metaService.setTitle(this.video.name)
525
526 this.metaService.setTag('og:type', 'video')
527
528 this.metaService.setTag('og:title', this.video.name)
529 this.metaService.setTag('name', this.video.name)
530
531 this.metaService.setTag('og:description', this.video.description)
532 this.metaService.setTag('description', this.video.description)
533
534 this.metaService.setTag('og:image', this.video.previewPath)
535
536 this.metaService.setTag('og:duration', this.video.duration.toString())
537
538 this.metaService.setTag('og:site_name', 'PeerTube')
539
540 this.metaService.setTag('og:url', window.location.href)
541 this.metaService.setTag('url', window.location.href)
542 }
543
544 private isAutoplay () {
545 // We'll jump to the thread id, so do not play the video
546 if (this.route.snapshot.params['threadId']) return false
547
548 // Otherwise true by default
549 if (!this.user) return true
550
551 // Be sure the autoPlay is set to false
552 return this.user.autoPlayVideo !== false
553 }
554
555 private flushPlayer () {
556 // Remove player if it exists
557 if (this.player) {
558 this.player.dispose()
559 this.player = undefined
560 }
561 }
562 }