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