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