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