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