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