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