]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/+video-watch/video-watch.component.ts
Localize player
[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
29 @Component({
30 selector: 'my-video-watch',
31 templateUrl: './video-watch.component.html',
32 styleUrls: [ './video-watch.component.scss' ]
33 })
34 export class VideoWatchComponent implements OnInit, OnDestroy {
35 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
36
37 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
38 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
39 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
40 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
41
42 otherVideosDisplayed: Video[] = []
43
44 player: videojs.Player
45 playerElement: HTMLVideoElement
46 userRating: UserVideoRateType = null
47 video: VideoDetails = null
48 videoNotFound = false
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 if (this.player) {
105 this.player.pause()
106 }
107
108 const uuid = routeParams['uuid']
109
110 // Video did not change
111 if (this.video && this.video.uuid === uuid) return
112 // Video did change
113 this.videoService
114 .getVideo(uuid)
115 .pipe(catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 404 ])))
116 .subscribe(
117 video => {
118 const startTime = this.route.snapshot.queryParams.start
119 this.onVideoFetched(video, startTime)
120 .catch(err => this.handleError(err))
121 },
122
123 error => {
124 this.videoNotFound = true
125 console.error(error)
126 }
127 )
128 })
129 }
130
131 ngOnDestroy () {
132 this.flushPlayer()
133
134 // Unsubscribe subscriptions
135 this.paramsSub.unsubscribe()
136 }
137
138 setLike () {
139 if (this.isUserLoggedIn() === false) return
140 if (this.userRating === 'like') {
141 // Already liked this video
142 this.setRating('none')
143 } else {
144 this.setRating('like')
145 }
146 }
147
148 setDislike () {
149 if (this.isUserLoggedIn() === false) return
150 if (this.userRating === 'dislike') {
151 // Already disliked this video
152 this.setRating('none')
153 } else {
154 this.setRating('dislike')
155 }
156 }
157
158 async blacklistVideo (event: Event) {
159 event.preventDefault()
160
161 const res = await this.confirmService.confirm(this.i18n('Do you really want to blacklist this video?'), this.i18n('Blacklist'))
162 if (res === false) return
163
164 this.videoBlacklistService.blacklistVideo(this.video.id)
165 .subscribe(
166 status => {
167 this.notificationsService.success(
168 this.i18n('Success'),
169 this.i18n('Video {{videoName}} had been blacklisted.', { videoName: this.video.name })
170 )
171 this.redirectService.redirectToHomepage()
172 },
173
174 error => this.notificationsService.error(this.i18n('Error'), error.message)
175 )
176 }
177
178 showMoreDescription () {
179 if (this.completeVideoDescription === undefined) {
180 return this.loadCompleteDescription()
181 }
182
183 this.updateVideoDescription(this.completeVideoDescription)
184 this.completeDescriptionShown = true
185 }
186
187 showLessDescription () {
188 this.updateVideoDescription(this.shortVideoDescription)
189 this.completeDescriptionShown = false
190 }
191
192 loadCompleteDescription () {
193 this.descriptionLoading = true
194
195 this.videoService.loadCompleteDescription(this.video.descriptionPath)
196 .subscribe(
197 description => {
198 this.completeDescriptionShown = true
199 this.descriptionLoading = false
200
201 this.shortVideoDescription = this.video.description
202 this.completeVideoDescription = description
203
204 this.updateVideoDescription(this.completeVideoDescription)
205 },
206
207 error => {
208 this.descriptionLoading = false
209 this.notificationsService.error(this.i18n('Error'), error.message)
210 }
211 )
212 }
213
214 showReportModal (event: Event) {
215 event.preventDefault()
216 this.videoReportModal.show()
217 }
218
219 showSupportModal () {
220 this.videoSupportModal.show()
221 }
222
223 showShareModal () {
224 this.videoShareModal.show()
225 }
226
227 showDownloadModal (event: Event) {
228 event.preventDefault()
229 this.videoDownloadModal.show()
230 }
231
232 isUserLoggedIn () {
233 return this.authService.isLoggedIn()
234 }
235
236 isVideoUpdatable () {
237 return this.video.isUpdatableBy(this.authService.getUser())
238 }
239
240 isVideoBlacklistable () {
241 return this.video.isBlackistableBy(this.user)
242 }
243
244 getVideoPoster () {
245 if (!this.video) return ''
246
247 return this.video.previewUrl
248 }
249
250 getVideoTags () {
251 if (!this.video || Array.isArray(this.video.tags) === false) return []
252
253 return this.video.tags.join(', ')
254 }
255
256 isVideoRemovable () {
257 return this.video.isRemovableBy(this.authService.getUser())
258 }
259
260 async removeVideo (event: Event) {
261 event.preventDefault()
262
263 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
264 if (res === false) return
265
266 this.videoService.removeVideo(this.video.id)
267 .subscribe(
268 status => {
269 this.notificationsService.success(
270 this.i18n('Success'),
271 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
272 )
273
274 // Go back to the video-list.
275 this.redirectService.redirectToHomepage()
276 },
277
278 error => this.notificationsService.error(this.i18n('Error'), error.message)
279 )
280 }
281
282 acceptedPrivacyConcern () {
283 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
284 this.hasAlreadyAcceptedPrivacyConcern = true
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(
303 '{{likesNumber}} likes / {{dislikesNumber}} dislikes',
304 { likesNumber: this.video.likes, dislikes: 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.videoService.getVideoViewUrl(this.video.uuid),
372 videoDuration: this.video.duration,
373 enableHotkeys: true,
374 peertubeLink: false,
375 poster: this.video.previewUrl,
376 startTime
377 })
378
379 if (this.videojsLocaleLoaded === false) {
380 await loadLocale(environment.apiUrl, videojs, environment.production === true ? this.localeId : 'fr')
381 this.videojsLocaleLoaded = true
382 }
383
384 const self = this
385 this.zone.runOutsideAngular(async () => {
386 videojs(this.playerElement, videojsOptions, function () {
387 self.player = this
388 this.on('customError', (event, data) => self.handleError(data.err))
389
390 addContextMenu(self.player, self.video.embedUrl)
391 })
392 })
393
394 this.setVideoDescriptionHTML()
395 this.setVideoLikesBarTooltipText()
396
397 this.setOpenGraphTags()
398 this.checkUserRating()
399 }
400
401 private setRating (nextRating) {
402 let method
403 switch (nextRating) {
404 case 'like':
405 method = this.videoService.setVideoLike
406 break
407 case 'dislike':
408 method = this.videoService.setVideoDislike
409 break
410 case 'none':
411 method = this.videoService.unsetVideoLike
412 break
413 }
414
415 method.call(this.videoService, this.video.id)
416 .subscribe(
417 () => {
418 // Update the video like attribute
419 this.updateVideoRating(this.userRating, nextRating)
420 this.userRating = nextRating
421 },
422 err => this.notificationsService.error(this.i18n('Error'), err.message)
423 )
424 }
425
426 private updateVideoRating (oldRating: UserVideoRateType, newRating: VideoRateType) {
427 let likesToIncrement = 0
428 let dislikesToIncrement = 0
429
430 if (oldRating) {
431 if (oldRating === 'like') likesToIncrement--
432 if (oldRating === 'dislike') dislikesToIncrement--
433 }
434
435 if (newRating === 'like') likesToIncrement++
436 if (newRating === 'dislike') dislikesToIncrement++
437
438 this.video.likes += likesToIncrement
439 this.video.dislikes += dislikesToIncrement
440
441 this.video.buildLikeAndDislikePercents()
442 this.setVideoLikesBarTooltipText()
443 }
444
445 private updateOtherVideosDisplayed () {
446 if (this.video && this.otherVideos && this.otherVideos.length > 0) {
447 this.otherVideosDisplayed = this.otherVideos.filter(v => v.uuid !== this.video.uuid)
448 }
449 }
450
451 private setOpenGraphTags () {
452 this.metaService.setTitle(this.video.name)
453
454 this.metaService.setTag('og:type', 'video')
455
456 this.metaService.setTag('og:title', this.video.name)
457 this.metaService.setTag('name', this.video.name)
458
459 this.metaService.setTag('og:description', this.video.description)
460 this.metaService.setTag('description', this.video.description)
461
462 this.metaService.setTag('og:image', this.video.previewPath)
463
464 this.metaService.setTag('og:duration', this.video.duration.toString())
465
466 this.metaService.setTag('og:site_name', 'PeerTube')
467
468 this.metaService.setTag('og:url', window.location.href)
469 this.metaService.setTag('url', window.location.href)
470 }
471
472 private isAutoplay () {
473 // True by default
474 if (!this.user) return true
475
476 // Be sure the autoPlay is set to false
477 return this.user.autoPlayVideo !== false
478 }
479
480 private flushPlayer () {
481 // Remove player if it exists
482 if (this.player) {
483 this.player.dispose()
484 this.player = undefined
485 }
486 }
487 }