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