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