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