]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/videos/+video-watch/video-watch.component.ts
Fix lint error introduced in #2539
[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'
d3217560 5import { peertubeLocalStorage } from '@app/shared/misc/peertube-web-storage'
07fa4c97 6import { VideoSupportComponent } from '@app/videos/+video-watch/modal/video-support.component'
1f3e9fec 7import { MetaService } from '@ngx-meta/core'
3d9a63d3 8import { AuthUser, Notifier, ServerService } from '@app/core'
4c72c1cd 9import { forkJoin, Observable, Subscription } from 'rxjs'
20d21199 10import { Hotkey, HotkeysService } from 'angular2-hotkeys'
ba430d75 11import { ServerConfig, UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
df98563e 12import { AuthService, ConfirmService } from '../../core'
d3217560 13import { RestExtractor, UserService } from '../../shared'
ff249f49 14import { VideoDetails } from '../../shared/video/video-details.model'
63c4db6d 15import { VideoService } from '../../shared/video/video.service'
4635f59d 16import { VideoShareComponent } from './modal/video-share.component'
20d21199 17import { SubscribeButtonComponent } from '@app/shared/user-subscription/subscribe-button.component'
989e526a 18import { I18n } from '@ngx-translate/i18n-polyfill'
e945b184 19import { environment } from '../../../environments/environment'
16f7022b 20import { VideoCaptionService } from '@app/shared/video-caption'
1506307f 21import { MarkdownService } from '@app/shared/renderer'
6ec0b75b 22import {
5f85f8aa 23 videojs,
5efab546 24 CustomizationOptions,
6ec0b75b
C
25 P2PMediaLoaderOptions,
26 PeertubePlayerManager,
27 PeertubePlayerManagerOptions,
597a9266 28 PlayerMode
6ec0b75b 29} from '../../../assets/player/peertube-player-manager'
e2f01c47
C
30import { VideoPlaylist } from '@app/shared/video-playlist/video-playlist.model'
31import { VideoPlaylistService } from '@app/shared/video-playlist/video-playlist.service'
e2f01c47 32import { Video } from '@app/shared/video/video.model'
5efab546 33import { isWebRTCDisabled, timeToInt } from '../../../assets/player/utils'
72675ebe 34import { VideoWatchPlaylistComponent } from '@app/videos/+video-watch/video-watch-playlist.component'
c469c05b 35import { getStoredP2PEnabled, getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
93cae479 36import { HooksService } from '@app/core/plugins/hooks.service'
60c2bc80 37import { PlatformLocation } from '@angular/common'
9d45db29 38import { scrollToTop, isXPercentInViewport } from '@app/shared/misc/utils'
dc8bc31b 39
dc8bc31b
C
40@Component({
41 selector: 'my-video-watch',
ec8d8440
C
42 templateUrl: './video-watch.component.html',
43 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 44})
0629423c 45export class VideoWatchComponent implements OnInit, OnDestroy {
22b59e80
C
46 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
47
f36da21e 48 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
2f5d2ec5
C
49 @ViewChild('videoShareModal') videoShareModal: VideoShareComponent
50 @ViewChild('videoSupportModal') videoSupportModal: VideoSupportComponent
51 @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent
df98563e 52
2adfc7ea 53 player: any
0826c92d 54 playerElement: HTMLVideoElement
9a18a625 55 theaterEnabled = false
154898b0 56 userRating: UserVideoRateType = null
80958c78 57 descriptionLoading = false
2de96f4d 58
2f4c784a
C
59 video: VideoDetails = null
60 videoCaptions: VideoCaption[] = []
61
e2f01c47 62 playlist: VideoPlaylist = null
e2f01c47 63
2de96f4d
C
64 completeDescriptionShown = false
65 completeVideoDescription: string
66 shortVideoDescription: string
9d9597df 67 videoHTMLDescription = ''
e9189001 68 likesBarTooltipText = ''
73e09f27 69 hasAlreadyAcceptedPrivacyConcern = false
6d88de72 70 remoteServerDown = false
3d216ea0 71 hotkeys: Hotkey[] = []
df98563e 72
94dfca3e
RK
73 tooltipLike = ''
74 tooltipDislike = ''
75 tooltipSupport = ''
76 tooltipSaveToPlaylist = ''
77
6aa54148 78 private nextVideoUuid = ''
3bcb4fd7 79 private nextVideoTitle = ''
f0a39880 80 private currentTime: number
df98563e 81 private paramsSub: Subscription
e2f01c47 82 private queryParamsSub: Subscription
31b6ddf8 83 private configSub: Subscription
df98563e 84
ba430d75
C
85 private serverConfig: ServerConfig
86
df98563e 87 constructor (
4fd8aa32 88 private elementRef: ElementRef,
3b492bff 89 private changeDetector: ChangeDetectorRef,
0629423c 90 private route: ActivatedRoute,
92fb909c 91 private router: Router,
d3ef341a 92 private videoService: VideoService,
e2f01c47 93 private playlistService: VideoPlaylistService,
92fb909c 94 private confirmService: ConfirmService,
3ec343a4 95 private metaService: MetaService,
7ddd02c9 96 private authService: AuthService,
d3217560 97 private userService: UserService,
0883b324 98 private serverService: ServerService,
a51bad1a 99 private restExtractor: RestExtractor,
f8b2c1b4 100 private notifier: Notifier,
7ae71355 101 private markdownService: MarkdownService,
901637bb 102 private zone: NgZone,
989e526a 103 private redirectService: RedirectService,
16f7022b 104 private videoCaptionService: VideoCaptionService,
e945b184 105 private i18n: I18n,
20d21199 106 private hotkeysService: HotkeysService,
93cae479 107 private hooks: HooksService,
60c2bc80 108 private location: PlatformLocation,
e945b184 109 @Inject(LOCALE_ID) private localeId: string
94dfca3e
RK
110 ) {
111 this.tooltipLike = this.i18n('Like this video')
112 this.tooltipDislike = this.i18n('Dislike this video')
113 this.tooltipSupport = this.i18n('Support options for this video')
114 this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
115 }
dc8bc31b 116
b2731bff
C
117 get user () {
118 return this.authService.getUser()
119 }
120
d3217560
RK
121 get anonymousUser () {
122 return this.userService.getAnonymousUser()
123 }
124
18a6f04c 125 async ngOnInit () {
ba430d75
C
126 this.serverConfig = this.serverService.getTmpConfig()
127
128 this.configSub = this.serverService.getConfig()
129 .subscribe(config => {
130 this.serverConfig = config
131
31b6ddf8
C
132 if (
133 isWebRTCDisabled() ||
ba430d75 134 this.serverConfig.tracker.enabled === false ||
c469c05b 135 getStoredP2PEnabled() === false ||
31b6ddf8
C
136 peertubeLocalStorage.getItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY) === 'true'
137 ) {
138 this.hasAlreadyAcceptedPrivacyConcern = true
139 }
140 })
2b3b76ab 141
13fc89f4 142 this.paramsSub = this.route.params.subscribe(routeParams => {
e2f01c47
C
143 const videoId = routeParams[ 'videoId' ]
144 if (videoId) this.loadVideo(videoId)
a51bad1a 145
e2f01c47
C
146 const playlistId = routeParams[ 'playlistId' ]
147 if (playlistId) this.loadPlaylist(playlistId)
148 })
bf079b7b 149
b29bf61d 150 this.queryParamsSub = this.route.queryParams.subscribe(async queryParams => {
e2f01c47 151 const videoId = queryParams[ 'videoId' ]
2a5518a6 152 if (videoId) this.loadVideo(videoId)
b29bf61d
RK
153
154 const start = queryParams[ 'start' ]
155 if (this.player && start) this.player.currentTime(parseInt(start, 10))
df98563e 156 })
20d21199 157
1c8ddbfa 158 this.initHotkeys()
011e1e6b
C
159
160 this.theaterEnabled = getStoredTheater()
18a6f04c 161
c9e3eeed 162 this.hooks.runAction('action:video-watch.init', 'video-watch')
d1992b93
C
163 }
164
df98563e 165 ngOnDestroy () {
09edde40 166 this.flushPlayer()
067e3f84 167
13fc89f4 168 // Unsubscribe subscriptions
e2f01c47
C
169 if (this.paramsSub) this.paramsSub.unsubscribe()
170 if (this.queryParamsSub) this.queryParamsSub.unsubscribe()
20d21199
RK
171
172 // Unbind hotkeys
3d216ea0 173 this.hotkeysService.remove(this.hotkeys)
dc8bc31b 174 }
98b01bac 175
df98563e
C
176 setLike () {
177 if (this.isUserLoggedIn() === false) return
4c72c1cd
C
178
179 // Already liked this video
180 if (this.userRating === 'like') this.setRating('none')
181 else this.setRating('like')
d38b8281
C
182 }
183
df98563e
C
184 setDislike () {
185 if (this.isUserLoggedIn() === false) return
4c72c1cd
C
186
187 // Already disliked this video
188 if (this.userRating === 'dislike') this.setRating('none')
189 else this.setRating('dislike')
d38b8281
C
190 }
191
0d3a9be9
C
192 getRatePopoverText () {
193 if (this.isUserLoggedIn()) return undefined
194
195 return this.i18n('You need to be connected to rate this content.')
196 }
197
2de96f4d 198 showMoreDescription () {
2de96f4d
C
199 if (this.completeVideoDescription === undefined) {
200 return this.loadCompleteDescription()
201 }
202
203 this.updateVideoDescription(this.completeVideoDescription)
80958c78 204 this.completeDescriptionShown = true
2de96f4d
C
205 }
206
207 showLessDescription () {
2de96f4d 208 this.updateVideoDescription(this.shortVideoDescription)
80958c78 209 this.completeDescriptionShown = false
2de96f4d
C
210 }
211
212 loadCompleteDescription () {
80958c78
C
213 this.descriptionLoading = true
214
2de96f4d 215 this.videoService.loadCompleteDescription(this.video.descriptionPath)
2186386c
C
216 .subscribe(
217 description => {
218 this.completeDescriptionShown = true
219 this.descriptionLoading = false
220
221 this.shortVideoDescription = this.video.description
222 this.completeVideoDescription = description
223
224 this.updateVideoDescription(this.completeVideoDescription)
225 },
226
227 error => {
228 this.descriptionLoading = false
f8b2c1b4 229 this.notifier.error(error.message)
2186386c
C
230 }
231 )
2de96f4d
C
232 }
233
07fa4c97 234 showSupportModal () {
689a4f69
C
235 this.pausePlayer()
236
07fa4c97
C
237 this.videoSupportModal.show()
238 }
239
df98563e 240 showShareModal () {
689a4f69
C
241 this.pausePlayer()
242
f0a39880 243 this.videoShareModal.show(this.currentTime)
99cc4f49
C
244 }
245
df98563e
C
246 isUserLoggedIn () {
247 return this.authService.isLoggedIn()
4f8c0eb0
C
248 }
249
b1fa3eba
C
250 getVideoTags () {
251 if (!this.video || Array.isArray(this.video.tags) === false) return []
252
4278710d 253 return this.video.tags
b1fa3eba
C
254 }
255
6aa54148
L
256 onRecommendations (videos: Video[]) {
257 if (videos.length > 0) {
3bcb4fd7
RK
258 // The recommended videos's first element should be the next video
259 const video = videos[0]
260 this.nextVideoUuid = video.uuid
261 this.nextVideoTitle = video.name
6aa54148
L
262 }
263 }
264
689a4f69
C
265 onModalOpened () {
266 this.pausePlayer()
267 }
268
3a0fb65c
C
269 onVideoRemoved () {
270 this.redirectService.redirectToHomepage()
6725d05c
C
271 }
272
d3217560
RK
273 declinedPrivacyConcern () {
274 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'false')
275 this.hasAlreadyAcceptedPrivacyConcern = false
276 }
277
73e09f27 278 acceptedPrivacyConcern () {
0bd78bf3 279 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
73e09f27
C
280 this.hasAlreadyAcceptedPrivacyConcern = true
281 }
282
2186386c
C
283 isVideoToTranscode () {
284 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
285 }
286
516df59b
C
287 isVideoToImport () {
288 return this.video && this.video.state.id === VideoState.TO_IMPORT
289 }
290
bbe0f064
C
291 hasVideoScheduledPublication () {
292 return this.video && this.video.scheduledUpdate !== undefined
293 }
294
e2f01c47 295 isVideoBlur (video: Video) {
ba430d75 296 return video.isVideoNSFWForUser(this.user, this.serverConfig)
e2f01c47
C
297 }
298
706c5a47
RK
299 isAutoPlayEnabled () {
300 return (
7c93905d 301 (this.user && this.user.autoPlayNextVideo) ||
d3217560 302 this.anonymousUser.autoPlayNextVideo
706c5a47 303 )
b29bf61d
RK
304 }
305
306 handleTimestampClicked (timestamp: number) {
307 if (this.player) this.player.currentTime(timestamp)
308 scrollToTop()
706c5a47
RK
309 }
310
311 isPlaylistAutoPlayEnabled () {
312 return (
7c93905d 313 (this.user && this.user.autoPlayNextVideoPlaylist) ||
d3217560 314 this.anonymousUser.autoPlayNextVideoPlaylist
706c5a47
RK
315 )
316 }
317
e2f01c47
C
318 private loadVideo (videoId: string) {
319 // Video did not change
320 if (this.video && this.video.uuid === videoId) return
321
322 if (this.player) this.player.pause()
323
93cae479
C
324 const videoObs = this.hooks.wrapObsFun(
325 this.videoService.getVideo.bind(this.videoService),
326 { videoId },
327 'video-watch',
328 'filter:api.video-watch.video.get.params',
329 'filter:api.video-watch.video.get.result'
330 )
331
e2f01c47 332 // Video did change
c8861d5d 333 forkJoin([
93cae479 334 videoObs,
e2f01c47 335 this.videoCaptionService.listCaptions(videoId)
c8861d5d 336 ])
e2f01c47
C
337 .pipe(
338 // If 401, the video is private or blacklisted so redirect to 404
339 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
340 )
341 .subscribe(([ video, captionsResult ]) => {
342 const queryParams = this.route.snapshot.queryParams
e2f01c47 343
4c72c1cd
C
344 const urlOptions = {
345 startTime: queryParams.start,
346 stopTime: queryParams.stop,
5efab546
C
347
348 muted: queryParams.muted,
349 loop: queryParams.loop,
4c72c1cd 350 subtitle: queryParams.subtitle,
5efab546
C
351
352 playerMode: queryParams.mode,
353 peertubeLink: false
4c72c1cd
C
354 }
355
356 this.onVideoFetched(video, captionsResult.data, urlOptions)
e2f01c47
C
357 .catch(err => this.handleError(err))
358 })
359 }
360
361 private loadPlaylist (playlistId: string) {
362 // Playlist did not change
363 if (this.playlist && this.playlist.uuid === playlistId) return
364
365 this.playlistService.getVideoPlaylist(playlistId)
366 .pipe(
367 // If 401, the video is private or blacklisted so redirect to 404
368 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
369 )
370 .subscribe(playlist => {
371 this.playlist = playlist
372
373 const videoId = this.route.snapshot.queryParams['videoId']
72675ebe 374 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
e2f01c47
C
375 })
376 }
377
2de96f4d
C
378 private updateVideoDescription (description: string) {
379 this.video.description = description
380 this.setVideoDescriptionHTML()
4c72c1cd 381 .catch(err => console.error(err))
2de96f4d
C
382 }
383
41d71344 384 private async setVideoDescriptionHTML () {
d68ebf0b
L
385 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
386 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
2de96f4d
C
387 }
388
e9189001 389 private setVideoLikesBarTooltipText () {
2186386c
C
390 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
391 likesNumber: this.video.likes,
392 dislikesNumber: this.video.dislikes
393 })
e9189001
C
394 }
395
0c31c33d
C
396 private handleError (err: any) {
397 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
398 if (!errorMessage) return
399
6d88de72 400 // Display a message in the video player instead of a notification
0f7fedc3 401 if (errorMessage.indexOf('from xs param') !== -1) {
6d88de72
C
402 this.flushPlayer()
403 this.remoteServerDown = true
3b492bff
C
404 this.changeDetector.detectChanges()
405
6d88de72 406 return
0c31c33d
C
407 }
408
f8b2c1b4 409 this.notifier.error(errorMessage)
0c31c33d
C
410 }
411
df98563e 412 private checkUserRating () {
d38b8281 413 // Unlogged users do not have ratings
df98563e 414 if (this.isUserLoggedIn() === false) return
d38b8281
C
415
416 this.videoService.getUserVideoRating(this.video.id)
2186386c
C
417 .subscribe(
418 ratingObject => {
419 if (ratingObject) {
420 this.userRating = ratingObject.rating
421 }
422 },
423
f8b2c1b4 424 err => this.notifier.error(err.message)
2186386c 425 )
d38b8281
C
426 }
427
597a9266
C
428 private async onVideoFetched (
429 video: VideoDetails,
430 videoCaptions: VideoCaption[],
5efab546 431 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
597a9266 432 ) {
df98563e 433 this.video = video
2f4c784a 434 this.videoCaptions = videoCaptions
92fb909c 435
c448d412
C
436 // Re init attributes
437 this.descriptionLoading = false
438 this.completeDescriptionShown = false
6d88de72 439 this.remoteServerDown = false
f0a39880 440 this.currentTime = undefined
c448d412 441
72675ebe 442 this.videoWatchPlaylist.updatePlaylistIndex(video)
e2f01c47 443
e2f01c47 444 if (this.isVideoBlur(this.video)) {
22b59e80 445 const res = await this.confirmService.confirm(
989e526a
C
446 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
447 this.i18n('Mature or explicit content')
d6e32a2e 448 )
60c2bc80 449 if (res === false) return this.location.back()
92fb909c
C
450 }
451
09edde40
C
452 // Flush old player if needed
453 this.flushPlayer()
b891f9bc 454
60c2bc80 455 // Build video element, because videojs removes it on dispose
e2f01c47 456 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
457 this.playerElement = document.createElement('video')
458 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 459 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
460 playerElementWrapper.appendChild(this.playerElement)
461
3d9a63d3
C
462 const params = {
463 video: this.video,
464 videoCaptions,
465 urlOptions,
466 user: this.user
e945b184 467 }
3d9a63d3
C
468 const { playerMode, playerOptions } = await this.hooks.wrapFun(
469 this.buildPlayerManagerOptions.bind(this),
470 params,
c2023a9f
C
471 'video-watch',
472 'filter:internal.video-watch.player.build-options.params',
3d9a63d3
C
473 'filter:internal.video-watch.player.build-options.result'
474 )
e945b184 475
e945b184 476 this.zone.runOutsideAngular(async () => {
3d9a63d3 477 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
d275e754 478 this.player.focus()
9a18a625 479
2adfc7ea 480 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
f0a39880
C
481
482 this.player.on('timeupdate', () => {
483 this.currentTime = Math.floor(this.player.currentTime())
484 })
e2f01c47 485
3bcb4fd7
RK
486 /**
487 * replaces this.player.one('ended')
223b24e6
RK
488 * 'condition()': true to make the upnext functionality trigger,
489 * false to disable the upnext functionality
490 * go to the next video in 'condition()' if you don't want of the timer.
491 * 'next': function triggered at the end of the timer.
492 * 'suspended': function used at each clic of the timer checking if we need
493 * to reset progress and wait until 'suspended' becomes truthy again.
3bcb4fd7
RK
494 */
495 this.player.upnext({
ddefb8c9 496 timeout: 10000, // 10s
3bcb4fd7
RK
497 headText: this.i18n('Up Next'),
498 cancelText: this.i18n('Cancel'),
223b24e6 499 suspendedText: this.i18n('Autoplay is suspended'),
3bcb4fd7
RK
500 getTitle: () => this.nextVideoTitle,
501 next: () => this.zone.run(() => this.autoplayNext()),
502 condition: () => {
503 if (this.playlist) {
504 if (this.isPlaylistAutoPlayEnabled()) {
505 // upnext will not trigger, and instead the next video will play immediately
506 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
507 }
508 } else if (this.isAutoPlayEnabled()) {
509 return true // upnext will trigger
510 }
511 return false // upnext will not trigger, and instead leave the video stopping
223b24e6
RK
512 },
513 suspended: () => {
514 return (
515 !isXPercentInViewport(this.player.el(), 80) ||
516 !document.getElementById('content').contains(document.activeElement)
517 )
e2f01c47
C
518 }
519 })
520
521 this.player.one('stopped', () => {
522 if (this.playlist) {
706c5a47 523 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
e2f01c47
C
524 }
525 })
9a18a625
C
526
527 this.player.on('theaterChange', (_: any, enabled: boolean) => {
528 this.zone.run(() => this.theaterEnabled = enabled)
529 })
5f85f8aa
RK
530
531 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
b891f9bc 532 })
22b59e80
C
533
534 this.setVideoDescriptionHTML()
535 this.setVideoLikesBarTooltipText()
536
537 this.setOpenGraphTags()
538 this.checkUserRating()
93cae479 539
5f85f8aa 540 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
92fb909c
C
541 }
542
6aa54148
L
543 private autoplayNext () {
544 if (this.nextVideoUuid) {
545 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
546 }
547 }
548
5c6d985f 549 private setRating (nextRating: UserVideoRateType) {
4c72c1cd
C
550 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
551 like: this.videoService.setVideoLike,
552 dislike: this.videoService.setVideoDislike,
553 none: this.videoService.unsetVideoLike
57a49263
BB
554 }
555
4c72c1cd 556 ratingMethods[nextRating].call(this.videoService, this.video.id)
2186386c
C
557 .subscribe(
558 () => {
559 // Update the video like attribute
560 this.updateVideoRating(this.userRating, nextRating)
561 this.userRating = nextRating
562 },
563
f8b2c1b4 564 (err: { message: string }) => this.notifier.error(err.message)
2186386c 565 )
57a49263
BB
566 }
567
5c6d985f 568 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
569 let likesToIncrement = 0
570 let dislikesToIncrement = 0
d38b8281
C
571
572 if (oldRating) {
df98563e
C
573 if (oldRating === 'like') likesToIncrement--
574 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
575 }
576
df98563e
C
577 if (newRating === 'like') likesToIncrement++
578 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 579
df98563e
C
580 this.video.likes += likesToIncrement
581 this.video.dislikes += dislikesToIncrement
20b40b19 582
22b59e80 583 this.video.buildLikeAndDislikePercents()
20b40b19 584 this.setVideoLikesBarTooltipText()
d38b8281
C
585 }
586
df98563e
C
587 private setOpenGraphTags () {
588 this.metaService.setTitle(this.video.name)
758b996d 589
df98563e 590 this.metaService.setTag('og:type', 'video')
3ec343a4 591
df98563e
C
592 this.metaService.setTag('og:title', this.video.name)
593 this.metaService.setTag('name', this.video.name)
3ec343a4 594
df98563e
C
595 this.metaService.setTag('og:description', this.video.description)
596 this.metaService.setTag('description', this.video.description)
3ec343a4 597
d38309c3 598 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 599
df98563e 600 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 601
df98563e 602 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 603
df98563e
C
604 this.metaService.setTag('og:url', window.location.href)
605 this.metaService.setTag('url', window.location.href)
3ec343a4 606 }
1f3e9fec 607
d4c6a3b9 608 private isAutoplay () {
bf079b7b
C
609 // We'll jump to the thread id, so do not play the video
610 if (this.route.snapshot.params['threadId']) return false
611
612 // Otherwise true by default
d4c6a3b9
C
613 if (!this.user) return true
614
615 // Be sure the autoPlay is set to false
616 return this.user.autoPlayVideo !== false
617 }
09edde40
C
618
619 private flushPlayer () {
620 // Remove player if it exists
621 if (this.player) {
536598cf
C
622 try {
623 this.player.dispose()
624 this.player = undefined
625 } catch (err) {
626 console.error('Cannot dispose player.', err)
627 }
09edde40
C
628 }
629 }
1c8ddbfa 630
3d9a63d3
C
631 private buildPlayerManagerOptions (params: {
632 video: VideoDetails,
633 videoCaptions: VideoCaption[],
634 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
635 user?: AuthUser
636 }) {
637 const { video, videoCaptions, urlOptions, user } = params
706c5a47
RK
638 const getStartTime = () => {
639 const byUrl = urlOptions.startTime !== undefined
96f6278f 640 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
706c5a47
RK
641
642 if (byUrl) {
643 return timeToInt(urlOptions.startTime)
644 } else if (byHistory) {
645 return video.userHistory.currentTime
646 } else {
647 return 0
648 }
649 }
3d9a63d3 650
706c5a47 651 let startTime = getStartTime()
3d9a63d3
C
652 // If we are at the end of the video, reset the timer
653 if (video.duration - startTime <= 1) startTime = 0
654
655 const playerCaptions = videoCaptions.map(c => ({
656 label: c.language.label,
657 language: c.language.id,
658 src: environment.apiUrl + c.captionPath
659 }))
660
661 const options: PeertubePlayerManagerOptions = {
662 common: {
663 autoplay: this.isAutoplay(),
1dc240a9 664 nextVideo: () => this.zone.run(() => this.autoplayNext()),
3d9a63d3
C
665
666 playerElement: this.playerElement,
667 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
668
669 videoDuration: video.duration,
670 enableHotkeys: true,
671 inactivityTimeout: 2500,
672 poster: video.previewUrl,
673
674 startTime,
675 stopTime: urlOptions.stopTime,
676 controls: urlOptions.controls,
677 muted: urlOptions.muted,
678 loop: urlOptions.loop,
679 subtitle: urlOptions.subtitle,
680
681 peertubeLink: urlOptions.peertubeLink,
682
683 theaterButton: true,
684 captions: videoCaptions.length !== 0,
685
686 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
687 ? this.videoService.getVideoViewUrl(video.uuid)
688 : null,
689 embedUrl: video.embedUrl,
690
691 language: this.localeId,
692
693 userWatching: user && user.videosHistoryEnabled === true ? {
694 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
695 authorizationHeader: this.authService.getRequestHeaderValue()
696 } : undefined,
697
698 serverUrl: environment.apiUrl,
699
700 videoCaptions: playerCaptions
701 },
702
703 webtorrent: {
704 videoFiles: video.files
705 }
706 }
707
708 let mode: PlayerMode
709
710 if (urlOptions.playerMode) {
711 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
712 else mode = 'webtorrent'
713 } else {
714 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
715 else mode = 'webtorrent'
716 }
717
718 if (mode === 'p2p-media-loader') {
719 const hlsPlaylist = video.getHlsPlaylist()
720
721 const p2pMediaLoader = {
722 playlistUrl: hlsPlaylist.playlistUrl,
723 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
724 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
725 trackerAnnounce: video.trackerUrls,
726 videoFiles: hlsPlaylist.files
727 } as P2PMediaLoaderOptions
728
729 Object.assign(options, { p2pMediaLoader })
730 }
731
732 return { playerMode: mode, playerOptions: options }
733 }
734
689a4f69
C
735 private pausePlayer () {
736 if (!this.player) return
737
738 this.player.pause()
739 }
941c5eac
C
740
741 private initHotkeys () {
742 this.hotkeys = [
941c5eac
C
743 // These hotkeys are managed by the player
744 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
745 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
746 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
747
748 new Hotkey('0-9', e => e, undefined, this.i18n('Skip to a percentage of the video: 0 is 0% and 9 is 90% (requires player focus)')),
749
750 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
751 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
752
753 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
754 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
755
756 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
757 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
758
759 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
760 ]
3d216ea0
C
761
762 if (this.isUserLoggedIn()) {
763 this.hotkeys = this.hotkeys.concat([
764 new Hotkey('shift+l', () => {
765 this.setLike()
766 return false
767 }, undefined, this.i18n('Like the video')),
768
769 new Hotkey('shift+d', () => {
770 this.setDislike()
771 return false
772 }, undefined, this.i18n('Dislike the video')),
773
774 new Hotkey('shift+s', () => {
775 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
776 return false
777 }, undefined, this.i18n('Subscribe to the account'))
778 ])
779 }
780
781 this.hotkeysService.add(this.hotkeys)
941c5eac 782 }
dc8bc31b 783}