]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - 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
CommitLineData
e972e046 1import { catchError } from 'rxjs/operators'
3b492bff 2import { ChangeDetectorRef, Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'
df98563e 3import { ActivatedRoute, Router } from '@angular/router'
901637bb 4import { RedirectService } from '@app/core/routing/redirect.service'
0bd78bf3 5import { peertubeLocalStorage } from '@app/shared/misc/peertube-local-storage'
07fa4c97 6import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
1f3e9fec 7import { MetaService } from '@ngx-meta/core'
f8b2c1b4 8import { Notifier, ServerService } from '@app/core'
16f7022b 9import { forkJoin, Subscription } from 'rxjs'
20d21199 10import { Hotkey, HotkeysService } from 'angular2-hotkeys'
caae7a06 11import * as WebTorrent from 'webtorrent'
f8b2c1b4 12import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
df98563e 13import { AuthService, ConfirmService } from '../../core'
a51bad1a 14import { RestExtractor, VideoBlacklistService } from '../../shared'
ff249f49 15import { VideoDetails } from '../../shared/video/video-details.model'
63c4db6d 16import { VideoService } from '../../shared/video/video.service'
4635f59d
C
17import { VideoDownloadComponent } from './modal/video-download.component'
18import { VideoReportComponent } from './modal/video-report.component'
19import { VideoShareComponent } from './modal/video-share.component'
26b7305a 20import { VideoBlacklistComponent } from './modal/video-blacklist.component'
20d21199 21import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
989e526a 22import { I18n } from '@ngx-translate/i18n-polyfill'
e945b184 23import { environment } from '../../../environments/environment'
16f7022b 24import { VideoCaptionService } from '@app/shared/video-caption'
1506307f 25import { MarkdownService } from '@app/shared/renderer'
6ec0b75b
C
26import {
27 P2PMediaLoaderOptions,
28 PeertubePlayerManager,
29 PeertubePlayerManagerOptions,
30 PlayerMode,
31 WebtorrentOptions
32} from '../../../assets/player/peertube-player-manager'
dc8bc31b 33
dc8bc31b
C
34@Component({
35 selector: 'my-video-watch',
ec8d8440
C
36 templateUrl: './video-watch.component.html',
37 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 38})
0629423c 39export class VideoWatchComponent implements OnInit, OnDestroy {
22b59e80
C
40 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
41
a96aed15 42 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
df98563e
C
43 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
44 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
07fa4c97 45 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
26b7305a 46 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
20d21199 47 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
df98563e 48
2adfc7ea 49 player: any
0826c92d 50 playerElement: HTMLVideoElement
154898b0 51 userRating: UserVideoRateType = null
404b54e1 52 video: VideoDetails = null
80958c78 53 descriptionLoading = false
2de96f4d
C
54
55 completeDescriptionShown = false
56 completeVideoDescription: string
57 shortVideoDescription: string
9d9597df 58 videoHTMLDescription = ''
e9189001 59 likesBarTooltipText = ''
73e09f27 60 hasAlreadyAcceptedPrivacyConcern = false
6d88de72 61 remoteServerDown = false
20d21199 62 hotkeys: Hotkey[]
df98563e 63
df98563e 64 private paramsSub: Subscription
df98563e
C
65
66 constructor (
4fd8aa32 67 private elementRef: ElementRef,
3b492bff 68 private changeDetector: ChangeDetectorRef,
0629423c 69 private route: ActivatedRoute,
92fb909c 70 private router: Router,
d3ef341a 71 private videoService: VideoService,
35bf0c83 72 private videoBlacklistService: VideoBlacklistService,
92fb909c 73 private confirmService: ConfirmService,
3ec343a4 74 private metaService: MetaService,
7ddd02c9 75 private authService: AuthService,
0883b324 76 private serverService: ServerService,
a51bad1a 77 private restExtractor: RestExtractor,
f8b2c1b4 78 private notifier: Notifier,
7ae71355 79 private markdownService: MarkdownService,
901637bb 80 private zone: NgZone,
989e526a 81 private redirectService: RedirectService,
16f7022b 82 private videoCaptionService: VideoCaptionService,
e945b184 83 private i18n: I18n,
20d21199 84 private hotkeysService: HotkeysService,
e945b184 85 @Inject(LOCALE_ID) private localeId: string
d3ef341a 86 ) {}
dc8bc31b 87
b2731bff
C
88 get user () {
89 return this.authService.getUser()
90 }
91
df98563e 92 ngOnInit () {
0bd78bf3
C
93 if (
94 WebTorrent.WEBRTC_SUPPORT === false ||
95 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
96 ) {
2b3b76ab
C
97 this.hasAlreadyAcceptedPrivacyConcern = true
98 }
99
13fc89f4 100 this.paramsSub = this.route.params.subscribe(routeParams => {
2186386c 101 const uuid = routeParams[ 'uuid' ]
a51bad1a 102
244e76a5 103 // Video did not change
1263fc4e 104 if (this.video && this.video.uuid === uuid) return
bf079b7b
C
105
106 if (this.player) this.player.pause()
107
244e76a5 108 // Video did change
16f7022b
C
109 forkJoin(
110 this.videoService.getVideo(uuid),
111 this.videoCaptionService.listCaptions(uuid)
112 )
113 .pipe(
191764f3 114 // If 401, the video is private or blacklisted so redirect to 404
8d427346 115 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
16f7022b
C
116 )
117 .subscribe(([ video, captionsResult ]) => {
118 const startTime = this.route.snapshot.queryParams.start
1b04f19c
C
119 const subtitle = this.route.snapshot.queryParams.subtitle
120
121 this.onVideoFetched(video, captionsResult.data, { startTime, subtitle })
16f7022b
C
122 .catch(err => this.handleError(err))
123 })
df98563e 124 })
20d21199
RK
125
126 this.hotkeys = [
a157b3a3 127 new Hotkey('shift+l', (event: KeyboardEvent): boolean => {
20d21199
RK
128 this.setLike()
129 return false
e33f888b 130 }, undefined, this.i18n('Like the video')),
a157b3a3 131 new Hotkey('shift+d', (event: KeyboardEvent): boolean => {
20d21199
RK
132 this.setDislike()
133 return false
e33f888b 134 }, undefined, this.i18n('Dislike the video')),
a157b3a3 135 new Hotkey('shift+s', (event: KeyboardEvent): boolean => {
20d21199
RK
136 this.subscribeButton.subscribed ?
137 this.subscribeButton.unsubscribe() :
138 this.subscribeButton.subscribe()
139 return false
e33f888b 140 }, undefined, this.i18n('Subscribe to the account'))
20d21199
RK
141 ]
142 if (this.isUserLoggedIn()) this.hotkeysService.add(this.hotkeys)
d1992b93
C
143 }
144
df98563e 145 ngOnDestroy () {
09edde40 146 this.flushPlayer()
067e3f84 147
13fc89f4 148 // Unsubscribe subscriptions
df98563e 149 this.paramsSub.unsubscribe()
20d21199
RK
150
151 // Unbind hotkeys
152 if (this.isUserLoggedIn()) this.hotkeysService.remove(this.hotkeys)
dc8bc31b 153 }
98b01bac 154
df98563e
C
155 setLike () {
156 if (this.isUserLoggedIn() === false) return
57a49263
BB
157 if (this.userRating === 'like') {
158 // Already liked this video
159 this.setRating('none')
160 } else {
161 this.setRating('like')
162 }
d38b8281
C
163 }
164
df98563e
C
165 setDislike () {
166 if (this.isUserLoggedIn() === false) return
57a49263
BB
167 if (this.userRating === 'dislike') {
168 // Already disliked this video
169 this.setRating('none')
170 } else {
171 this.setRating('dislike')
172 }
d38b8281
C
173 }
174
2de96f4d 175 showMoreDescription () {
2de96f4d
C
176 if (this.completeVideoDescription === undefined) {
177 return this.loadCompleteDescription()
178 }
179
180 this.updateVideoDescription(this.completeVideoDescription)
80958c78 181 this.completeDescriptionShown = true
2de96f4d
C
182 }
183
184 showLessDescription () {
2de96f4d 185 this.updateVideoDescription(this.shortVideoDescription)
80958c78 186 this.completeDescriptionShown = false
2de96f4d
C
187 }
188
189 loadCompleteDescription () {
80958c78
C
190 this.descriptionLoading = true
191
2de96f4d 192 this.videoService.loadCompleteDescription(this.video.descriptionPath)
2186386c
C
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
f8b2c1b4 206 this.notifier.error(error.message)
2186386c
C
207 }
208 )
2de96f4d
C
209 }
210
df98563e
C
211 showReportModal (event: Event) {
212 event.preventDefault()
213 this.videoReportModal.show()
4f8c0eb0
C
214 }
215
07fa4c97
C
216 showSupportModal () {
217 this.videoSupportModal.show()
218 }
219
df98563e 220 showShareModal () {
11b8762f
C
221 const currentTime = this.player ? this.player.currentTime() : undefined
222
223 this.videoShareModal.show(currentTime)
99cc4f49
C
224 }
225
a96aed15 226 showDownloadModal (event: Event) {
df98563e 227 event.preventDefault()
a96aed15 228 this.videoDownloadModal.show()
99cc4f49
C
229 }
230
26b7305a
C
231 showBlacklistModal (event: Event) {
232 event.preventDefault()
233 this.videoBlacklistModal.show()
234 }
235
191764f3
C
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 () => {
f8b2c1b4 248 this.notifier.success(this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name }))
191764f3
C
249
250 this.video.blacklisted = false
251 this.video.blacklistedReason = null
252 },
253
f8b2c1b4 254 err => this.notifier.error(err.message)
191764f3
C
255 )
256 }
257
df98563e
C
258 isUserLoggedIn () {
259 return this.authService.isLoggedIn()
4f8c0eb0
C
260 }
261
4635f59d
C
262 isVideoUpdatable () {
263 return this.video.isUpdatableBy(this.authService.getUser())
264 }
265
df98563e 266 isVideoBlacklistable () {
b2731bff 267 return this.video.isBlackistableBy(this.user)
198b205c
GS
268 }
269
191764f3
C
270 isVideoUnblacklistable () {
271 return this.video.isUnblacklistableBy(this.user)
272 }
273
b1fa3eba
C
274 getVideoTags () {
275 if (!this.video || Array.isArray(this.video.tags) === false) return []
276
4278710d 277 return this.video.tags
b1fa3eba
C
278 }
279
6725d05c
C
280 isVideoRemovable () {
281 return this.video.isRemovableBy(this.authService.getUser())
282 }
283
1f30a185 284 async removeVideo (event: Event) {
6725d05c
C
285 event.preventDefault()
286
989e526a 287 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
1f30a185 288 if (res === false) return
6725d05c 289
1f30a185 290 this.videoService.removeVideo(this.video.id)
2186386c 291 .subscribe(
f8b2c1b4
C
292 () => {
293 this.notifier.success(this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name }))
2186386c
C
294
295 // Go back to the video-list.
296 this.redirectService.redirectToHomepage()
297 },
298
f8b2c1b4 299 error => this.notifier.error(error.message)
2186386c 300 )
6725d05c
C
301 }
302
73e09f27 303 acceptedPrivacyConcern () {
0bd78bf3 304 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
73e09f27
C
305 this.hasAlreadyAcceptedPrivacyConcern = true
306 }
307
2186386c
C
308 isVideoToTranscode () {
309 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
310 }
311
516df59b
C
312 isVideoToImport () {
313 return this.video && this.video.state.id === VideoState.TO_IMPORT
314 }
315
bbe0f064
C
316 hasVideoScheduledPublication () {
317 return this.video && this.video.scheduledUpdate !== undefined
318 }
319
2de96f4d
C
320 private updateVideoDescription (description: string) {
321 this.video.description = description
322 this.setVideoDescriptionHTML()
323 }
324
325 private setVideoDescriptionHTML () {
07fa4c97 326 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
2de96f4d
C
327 }
328
e9189001 329 private setVideoLikesBarTooltipText () {
2186386c
C
330 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
331 likesNumber: this.video.likes,
332 dislikesNumber: this.video.dislikes
333 })
e9189001
C
334 }
335
0c31c33d
C
336 private handleError (err: any) {
337 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
338 if (!errorMessage) return
339
6d88de72 340 // Display a message in the video player instead of a notification
0f7fedc3 341 if (errorMessage.indexOf('from xs param') !== -1) {
6d88de72
C
342 this.flushPlayer()
343 this.remoteServerDown = true
3b492bff
C
344 this.changeDetector.detectChanges()
345
6d88de72 346 return
0c31c33d
C
347 }
348
f8b2c1b4 349 this.notifier.error(errorMessage)
0c31c33d
C
350 }
351
df98563e 352 private checkUserRating () {
d38b8281 353 // Unlogged users do not have ratings
df98563e 354 if (this.isUserLoggedIn() === false) return
d38b8281
C
355
356 this.videoService.getUserVideoRating(this.video.id)
2186386c
C
357 .subscribe(
358 ratingObject => {
359 if (ratingObject) {
360 this.userRating = ratingObject.rating
361 }
362 },
363
f8b2c1b4 364 err => this.notifier.error(err.message)
2186386c 365 )
d38b8281
C
366 }
367
1b04f19c 368 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], urlOptions: { startTime: number, subtitle: string }) {
df98563e 369 this.video = video
92fb909c 370
c448d412
C
371 // Re init attributes
372 this.descriptionLoading = false
373 this.completeDescriptionShown = false
6d88de72 374 this.remoteServerDown = false
c448d412 375
1b04f19c 376 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
43483d12 377 // If we are at the end of the video, reset the timer
6e46de09
C
378 if (this.video.duration - startTime <= 1) startTime = 0
379
0883b324 380 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
22b59e80 381 const res = await this.confirmService.confirm(
989e526a
C
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')
d6e32a2e 384 )
901637bb 385 if (res === false) return this.redirectService.redirectToHomepage()
92fb909c
C
386 }
387
09edde40
C
388 // Flush old player if needed
389 this.flushPlayer()
b891f9bc
C
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'
e7eb5b39 395 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
396 playerElementWrapper.appendChild(this.playerElement)
397
16f7022b
C
398 const playerCaptions = videoCaptions.map(c => ({
399 label: c.language.label,
400 language: c.language.id,
401 src: environment.apiUrl + c.captionPath
402 }))
403
6ec0b75b 404 const options: PeertubePlayerManagerOptions = {
2adfc7ea
C
405 common: {
406 autoplay: this.isAutoplay(),
6ec0b75b 407
2adfc7ea 408 playerElement: this.playerElement,
6ec0b75b
C
409 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
410
2adfc7ea
C
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,
aa8b6df4 427
2adfc7ea
C
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
6ec0b75b
C
436 },
437
438 webtorrent: {
439 videoFiles: this.video.files
09209296
C
440 }
441 }
2adfc7ea 442
09209296
C
443 let mode: PlayerMode
444 const hlsPlaylist = this.video.getHlsPlaylist()
445 if (hlsPlaylist) {
446 mode = 'p2p-media-loader'
6ec0b75b 447
09209296
C
448 const p2pMediaLoader = {
449 playlistUrl: hlsPlaylist.playlistUrl,
450 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
451 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
452 trackerAnnounce: this.video.trackerUrls,
2adfc7ea 453 videoFiles: this.video.files
09209296
C
454 } as P2PMediaLoaderOptions
455
456 Object.assign(options, { p2pMediaLoader })
457 } else {
458 mode = 'webtorrent'
e945b184
C
459 }
460
e945b184 461 this.zone.runOutsideAngular(async () => {
09209296 462 this.player = await PeertubePlayerManager.initialize(mode, options)
2adfc7ea 463 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
b891f9bc 464 })
22b59e80
C
465
466 this.setVideoDescriptionHTML()
467 this.setVideoLikesBarTooltipText()
468
469 this.setOpenGraphTags()
470 this.checkUserRating()
92fb909c
C
471 }
472
5c6d985f 473 private setRating (nextRating: UserVideoRateType) {
57a49263
BB
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)
2186386c
C
488 .subscribe(
489 () => {
490 // Update the video like attribute
c199c427
C
491 this.updateVideoRating(this.userRating, nextRating)
492 this.userRating = nextRating
2186386c
C
493 },
494
f8b2c1b4 495 (err: { message: string }) => this.notifier.error(err.message)
2186386c 496 )
57a49263
BB
497 }
498
5c6d985f 499 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
500 let likesToIncrement = 0
501 let dislikesToIncrement = 0
d38b8281
C
502
503 if (oldRating) {
df98563e
C
504 if (oldRating === 'like') likesToIncrement--
505 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
506 }
507
df98563e
C
508 if (newRating === 'like') likesToIncrement++
509 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 510
df98563e
C
511 this.video.likes += likesToIncrement
512 this.video.dislikes += dislikesToIncrement
20b40b19 513
22b59e80 514 this.video.buildLikeAndDislikePercents()
20b40b19 515 this.setVideoLikesBarTooltipText()
d38b8281
C
516 }
517
df98563e
C
518 private setOpenGraphTags () {
519 this.metaService.setTitle(this.video.name)
758b996d 520
df98563e 521 this.metaService.setTag('og:type', 'video')
3ec343a4 522
df98563e
C
523 this.metaService.setTag('og:title', this.video.name)
524 this.metaService.setTag('name', this.video.name)
3ec343a4 525
df98563e
C
526 this.metaService.setTag('og:description', this.video.description)
527 this.metaService.setTag('description', this.video.description)
3ec343a4 528
d38309c3 529 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 530
df98563e 531 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 532
df98563e 533 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 534
df98563e
C
535 this.metaService.setTag('og:url', window.location.href)
536 this.metaService.setTag('url', window.location.href)
3ec343a4 537 }
1f3e9fec 538
d4c6a3b9 539 private isAutoplay () {
bf079b7b
C
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
d4c6a3b9
C
544 if (!this.user) return true
545
546 // Be sure the autoPlay is set to false
547 return this.user.autoPlayVideo !== false
548 }
09edde40
C
549
550 private flushPlayer () {
551 // Remove player if it exists
552 if (this.player) {
553 this.player.dispose()
554 this.player = undefined
555 }
556 }
dc8bc31b 557}