]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/videos/+video-watch/video-watch.component.ts
add 'up next' screen on autoplay
[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'
88a7f93f 5import { peertubeLocalStorage, peertubeSessionStorage } 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'
72675ebe 11import { UserVideoRateType, VideoCaption, VideoPrivacy, VideoState } from '../../../../../shared'
df98563e 12import { AuthService, ConfirmService } from '../../core'
a51bad1a 13import { RestExtractor, VideoBlacklistService } 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'
011e1e6b 35import { getStoredTheater } from '../../../assets/player/peertube-player-local-storage'
18a6f04c 36import { PluginService } from '@app/core/plugins/plugin.service'
93cae479 37import { HooksService } from '@app/core/plugins/hooks.service'
60c2bc80 38import { PlatformLocation } from '@angular/common'
bee29df8 39import { RecommendedVideosComponent } from '../recommendations/recommended-videos.component'
b29bf61d 40import { scrollToTop } from '@app/shared/misc/utils'
dc8bc31b 41
dc8bc31b
C
42@Component({
43 selector: 'my-video-watch',
ec8d8440
C
44 templateUrl: './video-watch.component.html',
45 styleUrls: [ './video-watch.component.scss' ]
dc8bc31b 46})
0629423c 47export class VideoWatchComponent implements OnInit, OnDestroy {
22b59e80
C
48 private static LOCAL_STORAGE_PRIVACY_CONCERN_KEY = 'video-watch-privacy-concern'
49
f36da21e
C
50 @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent
51 @ViewChild('videoShareModal', { static: false }) videoShareModal: VideoShareComponent
52 @ViewChild('videoSupportModal', { static: false }) videoSupportModal: VideoSupportComponent
53 @ViewChild('subscribeButton', { static: false }) subscribeButton: SubscribeButtonComponent
df98563e 54
2adfc7ea 55 player: any
0826c92d 56 playerElement: HTMLVideoElement
9a18a625 57 theaterEnabled = false
154898b0 58 userRating: UserVideoRateType = null
80958c78 59 descriptionLoading = false
2de96f4d 60
2f4c784a
C
61 video: VideoDetails = null
62 videoCaptions: VideoCaption[] = []
63
e2f01c47 64 playlist: VideoPlaylist = null
e2f01c47 65
2de96f4d
C
66 completeDescriptionShown = false
67 completeVideoDescription: string
68 shortVideoDescription: string
9d9597df 69 videoHTMLDescription = ''
e9189001 70 likesBarTooltipText = ''
73e09f27 71 hasAlreadyAcceptedPrivacyConcern = false
6d88de72 72 remoteServerDown = false
3d216ea0 73 hotkeys: Hotkey[] = []
df98563e 74
94dfca3e
RK
75 tooltipLike = ''
76 tooltipDislike = ''
77 tooltipSupport = ''
78 tooltipSaveToPlaylist = ''
79
6aa54148 80 private nextVideoUuid = ''
3bcb4fd7 81 private nextVideoTitle = ''
f0a39880 82 private currentTime: number
df98563e 83 private paramsSub: Subscription
e2f01c47 84 private queryParamsSub: Subscription
31b6ddf8 85 private configSub: Subscription
df98563e
C
86
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,
35bf0c83 94 private videoBlacklistService: VideoBlacklistService,
92fb909c 95 private confirmService: ConfirmService,
3ec343a4 96 private metaService: MetaService,
7ddd02c9 97 private authService: AuthService,
0883b324 98 private serverService: ServerService,
a51bad1a 99 private restExtractor: RestExtractor,
f8b2c1b4 100 private notifier: Notifier,
18a6f04c 101 private pluginService: PluginService,
7ae71355 102 private markdownService: MarkdownService,
901637bb 103 private zone: NgZone,
989e526a 104 private redirectService: RedirectService,
16f7022b 105 private videoCaptionService: VideoCaptionService,
e945b184 106 private i18n: I18n,
20d21199 107 private hotkeysService: HotkeysService,
93cae479 108 private hooks: HooksService,
60c2bc80 109 private location: PlatformLocation,
e945b184 110 @Inject(LOCALE_ID) private localeId: string
94dfca3e
RK
111 ) {
112 this.tooltipLike = this.i18n('Like this video')
113 this.tooltipDislike = this.i18n('Dislike this video')
114 this.tooltipSupport = this.i18n('Support options for this video')
115 this.tooltipSaveToPlaylist = this.i18n('Save to playlist')
116 }
dc8bc31b 117
b2731bff
C
118 get user () {
119 return this.authService.getUser()
120 }
121
18a6f04c 122 async ngOnInit () {
31b6ddf8
C
123 this.configSub = this.serverService.configLoaded
124 .subscribe(() => {
125 if (
126 isWebRTCDisabled() ||
127 this.serverService.getConfig().tracker.enabled === false ||
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' ]
b29bf61d
RK
144 if (videoId) await this.loadVideo(videoId)
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
73e09f27 265 acceptedPrivacyConcern () {
0bd78bf3 266 peertubeLocalStorage.setItem(VideoWatchComponent.LOCAL_STORAGE_PRIVACY_CONCERN_KEY, 'true')
73e09f27
C
267 this.hasAlreadyAcceptedPrivacyConcern = true
268 }
269
2186386c
C
270 isVideoToTranscode () {
271 return this.video && this.video.state.id === VideoState.TO_TRANSCODE
272 }
273
516df59b
C
274 isVideoToImport () {
275 return this.video && this.video.state.id === VideoState.TO_IMPORT
276 }
277
bbe0f064
C
278 hasVideoScheduledPublication () {
279 return this.video && this.video.scheduledUpdate !== undefined
280 }
281
e2f01c47
C
282 isVideoBlur (video: Video) {
283 return video.isVideoNSFWForUser(this.user, this.serverService.getConfig())
284 }
285
706c5a47
RK
286 isAutoPlayEnabled () {
287 return (
7c93905d 288 (this.user && this.user.autoPlayNextVideo) ||
706c5a47
RK
289 peertubeSessionStorage.getItem(RecommendedVideosComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO) === 'true'
290 )
b29bf61d
RK
291 }
292
293 handleTimestampClicked (timestamp: number) {
294 if (this.player) this.player.currentTime(timestamp)
295 scrollToTop()
706c5a47
RK
296 }
297
298 isPlaylistAutoPlayEnabled () {
299 return (
7c93905d 300 (this.user && this.user.autoPlayNextVideoPlaylist) ||
706c5a47
RK
301 peertubeSessionStorage.getItem(VideoWatchPlaylistComponent.SESSION_STORAGE_AUTO_PLAY_NEXT_VIDEO_PLAYLIST) === 'true'
302 )
303 }
304
e2f01c47
C
305 private loadVideo (videoId: string) {
306 // Video did not change
307 if (this.video && this.video.uuid === videoId) return
308
309 if (this.player) this.player.pause()
310
93cae479
C
311 const videoObs = this.hooks.wrapObsFun(
312 this.videoService.getVideo.bind(this.videoService),
313 { videoId },
314 'video-watch',
315 'filter:api.video-watch.video.get.params',
316 'filter:api.video-watch.video.get.result'
317 )
318
e2f01c47 319 // Video did change
c8861d5d 320 forkJoin([
93cae479 321 videoObs,
e2f01c47 322 this.videoCaptionService.listCaptions(videoId)
c8861d5d 323 ])
e2f01c47
C
324 .pipe(
325 // If 401, the video is private or blacklisted so redirect to 404
326 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
327 )
328 .subscribe(([ video, captionsResult ]) => {
329 const queryParams = this.route.snapshot.queryParams
e2f01c47 330
4c72c1cd
C
331 const urlOptions = {
332 startTime: queryParams.start,
333 stopTime: queryParams.stop,
5efab546
C
334
335 muted: queryParams.muted,
336 loop: queryParams.loop,
4c72c1cd 337 subtitle: queryParams.subtitle,
5efab546
C
338
339 playerMode: queryParams.mode,
340 peertubeLink: false
4c72c1cd
C
341 }
342
343 this.onVideoFetched(video, captionsResult.data, urlOptions)
e2f01c47
C
344 .catch(err => this.handleError(err))
345 })
346 }
347
348 private loadPlaylist (playlistId: string) {
349 // Playlist did not change
350 if (this.playlist && this.playlist.uuid === playlistId) return
351
352 this.playlistService.getVideoPlaylist(playlistId)
353 .pipe(
354 // If 401, the video is private or blacklisted so redirect to 404
355 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, [ 400, 401, 403, 404 ]))
356 )
357 .subscribe(playlist => {
358 this.playlist = playlist
359
360 const videoId = this.route.snapshot.queryParams['videoId']
72675ebe 361 this.videoWatchPlaylist.loadPlaylistElements(playlist, !videoId)
e2f01c47
C
362 })
363 }
364
2de96f4d
C
365 private updateVideoDescription (description: string) {
366 this.video.description = description
367 this.setVideoDescriptionHTML()
4c72c1cd 368 .catch(err => console.error(err))
2de96f4d
C
369 }
370
41d71344 371 private async setVideoDescriptionHTML () {
d68ebf0b
L
372 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
373 this.videoHTMLDescription = await this.markdownService.processVideoTimestamps(html)
2de96f4d
C
374 }
375
e9189001 376 private setVideoLikesBarTooltipText () {
2186386c
C
377 this.likesBarTooltipText = this.i18n('{{likesNumber}} likes / {{dislikesNumber}} dislikes', {
378 likesNumber: this.video.likes,
379 dislikesNumber: this.video.dislikes
380 })
e9189001
C
381 }
382
0c31c33d
C
383 private handleError (err: any) {
384 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
385 if (!errorMessage) return
386
6d88de72 387 // Display a message in the video player instead of a notification
0f7fedc3 388 if (errorMessage.indexOf('from xs param') !== -1) {
6d88de72
C
389 this.flushPlayer()
390 this.remoteServerDown = true
3b492bff
C
391 this.changeDetector.detectChanges()
392
6d88de72 393 return
0c31c33d
C
394 }
395
f8b2c1b4 396 this.notifier.error(errorMessage)
0c31c33d
C
397 }
398
df98563e 399 private checkUserRating () {
d38b8281 400 // Unlogged users do not have ratings
df98563e 401 if (this.isUserLoggedIn() === false) return
d38b8281
C
402
403 this.videoService.getUserVideoRating(this.video.id)
2186386c
C
404 .subscribe(
405 ratingObject => {
406 if (ratingObject) {
407 this.userRating = ratingObject.rating
408 }
409 },
410
f8b2c1b4 411 err => this.notifier.error(err.message)
2186386c 412 )
d38b8281
C
413 }
414
597a9266
C
415 private async onVideoFetched (
416 video: VideoDetails,
417 videoCaptions: VideoCaption[],
5efab546 418 urlOptions: CustomizationOptions & { playerMode: PlayerMode }
597a9266 419 ) {
df98563e 420 this.video = video
2f4c784a 421 this.videoCaptions = videoCaptions
92fb909c 422
c448d412
C
423 // Re init attributes
424 this.descriptionLoading = false
425 this.completeDescriptionShown = false
6d88de72 426 this.remoteServerDown = false
f0a39880 427 this.currentTime = undefined
c448d412 428
72675ebe 429 this.videoWatchPlaylist.updatePlaylistIndex(video)
e2f01c47 430
e2f01c47 431 if (this.isVideoBlur(this.video)) {
22b59e80 432 const res = await this.confirmService.confirm(
989e526a
C
433 this.i18n('This video contains mature or explicit content. Are you sure you want to watch it?'),
434 this.i18n('Mature or explicit content')
d6e32a2e 435 )
60c2bc80 436 if (res === false) return this.location.back()
92fb909c
C
437 }
438
09edde40
C
439 // Flush old player if needed
440 this.flushPlayer()
b891f9bc 441
60c2bc80 442 // Build video element, because videojs removes it on dispose
e2f01c47 443 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
444 this.playerElement = document.createElement('video')
445 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 446 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
447 playerElementWrapper.appendChild(this.playerElement)
448
3d9a63d3
C
449 const params = {
450 video: this.video,
451 videoCaptions,
452 urlOptions,
453 user: this.user
e945b184 454 }
3d9a63d3
C
455 const { playerMode, playerOptions } = await this.hooks.wrapFun(
456 this.buildPlayerManagerOptions.bind(this),
457 params,
c2023a9f
C
458 'video-watch',
459 'filter:internal.video-watch.player.build-options.params',
3d9a63d3
C
460 'filter:internal.video-watch.player.build-options.result'
461 )
e945b184 462
e945b184 463 this.zone.runOutsideAngular(async () => {
3d9a63d3 464 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
d275e754 465 this.player.focus()
9a18a625 466
2adfc7ea 467 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
f0a39880
C
468
469 this.player.on('timeupdate', () => {
470 this.currentTime = Math.floor(this.player.currentTime())
471 })
e2f01c47 472
3bcb4fd7
RK
473 /**
474 * replaces this.player.one('ended')
475 * define 'condition(next)' to return true to wait, false to stop
476 */
477 this.player.upnext({
478 timeout: 1000000,
479 headText: this.i18n('Up Next'),
480 cancelText: this.i18n('Cancel'),
481 getTitle: () => this.nextVideoTitle,
482 next: () => this.zone.run(() => this.autoplayNext()),
483 condition: () => {
484 if (this.playlist) {
485 if (this.isPlaylistAutoPlayEnabled()) {
486 // upnext will not trigger, and instead the next video will play immediately
487 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
488 }
489 } else if (this.isAutoPlayEnabled()) {
490 return true // upnext will trigger
491 }
492 return false // upnext will not trigger, and instead leave the video stopping
e2f01c47
C
493 }
494 })
495
496 this.player.one('stopped', () => {
497 if (this.playlist) {
706c5a47 498 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
e2f01c47
C
499 }
500 })
9a18a625
C
501
502 this.player.on('theaterChange', (_: any, enabled: boolean) => {
503 this.zone.run(() => this.theaterEnabled = enabled)
504 })
5f85f8aa
RK
505
506 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player })
b891f9bc 507 })
22b59e80
C
508
509 this.setVideoDescriptionHTML()
510 this.setVideoLikesBarTooltipText()
511
512 this.setOpenGraphTags()
513 this.checkUserRating()
93cae479 514
5f85f8aa 515 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', { videojs })
92fb909c
C
516 }
517
6aa54148
L
518 private autoplayNext () {
519 if (this.nextVideoUuid) {
520 this.router.navigate([ '/videos/watch', this.nextVideoUuid ])
521 }
522 }
523
5c6d985f 524 private setRating (nextRating: UserVideoRateType) {
4c72c1cd
C
525 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
526 like: this.videoService.setVideoLike,
527 dislike: this.videoService.setVideoDislike,
528 none: this.videoService.unsetVideoLike
57a49263
BB
529 }
530
4c72c1cd 531 ratingMethods[nextRating].call(this.videoService, this.video.id)
2186386c
C
532 .subscribe(
533 () => {
534 // Update the video like attribute
535 this.updateVideoRating(this.userRating, nextRating)
536 this.userRating = nextRating
537 },
538
f8b2c1b4 539 (err: { message: string }) => this.notifier.error(err.message)
2186386c 540 )
57a49263
BB
541 }
542
5c6d985f 543 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
544 let likesToIncrement = 0
545 let dislikesToIncrement = 0
d38b8281
C
546
547 if (oldRating) {
df98563e
C
548 if (oldRating === 'like') likesToIncrement--
549 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
550 }
551
df98563e
C
552 if (newRating === 'like') likesToIncrement++
553 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 554
df98563e
C
555 this.video.likes += likesToIncrement
556 this.video.dislikes += dislikesToIncrement
20b40b19 557
22b59e80 558 this.video.buildLikeAndDislikePercents()
20b40b19 559 this.setVideoLikesBarTooltipText()
d38b8281
C
560 }
561
df98563e
C
562 private setOpenGraphTags () {
563 this.metaService.setTitle(this.video.name)
758b996d 564
df98563e 565 this.metaService.setTag('og:type', 'video')
3ec343a4 566
df98563e
C
567 this.metaService.setTag('og:title', this.video.name)
568 this.metaService.setTag('name', this.video.name)
3ec343a4 569
df98563e
C
570 this.metaService.setTag('og:description', this.video.description)
571 this.metaService.setTag('description', this.video.description)
3ec343a4 572
d38309c3 573 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 574
df98563e 575 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 576
df98563e 577 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 578
df98563e
C
579 this.metaService.setTag('og:url', window.location.href)
580 this.metaService.setTag('url', window.location.href)
3ec343a4 581 }
1f3e9fec 582
d4c6a3b9 583 private isAutoplay () {
bf079b7b
C
584 // We'll jump to the thread id, so do not play the video
585 if (this.route.snapshot.params['threadId']) return false
586
587 // Otherwise true by default
d4c6a3b9
C
588 if (!this.user) return true
589
590 // Be sure the autoPlay is set to false
591 return this.user.autoPlayVideo !== false
592 }
09edde40
C
593
594 private flushPlayer () {
595 // Remove player if it exists
596 if (this.player) {
536598cf
C
597 try {
598 this.player.dispose()
599 this.player = undefined
600 } catch (err) {
601 console.error('Cannot dispose player.', err)
602 }
09edde40
C
603 }
604 }
1c8ddbfa 605
3d9a63d3
C
606 private buildPlayerManagerOptions (params: {
607 video: VideoDetails,
608 videoCaptions: VideoCaption[],
609 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
610 user?: AuthUser
611 }) {
612 const { video, videoCaptions, urlOptions, user } = params
706c5a47
RK
613 const getStartTime = () => {
614 const byUrl = urlOptions.startTime !== undefined
615 const byHistory = video.userHistory && !this.playlist
616
617 if (byUrl) {
618 return timeToInt(urlOptions.startTime)
619 } else if (byHistory) {
620 return video.userHistory.currentTime
621 } else {
622 return 0
623 }
624 }
3d9a63d3 625
706c5a47 626 let startTime = getStartTime()
3d9a63d3
C
627 // If we are at the end of the video, reset the timer
628 if (video.duration - startTime <= 1) startTime = 0
629
630 const playerCaptions = videoCaptions.map(c => ({
631 label: c.language.label,
632 language: c.language.id,
633 src: environment.apiUrl + c.captionPath
634 }))
635
636 const options: PeertubePlayerManagerOptions = {
637 common: {
638 autoplay: this.isAutoplay(),
639
640 playerElement: this.playerElement,
641 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
642
643 videoDuration: video.duration,
644 enableHotkeys: true,
645 inactivityTimeout: 2500,
646 poster: video.previewUrl,
647
648 startTime,
649 stopTime: urlOptions.stopTime,
650 controls: urlOptions.controls,
651 muted: urlOptions.muted,
652 loop: urlOptions.loop,
653 subtitle: urlOptions.subtitle,
654
655 peertubeLink: urlOptions.peertubeLink,
656
657 theaterButton: true,
658 captions: videoCaptions.length !== 0,
659
660 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
661 ? this.videoService.getVideoViewUrl(video.uuid)
662 : null,
663 embedUrl: video.embedUrl,
664
665 language: this.localeId,
666
667 userWatching: user && user.videosHistoryEnabled === true ? {
668 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
669 authorizationHeader: this.authService.getRequestHeaderValue()
670 } : undefined,
671
672 serverUrl: environment.apiUrl,
673
674 videoCaptions: playerCaptions
675 },
676
677 webtorrent: {
678 videoFiles: video.files
679 }
680 }
681
682 let mode: PlayerMode
683
684 if (urlOptions.playerMode) {
685 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
686 else mode = 'webtorrent'
687 } else {
688 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
689 else mode = 'webtorrent'
690 }
691
692 if (mode === 'p2p-media-loader') {
693 const hlsPlaylist = video.getHlsPlaylist()
694
695 const p2pMediaLoader = {
696 playlistUrl: hlsPlaylist.playlistUrl,
697 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
698 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
699 trackerAnnounce: video.trackerUrls,
700 videoFiles: hlsPlaylist.files
701 } as P2PMediaLoaderOptions
702
703 Object.assign(options, { p2pMediaLoader })
704 }
705
706 return { playerMode: mode, playerOptions: options }
707 }
708
689a4f69
C
709 private pausePlayer () {
710 if (!this.player) return
711
712 this.player.pause()
713 }
941c5eac
C
714
715 private initHotkeys () {
716 this.hotkeys = [
941c5eac
C
717 // These hotkeys are managed by the player
718 new Hotkey('f', e => e, undefined, this.i18n('Enter/exit fullscreen (requires player focus)')),
719 new Hotkey('space', e => e, undefined, this.i18n('Play/Pause the video (requires player focus)')),
720 new Hotkey('m', e => e, undefined, this.i18n('Mute/unmute the video (requires player focus)')),
721
722 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)')),
723
724 new Hotkey('up', e => e, undefined, this.i18n('Increase the volume (requires player focus)')),
725 new Hotkey('down', e => e, undefined, this.i18n('Decrease the volume (requires player focus)')),
726
727 new Hotkey('right', e => e, undefined, this.i18n('Seek the video forward (requires player focus)')),
728 new Hotkey('left', e => e, undefined, this.i18n('Seek the video backward (requires player focus)')),
729
730 new Hotkey('>', e => e, undefined, this.i18n('Increase playback rate (requires player focus)')),
731 new Hotkey('<', e => e, undefined, this.i18n('Decrease playback rate (requires player focus)')),
732
733 new Hotkey('.', e => e, undefined, this.i18n('Navigate in the video frame by frame (requires player focus)'))
734 ]
3d216ea0
C
735
736 if (this.isUserLoggedIn()) {
737 this.hotkeys = this.hotkeys.concat([
738 new Hotkey('shift+l', () => {
739 this.setLike()
740 return false
741 }, undefined, this.i18n('Like the video')),
742
743 new Hotkey('shift+d', () => {
744 this.setDislike()
745 return false
746 }, undefined, this.i18n('Dislike the video')),
747
748 new Hotkey('shift+s', () => {
749 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
750 return false
751 }, undefined, this.i18n('Subscribe to the account'))
752 ])
753 }
754
755 this.hotkeysService.add(this.hotkeys)
941c5eac 756 }
dc8bc31b 757}