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