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