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