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