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