]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
4a67d456e164957e4847ea5b61fd28625a9fb8f2
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / +video-watch / video-watch.component.ts
1 import { catchError } from 'rxjs/operators'
2 import { Component, ElementRef, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild, Inject } 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, VideoRateType } 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 { getVideojsOptions, loadLocale, addContextMenu } 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 videoNotFound = false
50 descriptionLoading = false
51
52 completeDescriptionShown = false
53 completeVideoDescription: string
54 shortVideoDescription: string
55 videoHTMLDescription = ''
56 likesBarTooltipText = ''
57 hasAlreadyAcceptedPrivacyConcern = false
58
59 private videojsLocaleLoaded = false
60 private otherVideos: Video[] = []
61 private paramsSub: Subscription
62
63 constructor (
64 private elementRef: ElementRef,
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 i18n: I18n,
79 @Inject(LOCALE_ID) private localeId: string
80 ) {}
81
82 get user () {
83 return this.authService.getUser()
84 }
85
86 ngOnInit () {
87 if (
88 WebTorrent.WEBRTC_SUPPORT === false ||
89 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
90 ) {
91 this.hasAlreadyAcceptedPrivacyConcern = true
92 }
93
94 this.videoService.getVideos({ currentPage: 1, itemsPerPage: 5 }, '-createdAt')
95 .subscribe(
96 data => {
97 this.otherVideos = data.videos
98 this.updateOtherVideosDisplayed()
99 },
100
101 err => console.error(err)
102 )
103
104 this.paramsSub = this.route.params.subscribe(routeParams => {
105 if (this.player) {
106 this.player.pause()
107 }
108
109 const uuid = routeParams['uuid']
110
111 // Video did not change
112 if (this.video && this.video.uuid === uuid) return
113 // Video did change
114 this.videoService
115 .getVideo(uuid)
116 .pipe(catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ])))
117 .subscribe(
118 video => {
119 const startTime = this.route.snapshot.queryParams.start
120 this.onVideoFetched(video, startTime)
121 .catch(err => this.handleError(err))
122 },
123
124 error => {
125 this.videoNotFound = true
126 console.error(error)
127 }
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 status => {
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.join(', ')
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 private updateVideoDescription (description: string) {
289 this.video.description = description
290 this.setVideoDescriptionHTML()
291 }
292
293 private setVideoDescriptionHTML () {
294 if (!this.video.description) {
295 this.videoHTMLDescription = ''
296 return
297 }
298
299 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
300 }
301
302 private setVideoLikesBarTooltipText () {
303 this.likesBarTooltipText = this.i18n(
304 '{{likesNumber}} likes / {{dislikesNumber}} dislikes',
305 { likesNumber: this.video.likes, dislikes: this.video.dislikes }
306 )
307 }
308
309 private handleError (err: any) {
310 const errorMessage: string = typeof err === 'string' ? err : err.message
311 if (!errorMessage) return
312
313 let message = ''
314
315 if (errorMessage.indexOf('http error') !== -1) {
316 message = this.i18n('Cannot fetch video from server, maybe down.')
317 } else {
318 message = errorMessage
319 }
320
321 this.notificationsService.error(this.i18n('Error'), message)
322 }
323
324 private checkUserRating () {
325 // Unlogged users do not have ratings
326 if (this.isUserLoggedIn() === false) return
327
328 this.videoService.getUserVideoRating(this.video.id)
329 .subscribe(
330 ratingObject => {
331 if (ratingObject) {
332 this.userRating = ratingObject.rating
333 }
334 },
335
336 err => this.notificationsService.error(this.i18n('Error'), err.message)
337 )
338 }
339
340 private async onVideoFetched (video: VideoDetails, startTime = 0) {
341 this.video = video
342
343 // Re init attributes
344 this.descriptionLoading = false
345 this.completeDescriptionShown = false
346
347 this.updateOtherVideosDisplayed()
348
349 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
350 const res = await this.confirmService.confirm(
351 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
352 this.i18n('Mature or explicit content')
353 )
354 if (res === false) return this.redirectService.redirectToHomepage()
355 }
356
357 // Flush old player if needed
358 this.flushPlayer()
359
360 // Build video element, because videojs remove it on dispose
361 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
362 this.playerElement = document.createElement('video')
363 this.playerElement.className = 'video-js vjs-peertube-skin'
364 this.playerElement.setAttribute('playsinline', 'true')
365 playerElementWrapper.appendChild(this.playerElement)
366
367 const videojsOptions = getVideojsOptions({
368 autoplay: this.isAutoplay(),
369 inactivityTimeout: 2500,
370 videoFiles: this.video.files,
371 playerElement: this.playerElement,
372 videoViewUrl: this.videoService.getVideoViewUrl(this.video.uuid),
373 videoDuration: this.video.duration,
374 enableHotkeys: true,
375 peertubeLink: false,
376 poster: this.video.previewUrl,
377 startTime
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 err => this.notificationsService.error(this.i18n('Error'), err.message)
424 )
425 }
426
427 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
428 let likesToIncrement = 0
429 let dislikesToIncrement = 0
430
431 if (oldRating) {
432 if (oldRating === 'like') likesToIncrement--
433 if (oldRating === 'dislike') dislikesToIncrement--
434 }
435
436 if (newRating === 'like') likesToIncrement++
437 if (newRating === 'dislike') dislikesToIncrement++
438
439 this.video.likes += likesToIncrement
440 this.video.dislikes += dislikesToIncrement
441
442 this.video.buildLikeAndDislikePercents()
443 this.setVideoLikesBarTooltipText()
444 }
445
446 private updateOtherVideosDisplayed () {
447 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
448 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
449 }
450 }
451
452 private setOpenGraphTags () {
453 this.metaService.setTitle(this.video.name)
454
455 this.metaService.setTag('og:type', 'video')
456
457 this.metaService.setTag('og:title', this.video.name)
458 this.metaService.setTag('name', this.video.name)
459
460 this.metaService.setTag('og:description', this.video.description)
461 this.metaService.setTag('description', this.video.description)
462
463 this.metaService.setTag('og:image', this.video.previewPath)
464
465 this.metaService.setTag('og:duration', this.video.duration.toString())
466
467 this.metaService.setTag('og:site_name', 'PeerTube')
468
469 this.metaService.setTag('og:url', window.location.href)
470 this.metaService.setTag('url', window.location.href)
471 }
472
473 private isAutoplay () {
474 // True by default
475 if (!this.user) return true
476
477 // Be sure the autoPlay is set to false
478 return this.user.autoPlayVideo !== false
479 }
480
481 private flushPlayer () {
482 // Remove player if it exists
483 if (this.player) {
484 this.player.dispose()
485 this.player = undefined
486 }
487 }
488 }