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