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