]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Add blacklist reason field
[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 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ]))
125 )
126 .subscribe(([ video, captionsResult ]) => {
127 const startTime = this.route.snapshot.queryParams.start
128 this.onVideoFetched(video, captionsResult.data, startTime)
129 .catch(err => this.handleError(err))
130 })
131 })
132 }
133
134 ngOnDestroy () {
135 this.flushPlayer()
136
137 // Unsubscribe subscriptions
138 this.paramsSub.unsubscribe()
139 }
140
141 setLike () {
142 if (this.isUserLoggedIn() === false) return
143 if (this.userRating === 'like') {
144 // Already liked this video
145 this.setRating('none')
146 } else {
147 this.setRating('like')
148 }
149 }
150
151 setDislike () {
152 if (this.isUserLoggedIn() === false) return
153 if (this.userRating === 'dislike') {
154 // Already disliked this video
155 this.setRating('none')
156 } else {
157 this.setRating('dislike')
158 }
159 }
160
161 showMoreDescription () {
162 if (this.completeVideoDescription === undefined) {
163 return this.loadCompleteDescription()
164 }
165
166 this.updateVideoDescription(this.completeVideoDescription)
167 this.completeDescriptionShown = true
168 }
169
170 showLessDescription () {
171 this.updateVideoDescription(this.shortVideoDescription)
172 this.completeDescriptionShown = false
173 }
174
175 loadCompleteDescription () {
176 this.descriptionLoading = true
177
178 this.videoService.loadCompleteDescription(this.video.descriptionPath)
179 .subscribe(
180 description => {
181 this.completeDescriptionShown = true
182 this.descriptionLoading = false
183
184 this.shortVideoDescription = this.video.description
185 this.completeVideoDescription = description
186
187 this.updateVideoDescription(this.completeVideoDescription)
188 },
189
190 error => {
191 this.descriptionLoading = false
192 this.notificationsService.error(this.i18n('Error'), error.message)
193 }
194 )
195 }
196
197 showReportModal (event: Event) {
198 event.preventDefault()
199 this.videoReportModal.show()
200 }
201
202 showSupportModal () {
203 this.videoSupportModal.show()
204 }
205
206 showShareModal () {
207 this.videoShareModal.show()
208 }
209
210 showDownloadModal (event: Event) {
211 event.preventDefault()
212 this.videoDownloadModal.show()
213 }
214
215 showBlacklistModal (event: Event) {
216 event.preventDefault()
217 this.videoBlacklistModal.show()
218 }
219
220 isUserLoggedIn () {
221 return this.authService.isLoggedIn()
222 }
223
224 isVideoUpdatable () {
225 return this.video.isUpdatableBy(this.authService.getUser())
226 }
227
228 isVideoBlacklistable () {
229 return this.video.isBlackistableBy(this.user)
230 }
231
232 getVideoPoster () {
233 if (!this.video) return ''
234
235 return this.video.previewUrl
236 }
237
238 getVideoTags () {
239 if (!this.video || Array.isArray(this.video.tags) === false) return []
240
241 return this.video.tags
242 }
243
244 isVideoRemovable () {
245 return this.video.isRemovableBy(this.authService.getUser())
246 }
247
248 async removeVideo (event: Event) {
249 event.preventDefault()
250
251 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
252 if (res === false) return
253
254 this.videoService.removeVideo(this.video.id)
255 .subscribe(
256 status => {
257 this.notificationsService.success(
258 this.i18n('Success'),
259 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
260 )
261
262 // Go back to the video-list.
263 this.redirectService.redirectToHomepage()
264 },
265
266 error => this.notificationsService.error(this.i18n('Error'), error.message)
267 )
268 }
269
270 acceptedPrivacyConcern () {
271 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
272 this.hasAlreadyAcceptedPrivacyConcern = true
273 }
274
275 isVideoToTranscode () {
276 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
277 }
278
279 isVideoToImport () {
280 return this.video && this.video.state.id === VideoState.TO_IMPORT
281 }
282
283 hasVideoScheduledPublication () {
284 return this.video && this.video.scheduledUpdate !== undefined
285 }
286
287 private updateVideoDescription (description: string) {
288 this.video.description = description
289 this.setVideoDescriptionHTML()
290 }
291
292 private setVideoDescriptionHTML () {
293 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
294 }
295
296 private setVideoLikesBarTooltipText () {
297 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
298 likesNumber: this.video.likes,
299 dislikesNumber: this.video.dislikes
300 })
301 }
302
303 private handleError (err: any) {
304 const errorMessage: string = typeof err === 'string' ? err : err.message
305 if (!errorMessage) return
306
307 // Display a message in the video player instead of a notification
308 if (errorMessage.indexOf('from xs param') !== -1) {
309 this.flushPlayer()
310 this.remoteServerDown = true
311 this.changeDetector.detectChanges()
312
313 return
314 }
315
316 this.notificationsService.error(this.i18n('Error'), errorMessage)
317 }
318
319 private checkUserRating () {
320 // Unlogged users do not have ratings
321 if (this.isUserLoggedIn() === false) return
322
323 this.videoService.getUserVideoRating(this.video.id)
324 .subscribe(
325 ratingObject => {
326 if (ratingObject) {
327 this.userRating = ratingObject.rating
328 }
329 },
330
331 err => this.notificationsService.error(this.i18n('Error'), err.message)
332 )
333 }
334
335 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
336 this.video = video
337
338 // Re init attributes
339 this.descriptionLoading = false
340 this.completeDescriptionShown = false
341 this.remoteServerDown = false
342
343 this.updateOtherVideosDisplayed()
344
345 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
346 const res = await this.confirmService.confirm(
347 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
348 this.i18n('Mature or explicit content')
349 )
350 if (res === false) return this.redirectService.redirectToHomepage()
351 }
352
353 // Flush old player if needed
354 this.flushPlayer()
355
356 // Build video element, because videojs remove it on dispose
357 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
358 this.playerElement = document.createElement('video')
359 this.playerElement.className = 'video-js vjs-peertube-skin'
360 this.playerElement.setAttribute('playsinline', 'true')
361 playerElementWrapper.appendChild(this.playerElement)
362
363 const playerCaptions = videoCaptions.map(c => ({
364 label: c.language.label,
365 language: c.language.id,
366 src: environment.apiUrl + c.captionPath
367 }))
368
369 const videojsOptions = getVideojsOptions({
370 autoplay: this.isAutoplay(),
371 inactivityTimeout: 2500,
372 videoFiles: this.video.files,
373 videoCaptions: playerCaptions,
374 playerElement: this.playerElement,
375 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
376 videoDuration: this.video.duration,
377 enableHotkeys: true,
378 peertubeLink: false,
379 poster: this.video.previewUrl,
380 startTime,
381 theaterMode: true
382 })
383
384 if (this.videojsLocaleLoaded === false) {
385 await loadLocale(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
386 this.videojsLocaleLoaded = true
387 }
388
389 const self = this
390 this.zone.runOutsideAngular(async () => {
391 videojs(this.playerElement, videojsOptions, function () {
392 self.player = this
393 this.on('customError', (event, data) => self.handleError(data.err))
394
395 addContextMenu(self.player, self.video.embedUrl)
396 })
397 })
398
399 this.setVideoDescriptionHTML()
400 this.setVideoLikesBarTooltipText()
401
402 this.setOpenGraphTags()
403 this.checkUserRating()
404 }
405
406 private setRating (nextRating) {
407 let method
408 switch (nextRating) {
409 case 'like':
410 method = this.videoService.setVideoLike
411 break
412 case 'dislike':
413 method = this.videoService.setVideoDislike
414 break
415 case 'none':
416 method = this.videoService.unsetVideoLike
417 break
418 }
419
420 method.call(this.videoService, this.video.id)
421 .subscribe(
422 () => {
423 // Update the video like attribute
424 this.updateVideoRating(this.userRating, nextRating)
425 this.userRating = nextRating
426 },
427
428 err => this.notificationsService.error(this.i18n('Error'), err.message)
429 )
430 }
431
432 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
433 let likesToIncrement = 0
434 let dislikesToIncrement = 0
435
436 if (oldRating) {
437 if (oldRating === 'like') likesToIncrement--
438 if (oldRating === 'dislike') dislikesToIncrement--
439 }
440
441 if (newRating === 'like') likesToIncrement++
442 if (newRating === 'dislike') dislikesToIncrement++
443
444 this.video.likes += likesToIncrement
445 this.video.dislikes += dislikesToIncrement
446
447 this.video.buildLikeAndDislikePercents()
448 this.setVideoLikesBarTooltipText()
449 }
450
451 private updateOtherVideosDisplayed () {
452 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
453 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
454 }
455 }
456
457 private setOpenGraphTags () {
458 this.metaService.setTitle(this.video.name)
459
460 this.metaService.setTag('og:type', 'video')
461
462 this.metaService.setTag('og:title', this.video.name)
463 this.metaService.setTag('name', this.video.name)
464
465 this.metaService.setTag('og:description', this.video.description)
466 this.metaService.setTag('description', this.video.description)
467
468 this.metaService.setTag('og:image', this.video.previewPath)
469
470 this.metaService.setTag('og:duration', this.video.duration.toString())
471
472 this.metaService.setTag('og:site_name', 'PeerTube')
473
474 this.metaService.setTag('og:url', window.location.href)
475 this.metaService.setTag('url', window.location.href)
476 }
477
478 private isAutoplay () {
479 // We'll jump to the thread id, so do not play the video
480 if (this.route.snapshot.params['threadId']) return false
481
482 // Otherwise true by default
483 if (!this.user) return true
484
485 // Be sure the autoPlay is set to false
486 return this.user.autoPlayVideo !== false
487 }
488
489 private flushPlayer () {
490 // Remove player if it exists
491 if (this.player) {
492 this.player.dispose()
493 this.player = undefined
494 }
495 }
496 }