]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
25643cfded64a9b0fd28ac0eeca563fc632d9686
[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, VideoCaption, 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 { VideoService } from '../../shared/video/video.service'
19 import { MarkdownService } from '../shared'
20 import { VideoDownloadComponent } from './modal/video-download.component'
21 import { VideoReportComponent } from './modal/video-report.component'
22 import { VideoShareComponent } from './modal/video-share.component'
23 import { VideoBlacklistComponent } from './modal/video-blacklist.component'
24 import { addContextMenu, getVideojsOptions, loadLocaleInVideoJS } 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
31 @Component({
32 selector: 'my-video-watch',
33 templateUrl: './video-watch.component.html',
34 styleUrls: [ './video-watch.component.scss' ]
35 })
36 export class VideoWatchComponent implements OnInit, OnDestroy {
37 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
38
39 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
40 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
41 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
42 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
43 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
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 remoteServerDown = false
58
59 private videojsLocaleLoaded = false
60 private paramsSub: Subscription
61
62 constructor (
63 private elementRef: ElementRef,
64 private changeDetector: ChangeDetectorRef,
65 private route: ActivatedRoute,
66 private router: Router,
67 private videoService: VideoService,
68 private videoBlacklistService: VideoBlacklistService,
69 private confirmService: ConfirmService,
70 private metaService: MetaService,
71 private authService: AuthService,
72 private serverService: ServerService,
73 private restExtractor: RestExtractor,
74 private notificationsService: NotificationsService,
75 private markdownService: MarkdownService,
76 private zone: NgZone,
77 private redirectService: RedirectService,
78 private videoCaptionService: VideoCaptionService,
79 private i18n: I18n,
80 @Inject(LOCALE_ID) private localeId: string
81 ) {}
82
83 get user () {
84 return this.authService.getUser()
85 }
86
87 ngOnInit () {
88 if (
89 WebTorrent.WEBRTC_SUPPORT === false ||
90 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
91 ) {
92 this.hasAlreadyAcceptedPrivacyConcern = true
93 }
94
95 this.paramsSub = this.route.params.subscribe(routeParams => {
96 const uuid = routeParams[ 'uuid' ]
97
98 // Video did not change
99 if (this.video && this.video.uuid === uuid) return
100
101 if (this.player) this.player.pause()
102
103 // Video did change
104 forkJoin(
105 this.videoService.getVideo(uuid),
106 this.videoCaptionService.listCaptions(uuid)
107 )
108 .pipe(
109 // If 401, the video is private or blacklisted so redirect to 404
110 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 404 ]))
111 )
112 .subscribe(([ video, captionsResult ]) => {
113 const startTime = this.route.snapshot.queryParams.start
114 this.onVideoFetched(video, captionsResult.data, startTime)
115 .catch(err => this.handleError(err))
116 })
117 })
118 }
119
120 ngOnDestroy () {
121 this.flushPlayer()
122
123 // Unsubscribe subscriptions
124 this.paramsSub.unsubscribe()
125 }
126
127 setLike () {
128 if (this.isUserLoggedIn() === false) return
129 if (this.userRating === 'like') {
130 // Already liked this video
131 this.setRating('none')
132 } else {
133 this.setRating('like')
134 }
135 }
136
137 setDislike () {
138 if (this.isUserLoggedIn() === false) return
139 if (this.userRating === 'dislike') {
140 // Already disliked this video
141 this.setRating('none')
142 } else {
143 this.setRating('dislike')
144 }
145 }
146
147 showMoreDescription () {
148 if (this.completeVideoDescription === undefined) {
149 return this.loadCompleteDescription()
150 }
151
152 this.updateVideoDescription(this.completeVideoDescription)
153 this.completeDescriptionShown = true
154 }
155
156 showLessDescription () {
157 this.updateVideoDescription(this.shortVideoDescription)
158 this.completeDescriptionShown = false
159 }
160
161 loadCompleteDescription () {
162 this.descriptionLoading = true
163
164 this.videoService.loadCompleteDescription(this.video.descriptionPath)
165 .subscribe(
166 description => {
167 this.completeDescriptionShown = true
168 this.descriptionLoading = false
169
170 this.shortVideoDescription = this.video.description
171 this.completeVideoDescription = description
172
173 this.updateVideoDescription(this.completeVideoDescription)
174 },
175
176 error => {
177 this.descriptionLoading = false
178 this.notificationsService.error(this.i18n('Error'), error.message)
179 }
180 )
181 }
182
183 showReportModal (event: Event) {
184 event.preventDefault()
185 this.videoReportModal.show()
186 }
187
188 showSupportModal () {
189 this.videoSupportModal.show()
190 }
191
192 showShareModal () {
193 const currentTime = this.player ? this.player.currentTime() : undefined
194
195 this.videoShareModal.show(currentTime)
196 }
197
198 showDownloadModal (event: Event) {
199 event.preventDefault()
200 this.videoDownloadModal.show()
201 }
202
203 showBlacklistModal (event: Event) {
204 event.preventDefault()
205 this.videoBlacklistModal.show()
206 }
207
208 async unblacklistVideo (event: Event) {
209 event.preventDefault()
210
211 const confirmMessage = this.i18n(
212 'Do you really want to remove this video from the blacklist? It will be available again in the videos list.'
213 )
214
215 const res = await this.confirmService.confirm(confirmMessage, this.i18n('Unblacklist'))
216 if (res === false) return
217
218 this.videoBlacklistService.removeVideoFromBlacklist(this.video.id).subscribe(
219 () => {
220 this.notificationsService.success(
221 this.i18n('Success'),
222 this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name })
223 )
224
225 this.video.blacklisted = false
226 this.video.blacklistedReason = null
227 },
228
229 err => this.notificationsService.error(this.i18n('Error'), err.message)
230 )
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 isVideoUnblacklistable () {
246 return this.video.isUnblacklistableBy(this.user)
247 }
248
249 getVideoTags () {
250 if (!this.video || Array.isArray(this.video.tags) === false) return []
251
252 return this.video.tags
253 }
254
255 isVideoRemovable () {
256 return this.video.isRemovableBy(this.authService.getUser())
257 }
258
259 async removeVideo (event: Event) {
260 event.preventDefault()
261
262 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
263 if (res === false) return
264
265 this.videoService.removeVideo(this.video.id)
266 .subscribe(
267 status => {
268 this.notificationsService.success(
269 this.i18n('Success'),
270 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
271 )
272
273 // Go back to the video-list.
274 this.redirectService.redirectToHomepage()
275 },
276
277 error => this.notificationsService.error(this.i18n('Error'), error.message)
278 )
279 }
280
281 acceptedPrivacyConcern () {
282 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
283 this.hasAlreadyAcceptedPrivacyConcern = true
284 }
285
286 isVideoToTranscode () {
287 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
288 }
289
290 isVideoToImport () {
291 return this.video && this.video.state.id === VideoState.TO_IMPORT
292 }
293
294 hasVideoScheduledPublication () {
295 return this.video && this.video.scheduledUpdate !== undefined
296 }
297
298 private updateVideoDescription (description: string) {
299 this.video.description = description
300 this.setVideoDescriptionHTML()
301 }
302
303 private setVideoDescriptionHTML () {
304 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
305 }
306
307 private setVideoLikesBarTooltipText () {
308 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
309 likesNumber: this.video.likes,
310 dislikesNumber: this.video.dislikes
311 })
312 }
313
314 private handleError (err: any) {
315 const errorMessage: string = typeof err === 'string' ? err : err.message
316 if (!errorMessage) return
317
318 // Display a message in the video player instead of a notification
319 if (errorMessage.indexOf('from xs param') !== -1) {
320 this.flushPlayer()
321 this.remoteServerDown = true
322 this.changeDetector.detectChanges()
323
324 return
325 }
326
327 this.notificationsService.error(this.i18n('Error'), errorMessage)
328 }
329
330 private checkUserRating () {
331 // Unlogged users do not have ratings
332 if (this.isUserLoggedIn() === false) return
333
334 this.videoService.getUserVideoRating(this.video.id)
335 .subscribe(
336 ratingObject => {
337 if (ratingObject) {
338 this.userRating = ratingObject.rating
339 }
340 },
341
342 err => this.notificationsService.error(this.i18n('Error'), err.message)
343 )
344 }
345
346 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTime = 0) {
347 this.video = video
348
349 // Re init attributes
350 this.descriptionLoading = false
351 this.completeDescriptionShown = false
352 this.remoteServerDown = false
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 language: this.localeId
392 })
393
394 if (this.videojsLocaleLoaded === false) {
395 await loadLocaleInVideoJS(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
396 this.videojsLocaleLoaded = true
397 }
398
399 const self = this
400 this.zone.runOutsideAngular(async () => {
401 videojs(this.playerElement, videojsOptions, function () {
402 self.player = this
403 this.on('customError', (event, data) => self.handleError(data.err))
404
405 addContextMenu(self.player, self.video.embedUrl)
406 })
407 })
408
409 this.setVideoDescriptionHTML()
410 this.setVideoLikesBarTooltipText()
411
412 this.setOpenGraphTags()
413 this.checkUserRating()
414 }
415
416 private setRating (nextRating) {
417 let method
418 switch (nextRating) {
419 case 'like':
420 method = this.videoService.setVideoLike
421 break
422 case 'dislike':
423 method = this.videoService.setVideoDislike
424 break
425 case 'none':
426 method = this.videoService.unsetVideoLike
427 break
428 }
429
430 method.call(this.videoService, this.video.id)
431 .subscribe(
432 () => {
433 // Update the video like attribute
434 this.updateVideoRating(this.userRating, nextRating)
435 this.userRating = nextRating
436 },
437
438 err => this.notificationsService.error(this.i18n('Error'), err.message)
439 )
440 }
441
442 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
443 let likesToIncrement = 0
444 let dislikesToIncrement = 0
445
446 if (oldRating) {
447 if (oldRating === 'like') likesToIncrement--
448 if (oldRating === 'dislike') dislikesToIncrement--
449 }
450
451 if (newRating === 'like') likesToIncrement++
452 if (newRating === 'dislike') dislikesToIncrement++
453
454 this.video.likes += likesToIncrement
455 this.video.dislikes += dislikesToIncrement
456
457 this.video.buildLikeAndDislikePercents()
458 this.setVideoLikesBarTooltipText()
459 }
460
461 private setOpenGraphTags () {
462 this.metaService.setTitle(this.video.name)
463
464 this.metaService.setTag('og:type', 'video')
465
466 this.metaService.setTag('og:title', this.video.name)
467 this.metaService.setTag('name', this.video.name)
468
469 this.metaService.setTag('og:description', this.video.description)
470 this.metaService.setTag('description', this.video.description)
471
472 this.metaService.setTag('og:image', this.video.previewPath)
473
474 this.metaService.setTag('og:duration', this.video.duration.toString())
475
476 this.metaService.setTag('og:site_name', 'PeerTube')
477
478 this.metaService.setTag('og:url', window.location.href)
479 this.metaService.setTag('url', window.location.href)
480 }
481
482 private isAutoplay () {
483 // We'll jump to the thread id, so do not play the video
484 if (this.route.snapshot.params['threadId']) return false
485
486 // Otherwise true by default
487 if (!this.user) return true
488
489 // Be sure the autoPlay is set to false
490 return this.user.autoPlayVideo !== false
491 }
492
493 private flushPlayer () {
494 // Remove player if it exists
495 if (this.player) {
496 this.player.dispose()
497 this.player = undefined
498 }
499 }
500 }