]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/videos/+video-watch/video-watch.component.ts
Check activities host
[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
C
7import { MetaService } from '@ngx-meta/core'
8import { NotificationsService } from 'angular2-notifications'
16f7022b 9import { forkJoin, Subscription } from 'rxjs'
c199c427
C
10// FIXME: something weird with our path definition in tsconfig and typings
11// @ts-ignore
12import videojs from 'video.js'
d7701449 13import 'videojs-hotkeys'
20d21199 14import { Hotkey, HotkeysService } from 'angular2-hotkeys'
caae7a06 15import * as WebTorrent from 'webtorrent'
e63dbd42 16import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoRateType, VideoState } from '../../../../../shared'
aa8b6df4 17import '../../../assets/player/peertube-videojs-plugin'
df98563e 18import { AuthService, ConfirmService } from '../../core'
a51bad1a 19import { RestExtractor, VideoBlacklistService } from '../../shared'
ff249f49 20import { VideoDetails } from '../../shared/video/video-details.model'
63c4db6d 21import { VideoService } from '../../shared/video/video.service'
202f6b6c 22import { MarkdownService } from '../shared'
4635f59d
C
23import { VideoDownloadComponent } from './modal/video-download.component'
24import { VideoReportComponent } from './modal/video-report.component'
25import { VideoShareComponent } from './modal/video-share.component'
26b7305a 26import { VideoBlacklistComponent } from './modal/video-blacklist.component'
20d21199 27import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
3dfa8494 28import { addContextMenu, getVideojsOptions, loadLocaleInVideoJS } from '../../../assets/player/peertube-player'
0883b324 29import { ServerService } from '@app/core'
989e526a 30import { I18n } from '@ngx-translate/i18n-polyfill'
e945b184 31import { environment } from '../../../environments/environment'
74b7c6d4 32import { getDevLocale, isOnDevLocale } from '@app/shared/i18n/i18n-utils'
16f7022b 33import { VideoCaptionService } from '@app/shared/video-caption'
dc8bc31b 34
dc8bc31b
C
35@Component({
36 selector: 'my-video-watch',
ec8d8440
C
37 templateUrl: './video-watch.component.html',
38 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 39})
0629423c 40export class VideoWatchComponent implements OnInit, OnDestroy {
22b59e80
C
41 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
42
a96aed15 43 @ViewChild('videoDownloadModal') videoDownloadModal: VideoDownloadComponent
df98563e
C
44 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
45 @ViewChild('videoReportModal') videoReportModal: VideoReportComponent
07fa4c97 46 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
26b7305a 47 @ViewChild('videoBlacklistModal') videoBlacklistModal: VideoBlacklistComponent
20d21199 48 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
df98563e 49
c199c427 50 player: videojs.Player
0826c92d 51 playerElement: HTMLVideoElement
154898b0 52 userRating: UserVideoRateType = null
404b54e1 53 video: VideoDetails = null
80958c78 54 descriptionLoading = false
2de96f4d
C
55
56 completeDescriptionShown = false
57 completeVideoDescription: string
58 shortVideoDescription: string
9d9597df 59 videoHTMLDescription = ''
e9189001 60 likesBarTooltipText = ''
73e09f27 61 hasAlreadyAcceptedPrivacyConcern = false
6d88de72 62 remoteServerDown = false
20d21199 63 hotkeys: Hotkey[]
df98563e 64
e945b184 65 private videojsLocaleLoaded = false
df98563e 66 private paramsSub: Subscription
df98563e
C
67
68 constructor (
4fd8aa32 69 private elementRef: ElementRef,
3b492bff 70 private changeDetector: ChangeDetectorRef,
0629423c 71 private route: ActivatedRoute,
92fb909c 72 private router: Router,
d3ef341a 73 private videoService: VideoService,
35bf0c83 74 private videoBlacklistService: VideoBlacklistService,
92fb909c 75 private confirmService: ConfirmService,
3ec343a4 76 private metaService: MetaService,
7ddd02c9 77 private authService: AuthService,
0883b324 78 private serverService: ServerService,
a51bad1a 79 private restExtractor: RestExtractor,
9d9597df 80 private notificationsService: NotificationsService,
7ae71355 81 private markdownService: MarkdownService,
901637bb 82 private zone: NgZone,
989e526a 83 private redirectService: RedirectService,
16f7022b 84 private videoCaptionService: VideoCaptionService,
e945b184 85 private i18n: I18n,
20d21199 86 private hotkeysService: HotkeysService,
e945b184 87 @Inject(LOCALE_ID) private localeId: string
d3ef341a 88 ) {}
dc8bc31b 89
b2731bff
C
90 get user () {
91 return this.authService.getUser()
92 }
93
df98563e 94 ngOnInit () {
0bd78bf3
C
95 if (
96 WebTorrent.WEBRTC_SUPPORT === false ||
97 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
98 ) {
2b3b76ab
C
99 this.hasAlreadyAcceptedPrivacyConcern = true
100 }
101
13fc89f4 102 this.paramsSub = this.route.params.subscribe(routeParams => {
2186386c 103 const uuid = routeParams[ 'uuid' ]
a51bad1a 104
244e76a5 105 // Video did not change
1263fc4e 106 if (this.video && this.video.uuid === uuid) return
bf079b7b
C
107
108 if (this.player) this.player.pause()
109
244e76a5 110 // Video did change
16f7022b
C
111 forkJoin(
112 this.videoService.getVideo(uuid),
113 this.videoCaptionService.listCaptions(uuid)
114 )
115 .pipe(
191764f3
C
116 // If 401, the video is private or blacklisted so redirect to 404
117 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 404 ]))
16f7022b
C
118 )
119 .subscribe(([ video, captionsResult ]) => {
120 const startTime = this.route.snapshot.queryParams.start
121 this.onVideoFetched(video, captionsResult.data, startTime)
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
206 this.notificationsService.error(this.i18n('Error'), error.message)
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 () => {
248 this.notificationsService.success(
249 this.i18n('Success'),
250 this.i18n('Video {{name}} removed from the blacklist.', { name: this.video.name })
251 )
252
253 this.video.blacklisted = false
254 this.video.blacklistedReason = null
255 },
256
257 err => this.notificationsService.error(this.i18n('Error'), err.message)
258 )
259 }
260
df98563e
C
261 isUserLoggedIn () {
262 return this.authService.isLoggedIn()
4f8c0eb0
C
263 }
264
4635f59d
C
265 isVideoUpdatable () {
266 return this.video.isUpdatableBy(this.authService.getUser())
267 }
268
df98563e 269 isVideoBlacklistable () {
b2731bff 270 return this.video.isBlackistableBy(this.user)
198b205c
GS
271 }
272
191764f3
C
273 isVideoUnblacklistable () {
274 return this.video.isUnblacklistableBy(this.user)
275 }
276
b1fa3eba
C
277 getVideoTags () {
278 if (!this.video || Array.isArray(this.video.tags) === false) return []
279
4278710d 280 return this.video.tags
b1fa3eba
C
281 }
282
6725d05c
C
283 isVideoRemovable () {
284 return this.video.isRemovableBy(this.authService.getUser())
285 }
286
1f30a185 287 async removeVideo (event: Event) {
6725d05c
C
288 event.preventDefault()
289
989e526a 290 const res = await this.confirmService.confirm(this.i18n('Do you really want to delete this video?'), this.i18n('Delete'))
1f30a185 291 if (res === false) return
6725d05c 292
1f30a185 293 this.videoService.removeVideo(this.video.id)
2186386c
C
294 .subscribe(
295 status => {
296 this.notificationsService.success(
297 this.i18n('Success'),
298 this.i18n('Video {{videoName}} deleted.', { videoName: this.video.name })
299 )
300
301 // Go back to the video-list.
302 this.redirectService.redirectToHomepage()
303 },
304
305 error => this.notificationsService.error(this.i18n('Error'), error.message)
306 )
6725d05c
C
307 }
308
73e09f27 309 acceptedPrivacyConcern () {
0bd78bf3 310 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
73e09f27
C
311 this.hasAlreadyAcceptedPrivacyConcern = true
312 }
313
2186386c
C
314 isVideoToTranscode () {
315 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
316 }
317
516df59b
C
318 isVideoToImport () {
319 return this.video && this.video.state.id === VideoState.TO_IMPORT
320 }
321
bbe0f064
C
322 hasVideoScheduledPublication () {
323 return this.video && this.video.scheduledUpdate !== undefined
324 }
325
2de96f4d
C
326 private updateVideoDescription (description: string) {
327 this.video.description = description
328 this.setVideoDescriptionHTML()
329 }
330
331 private setVideoDescriptionHTML () {
07fa4c97 332 this.videoHTMLDescription = this.markdownService.textMarkdownToHTML(this.video.description)
2de96f4d
C
333 }
334
e9189001 335 private setVideoLikesBarTooltipText () {
2186386c
C
336 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
337 likesNumber: this.video.likes,
338 dislikesNumber: this.video.dislikes
339 })
e9189001
C
340 }
341
0c31c33d
C
342 private handleError (err: any) {
343 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
344 if (!errorMessage) return
345
6d88de72 346 // Display a message in the video player instead of a notification
0f7fedc3 347 if (errorMessage.indexOf('from xs param') !== -1) {
6d88de72
C
348 this.flushPlayer()
349 this.remoteServerDown = true
3b492bff
C
350 this.changeDetector.detectChanges()
351
6d88de72 352 return
0c31c33d
C
353 }
354
6d88de72 355 this.notificationsService.error(this.i18n('Error'), errorMessage)
0c31c33d
C
356 }
357
df98563e 358 private checkUserRating () {
d38b8281 359 // Unlogged users do not have ratings
df98563e 360 if (this.isUserLoggedIn() === false) return
d38b8281
C
361
362 this.videoService.getUserVideoRating(this.video.id)
2186386c
C
363 .subscribe(
364 ratingObject => {
365 if (ratingObject) {
366 this.userRating = ratingObject.rating
367 }
368 },
369
370 err => this.notificationsService.error(this.i18n('Error'), err.message)
371 )
d38b8281
C
372 }
373
6e46de09 374 private async onVideoFetched (video: VideoDetails, videoCaptions: VideoCaption[], startTimeFromUrl: number) {
df98563e 375 this.video = video
92fb909c 376
c448d412
C
377 // Re init attributes
378 this.descriptionLoading = false
379 this.completeDescriptionShown = false
6d88de72 380 this.remoteServerDown = false
c448d412 381
6e46de09
C
382 let startTime = startTimeFromUrl || (this.video.userHistory ? this.video.userHistory.currentTime : 0)
383 // Don't start the video if we are at the end
384 if (this.video.duration - startTime <= 1) startTime = 0
385
0883b324 386 if (this.video.isVideoNSFWForUser(this.user, this.serverService.getConfig())) {
22b59e80 387 const res = await this.confirmService.confirm(
989e526a
C
388 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
389 this.i18n('Mature or explicit content')
d6e32a2e 390 )
901637bb 391 if (res === false) return this.redirectService.redirectToHomepage()
92fb909c
C
392 }
393
09edde40
C
394 // Flush old player if needed
395 this.flushPlayer()
b891f9bc
C
396
397 // Build video element, because videojs remove it on dispose
398 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#video-element-wrapper')
399 this.playerElement = document.createElement('video')
400 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 401 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
402 playerElementWrapper.appendChild(this.playerElement)
403
16f7022b
C
404 const playerCaptions = videoCaptions.map(c => ({
405 label: c.language.label,
406 language: c.language.id,
407 src: environment.apiUrl + c.captionPath
408 }))
409
b891f9bc
C
410 const videojsOptions = getVideojsOptions({
411 autoplay: this.isAutoplay(),
09edde40 412 inactivityTimeout: 2500,
b891f9bc 413 videoFiles: this.video.files,
16f7022b 414 videoCaptions: playerCaptions,
b891f9bc 415 playerElement: this.playerElement,
f5a2dc48 416 videoViewUrl: this.video.privacy.id !== VideoPrivacy.PRIVATE ? this.videoService.getVideoViewUrl(this.video.uuid) : null,
b891f9bc
C
417 videoDuration: this.video.duration,
418 enableHotkeys: true,
419 peertubeLink: false,
f37bad63 420 poster: this.video.previewUrl,
054a103b 421 startTime,
95d51135 422 theaterMode: true,
6e46de09
C
423 language: this.localeId,
424
425 userWatching: this.user ? {
426 url: this.videoService.getUserWatchingVideoUrl(this.video.uuid),
427 authorizationHeader: this.authService.getRequestHeaderValue()
428 } : undefined
b891f9bc 429 })
aa8b6df4 430
e945b184 431 if (this.videojsLocaleLoaded === false) {
3dfa8494 432 await loadLocaleInVideoJS(environment.apiUrl, videojs, isOnDevLocale() ? getDevLocale() : this.localeId)
e945b184
C
433 this.videojsLocaleLoaded = true
434 }
435
b891f9bc 436 const self = this
e945b184 437 this.zone.runOutsideAngular(async () => {
951ef829 438 videojs(this.playerElement, videojsOptions, function (this: videojs.Player) {
b891f9bc 439 self.player = this
c199c427 440 this.on('customError', ({ err }: { err: any }) => self.handleError(err))
e945b184
C
441
442 addContextMenu(self.player, self.video.embedUrl)
22b59e80 443 })
b891f9bc 444 })
22b59e80
C
445
446 this.setVideoDescriptionHTML()
447 this.setVideoLikesBarTooltipText()
448
449 this.setOpenGraphTags()
450 this.checkUserRating()
92fb909c
C
451 }
452
5c6d985f 453 private setRating (nextRating: UserVideoRateType) {
57a49263
BB
454 let method
455 switch (nextRating) {
456 case 'like':
457 method = this.videoService.setVideoLike
458 break
459 case 'dislike':
460 method = this.videoService.setVideoDislike
461 break
462 case 'none':
463 method = this.videoService.unsetVideoLike
464 break
465 }
466
467 method.call(this.videoService, this.video.id)
2186386c
C
468 .subscribe(
469 () => {
470 // Update the video like attribute
c199c427
C
471 this.updateVideoRating(this.userRating, nextRating)
472 this.userRating = nextRating
2186386c
C
473 },
474
c199c427 475 (err: { message: string }) => this.notificationsService.error(this.i18n('Error'), err.message)
2186386c 476 )
57a49263
BB
477 }
478
5c6d985f 479 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
480 let likesToIncrement = 0
481 let dislikesToIncrement = 0
d38b8281
C
482
483 if (oldRating) {
df98563e
C
484 if (oldRating === 'like') likesToIncrement--
485 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
486 }
487
df98563e
C
488 if (newRating === 'like') likesToIncrement++
489 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 490
df98563e
C
491 this.video.likes += likesToIncrement
492 this.video.dislikes += dislikesToIncrement
20b40b19 493
22b59e80 494 this.video.buildLikeAndDislikePercents()
20b40b19 495 this.setVideoLikesBarTooltipText()
d38b8281
C
496 }
497
df98563e
C
498 private setOpenGraphTags () {
499 this.metaService.setTitle(this.video.name)
758b996d 500
df98563e 501 this.metaService.setTag('og:type', 'video')
3ec343a4 502
df98563e
C
503 this.metaService.setTag('og:title', this.video.name)
504 this.metaService.setTag('name', this.video.name)
3ec343a4 505
df98563e
C
506 this.metaService.setTag('og:description', this.video.description)
507 this.metaService.setTag('description', this.video.description)
3ec343a4 508
d38309c3 509 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 510
df98563e 511 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 512
df98563e 513 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 514
df98563e
C
515 this.metaService.setTag('og:url', window.location.href)
516 this.metaService.setTag('url', window.location.href)
3ec343a4 517 }
1f3e9fec 518
d4c6a3b9 519 private isAutoplay () {
bf079b7b
C
520 // We'll jump to the thread id, so do not play the video
521 if (this.route.snapshot.params['threadId']) return false
522
523 // Otherwise true by default
d4c6a3b9
C
524 if (!this.user) return true
525
526 // Be sure the autoPlay is set to false
527 return this.user.autoPlayVideo !== false
528 }
09edde40
C
529
530 private flushPlayer () {
531 // Remove player if it exists
532 if (this.player) {
533 this.player.dispose()
534 this.player = undefined
535 }
536 }
dc8bc31b 537}