]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/videos/+video-watch/video-watch.component.ts
Add player mode in watch/embed urls
[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,
597a9266 30 PlayerMode
6ec0b75b 31} from '../../../assets/player/peertube-player-manager'
dc8bc31b 32
dc8bc31b
C
33@Component({
34 selector: 'my-video-watch',
ec8d8440
C
35 templateUrl: './video-watch.component.html',
36 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 37})
0629423c 38export class VideoWatchComponent implements OnInit, OnDestroy {
22b59e80
C
39 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
40
a96aed15 41 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
df98563e
C
42 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
43 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
07fa4c97 44 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
26b7305a 45 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
20d21199 46 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
df98563e 47
2adfc7ea 48 player: any
0826c92d 49 playerElement: HTMLVideoElement
154898b0 50 userRating: UserVideoRateType = null
404b54e1 51 video: VideoDetails = null
80958c78 52 descriptionLoading = false
2de96f4d
C
53
54 completeDescriptionShown = false
55 completeVideoDescription: string
56 shortVideoDescription: string
9d9597df 57 videoHTMLDescription = ''
e9189001 58 likesBarTooltipText = ''
73e09f27 59 hasAlreadyAcceptedPrivacyConcern = false
6d88de72 60 remoteServerDown = false
20d21199 61 hotkeys: Hotkey[]
df98563e 62
df98563e 63 private paramsSub: Subscription
df98563e
C
64
65 constructor (
4fd8aa32 66 private elementRef: ElementRef,
3b492bff 67 private changeDetector: ChangeDetectorRef,
0629423c 68 private route: ActivatedRoute,
92fb909c 69 private router: Router,
d3ef341a 70 private videoService: VideoService,
35bf0c83 71 private videoBlacklistService: VideoBlacklistService,
92fb909c 72 private confirmService: ConfirmService,
3ec343a4 73 private metaService: MetaService,
7ddd02c9 74 private authService: AuthService,
0883b324 75 private serverService: ServerService,
a51bad1a 76 private restExtractor: RestExtractor,
f8b2c1b4 77 private notifier: Notifier,
7ae71355 78 private markdownService: MarkdownService,
901637bb 79 private zone: NgZone,
989e526a 80 private redirectService: RedirectService,
16f7022b 81 private videoCaptionService: VideoCaptionService,
e945b184 82 private i18n: I18n,
20d21199 83 private hotkeysService: HotkeysService,
e945b184 84 @Inject(LOCALE_ID) private localeId: string
d3ef341a 85 ) {}
dc8bc31b 86
b2731bff
C
87 get user () {
88 return this.authService.getUser()
89 }
90
df98563e 91 ngOnInit () {
0bd78bf3
C
92 if (
93 WebTorrent.WEBRTC_SUPPORT === false ||
94 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
95 ) {
2b3b76ab
C
96 this.hasAlreadyAcceptedPrivacyConcern = true
97 }
98
13fc89f4 99 this.paramsSub = this.route.params.subscribe(routeParams => {
2186386c 100 const uuid = routeParams[ 'uuid' ]
a51bad1a 101
244e76a5 102 // Video did not change
1263fc4e 103 if (this.video && this.video.uuid === uuid) return
bf079b7b
C
104
105 if (this.player) this.player.pause()
106
244e76a5 107 // Video did change
16f7022b
C
108 forkJoin(
109 this.videoService.getVideo(uuid),
110 this.videoCaptionService.listCaptions(uuid)
111 )
112 .pipe(
191764f3 113 // If 401, the video is private or blacklisted so redirect to 404
8d427346 114 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
16f7022b
C
115 )
116 .subscribe(([ video, captionsResult ]) => {
117 const startTime = this.route.snapshot.queryParams.start
1b04f19c 118 const subtitle = this.route.snapshot.queryParams.subtitle
597a9266 119 const playerMode = this.route.snapshot.queryParams.mode
1b04f19c 120
597a9266 121 this.onVideoFetched(video, captionsResult.data, { startTime, subtitle, playerMode })
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
597a9266
C
368 private async onVideoFetched (
369 video: VideoDetails,
370 videoCaptions: VideoCaption[],
371 urlOptions: { startTime?: number, subtitle?: string, playerMode?: string }
372 ) {
df98563e 373 this.video = video
92fb909c 374
c448d412
C
375 // Re init attributes
376 this.descriptionLoading = false
377 this.completeDescriptionShown = false
6d88de72 378 this.remoteServerDown = false
c448d412 379
1b04f19c 380 let startTime = urlOptions.startTime || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
43483d12 381 // If we are at the end of the video, reset the timer
6e46de09
C
382 if (this.video.duration - startTime <= 1) startTime = 0
383
0883b324 384 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
22b59e80 385 const res = await this.confirmService.confirm(
989e526a
C
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')
d6e32a2e 388 )
901637bb 389 if (res === false) return this.redirectService.redirectToHomepage()
92fb909c
C
390 }
391
09edde40
C
392 // Flush old player if needed
393 this.flushPlayer()
b891f9bc
C
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'
e7eb5b39 399 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
400 playerElementWrapper.appendChild(this.playerElement)
401
16f7022b
C
402 const playerCaptions = videoCaptions.map(c => ({
403 label: c.language.label,
404 language: c.language.id,
405 src: environment.apiUrl + c.captionPath
406 }))
407
6ec0b75b 408 const options: PeertubePlayerManagerOptions = {
2adfc7ea
C
409 common: {
410 autoplay: this.isAutoplay(),
6ec0b75b 411
2adfc7ea 412 playerElement: this.playerElement,
6ec0b75b
C
413 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
414
2adfc7ea
C
415 videoDuration: this.video.duration,
416 enableHotkeys: true,
417 inactivityTimeout: 2500,
418 poster: this.video.previewUrl,
419 startTime,
420
421 theaterMode: true,
422 captions: videoCaptions.length !== 0,
423 peertubeLink: false,
424
425 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
426 embedUrl: this.video.embedUrl,
427
428 language: this.localeId,
429
430 subtitle: urlOptions.subtitle,
aa8b6df4 431
2adfc7ea
C
432 userWatching: this.user && this.user.videosHistoryEnabled === true ? {
433 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
434 authorizationHeader: this.authService.getRequestHeaderValue()
435 } : undefined,
436
437 serverUrl: environment.apiUrl,
438
439 videoCaptions: playerCaptions
6ec0b75b
C
440 },
441
442 webtorrent: {
443 videoFiles: this.video.files
09209296
C
444 }
445 }
2adfc7ea 446
597a9266
C
447 const mode: PlayerMode = urlOptions.playerMode === 'p2p-media-loader' ? 'p2p-media-loader' : 'webtorrent'
448
449 if (mode === 'p2p-media-loader') {
450 const hlsPlaylist = this.video.getHlsPlaylist()
6ec0b75b 451
09209296
C
452 const p2pMediaLoader = {
453 playlistUrl: hlsPlaylist.playlistUrl,
454 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
455 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
456 trackerAnnounce: this.video.trackerUrls,
2adfc7ea 457 videoFiles: this.video.files
09209296
C
458 } as P2PMediaLoaderOptions
459
460 Object.assign(options, { p2pMediaLoader })
e945b184
C
461 }
462
e945b184 463 this.zone.runOutsideAngular(async () => {
09209296 464 this.player = await PeertubePlayerManager.initialize(mode, options)
2adfc7ea 465 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
b891f9bc 466 })
22b59e80
C
467
468 this.setVideoDescriptionHTML()
469 this.setVideoLikesBarTooltipText()
470
471 this.setOpenGraphTags()
472 this.checkUserRating()
92fb909c
C
473 }
474
5c6d985f 475 private setRating (nextRating: UserVideoRateType) {
57a49263
BB
476 let method
477 switch (nextRating) {
478 case 'like':
479 method = this.videoService.setVideoLike
480 break
481 case 'dislike':
482 method = this.videoService.setVideoDislike
483 break
484 case 'none':
485 method = this.videoService.unsetVideoLike
486 break
487 }
488
489 method.call(this.videoService, this.video.id)
2186386c
C
490 .subscribe(
491 () => {
492 // Update the video like attribute
c199c427
C
493 this.updateVideoRating(this.userRating, nextRating)
494 this.userRating = nextRating
2186386c
C
495 },
496
f8b2c1b4 497 (err: { message: string }) => this.notifier.error(err.message)
2186386c 498 )
57a49263
BB
499 }
500
5c6d985f 501 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
502 let likesToIncrement = 0
503 let dislikesToIncrement = 0
d38b8281
C
504
505 if (oldRating) {
df98563e
C
506 if (oldRating === 'like') likesToIncrement--
507 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
508 }
509
df98563e
C
510 if (newRating === 'like') likesToIncrement++
511 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 512
df98563e
C
513 this.video.likes += likesToIncrement
514 this.video.dislikes += dislikesToIncrement
20b40b19 515
22b59e80 516 this.video.buildLikeAndDislikePercents()
20b40b19 517 this.setVideoLikesBarTooltipText()
d38b8281
C
518 }
519
df98563e
C
520 private setOpenGraphTags () {
521 this.metaService.setTitle(this.video.name)
758b996d 522
df98563e 523 this.metaService.setTag('og:type', 'video')
3ec343a4 524
df98563e
C
525 this.metaService.setTag('og:title', this.video.name)
526 this.metaService.setTag('name', this.video.name)
3ec343a4 527
df98563e
C
528 this.metaService.setTag('og:description', this.video.description)
529 this.metaService.setTag('description', this.video.description)
3ec343a4 530
d38309c3 531 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 532
df98563e 533 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 534
df98563e 535 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 536
df98563e
C
537 this.metaService.setTag('og:url', window.location.href)
538 this.metaService.setTag('url', window.location.href)
3ec343a4 539 }
1f3e9fec 540
d4c6a3b9 541 private isAutoplay () {
bf079b7b
C
542 // We'll jump to the thread id, so do not play the video
543 if (this.route.snapshot.params['threadId']) return false
544
545 // Otherwise true by default
d4c6a3b9
C
546 if (!this.user) return true
547
548 // Be sure the autoPlay is set to false
549 return this.user.autoPlayVideo !== false
550 }
09edde40
C
551
552 private flushPlayer () {
553 // Remove player if it exists
554 if (this.player) {
555 this.player.dispose()
556 this.player = undefined
557 }
558 }
dc8bc31b 559}