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