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