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