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