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