]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/app/+videos/+video-watch/video-watch.component.ts
refactor API errors to standard error format
[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'
e6abf95e 31import { 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 => {
76148b27 434 if (err.body.type === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && err.body.originUrl) {
e6abf95e
C
435 const search = window.location.search
436 let originUrl = err.body.originUrl
437 if (search) originUrl += search
438
439 this.confirmService.confirm(
440 $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`,
441 $localize`Redirection`
442 ).then(res => {
f2eb23cd 443 if (res === false) {
ab398a05 444 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
f2eb23cd 445 HttpStatusCode.BAD_REQUEST_400,
f2eb23cd
RK
446 HttpStatusCode.FORBIDDEN_403,
447 HttpStatusCode.NOT_FOUND_404
448 ])
449 }
e6abf95e
C
450
451 return window.location.href = originUrl
452 })
453 }
454
ab398a05 455 return this.restExtractor.redirectTo404IfNotFound(err, 'video', [
f2eb23cd 456 HttpStatusCode.BAD_REQUEST_400,
f2eb23cd
RK
457 HttpStatusCode.FORBIDDEN_403,
458 HttpStatusCode.NOT_FOUND_404
459 ])
e6abf95e 460 })
e2f01c47
C
461 )
462 .subscribe(([ video, captionsResult ]) => {
463 const queryParams = this.route.snapshot.queryParams
e2f01c47 464
4c72c1cd 465 const urlOptions = {
3c6a44a1
C
466 resume: queryParams.resume,
467
4c72c1cd
C
468 startTime: queryParams.start,
469 stopTime: queryParams.stop,
5efab546
C
470
471 muted: queryParams.muted,
472 loop: queryParams.loop,
4c72c1cd 473 subtitle: queryParams.subtitle,
5efab546
C
474
475 playerMode: queryParams.mode,
476 peertubeLink: false
4c72c1cd
C
477 }
478
479 this.onVideoFetched(video, captionsResult.data, urlOptions)
e2f01c47
C
480 .catch(err => this.handleError(err))
481 })
482 }
483
484 private loadPlaylist (playlistId: string) {
485 // Playlist did not change
486 if (this.playlist && this.playlist.uuid === playlistId) return
487
488 this.playlistService.getVideoPlaylist(playlistId)
489 .pipe(
ab398a05
RK
490 // If 400 or 403, the video is private or blocked so redirect to 404
491 catchError(err => this.restExtractor.redirectTo404IfNotFound(err, 'video', [
f2eb23cd 492 HttpStatusCode.BAD_REQUEST_400,
f2eb23cd
RK
493 HttpStatusCode.FORBIDDEN_403,
494 HttpStatusCode.NOT_FOUND_404
495 ]))
e2f01c47
C
496 )
497 .subscribe(playlist => {
498 this.playlist = playlist
499
d142c7b9 500 this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition)
e2f01c47
C
501 })
502 }
503
2de96f4d
C
504 private updateVideoDescription (description: string) {
505 this.video.description = description
506 this.setVideoDescriptionHTML()
4c72c1cd 507 .catch(err => console.error(err))
2de96f4d
C
508 }
509
41d71344 510 private async setVideoDescriptionHTML () {
d68ebf0b 511 const html = await this.markdownService.textMarkdownToHTML(this.video.description)
2539932e 512 this.videoHTMLDescription = this.markdownService.processVideoTimestamps(html)
2de96f4d
C
513 }
514
e9189001 515 private setVideoLikesBarTooltipText () {
66357162 516 this.likesBarTooltipText = `${this.video.likes} likes / ${this.video.dislikes} dislikes`
e9189001
C
517 }
518
0c31c33d
C
519 private handleError (err: any) {
520 const errorMessage: string = typeof err === 'string' ? err : err.message
bf5685f0
C
521 if (!errorMessage) return
522
6d88de72 523 // Display a message in the video player instead of a notification
0f7fedc3 524 if (errorMessage.indexOf('from xs param') !== -1) {
6d88de72
C
525 this.flushPlayer()
526 this.remoteServerDown = true
3b492bff
C
527 this.changeDetector.detectChanges()
528
6d88de72 529 return
0c31c33d
C
530 }
531
f8b2c1b4 532 this.notifier.error(errorMessage)
0c31c33d
C
533 }
534
df98563e 535 private checkUserRating () {
d38b8281 536 // Unlogged users do not have ratings
df98563e 537 if (this.isUserLoggedIn() === false) return
d38b8281
C
538
539 this.videoService.getUserVideoRating(this.video.id)
2186386c
C
540 .subscribe(
541 ratingObject => {
542 if (ratingObject) {
543 this.userRating = ratingObject.rating
544 }
545 },
546
f8b2c1b4 547 err => this.notifier.error(err.message)
2186386c 548 )
d38b8281
C
549 }
550
597a9266
C
551 private async onVideoFetched (
552 video: VideoDetails,
553 videoCaptions: VideoCaption[],
a5cf76af 554 urlOptions: URLOptions
597a9266 555 ) {
a5cf76af
C
556 this.subscribeToLiveEventsIfNeeded(this.video, video)
557
df98563e 558 this.video = video
2f4c784a 559 this.videoCaptions = videoCaptions
92fb909c 560
c448d412 561 // Re init attributes
c15d61f5 562 this.playerPlaceholderImgSrc = undefined
c448d412
C
563 this.descriptionLoading = false
564 this.completeDescriptionShown = false
06bee937 565 this.completeVideoDescription = undefined
6d88de72 566 this.remoteServerDown = false
f0a39880 567 this.currentTime = undefined
c448d412 568
e2f01c47 569 if (this.isVideoBlur(this.video)) {
22b59e80 570 const res = await this.confirmService.confirm(
66357162
C
571 $localize`This video contains mature or explicit content. Are you sure you want to watch it?`,
572 $localize`Mature or explicit content`
d6e32a2e 573 )
60c2bc80 574 if (res === false) return this.location.back()
92fb909c
C
575 }
576
0a6817f0
C
577 this.buildPlayer(urlOptions)
578 .catch(err => console.error('Cannot build the player', err))
579
580 this.setVideoDescriptionHTML()
581 this.setVideoLikesBarTooltipText()
582
583 this.setOpenGraphTags()
584 this.checkUserRating()
585
55b84d53
C
586 const hookOptions = {
587 videojs,
588 video: this.video,
589 playlist: this.playlist
590 }
591 this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions)
0a6817f0
C
592 }
593
594 private async buildPlayer (urlOptions: URLOptions) {
09edde40
C
595 // Flush old player if needed
596 this.flushPlayer()
b891f9bc 597
c15d61f5
C
598 const videoState = this.video.state.id
599 if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) {
600 this.playerPlaceholderImgSrc = this.video.previewPath
601 return
602 }
603
60c2bc80 604 // Build video element, because videojs removes it on dispose
e2f01c47 605 const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper')
b891f9bc
C
606 this.playerElement = document.createElement('video')
607 this.playerElement.className = 'video-js vjs-peertube-skin'
e7eb5b39 608 this.playerElement.setAttribute('playsinline', 'true')
b891f9bc
C
609 playerElementWrapper.appendChild(this.playerElement)
610
3d9a63d3
C
611 const params = {
612 video: this.video,
0a6817f0 613 videoCaptions: this.videoCaptions,
3d9a63d3
C
614 urlOptions,
615 user: this.user
e945b184 616 }
3d9a63d3
C
617 const { playerMode, playerOptions } = await this.hooks.wrapFun(
618 this.buildPlayerManagerOptions.bind(this),
619 params,
c2023a9f
C
620 'video-watch',
621 'filter:internal.video-watch.player.build-options.params',
3d9a63d3
C
622 'filter:internal.video-watch.player.build-options.result'
623 )
e945b184 624
e945b184 625 this.zone.runOutsideAngular(async () => {
3d9a63d3 626 this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player)
9a18a625 627
2adfc7ea 628 this.player.on('customError', ({ err }: { err: any }) => this.handleError(err))
f0a39880
C
629
630 this.player.on('timeupdate', () => {
631 this.currentTime = Math.floor(this.player.currentTime())
632 })
e2f01c47 633
3bcb4fd7
RK
634 /**
635 * replaces this.player.one('ended')
223b24e6
RK
636 * 'condition()': true to make the upnext functionality trigger,
637 * false to disable the upnext functionality
638 * go to the next video in 'condition()' if you don't want of the timer.
639 * 'next': function triggered at the end of the timer.
640 * 'suspended': function used at each clic of the timer checking if we need
641 * to reset progress and wait until 'suspended' becomes truthy again.
3bcb4fd7
RK
642 */
643 this.player.upnext({
ddefb8c9 644 timeout: 10000, // 10s
66357162
C
645 headText: $localize`Up Next`,
646 cancelText: $localize`Cancel`,
647 suspendedText: $localize`Autoplay is suspended`,
3bcb4fd7
RK
648 getTitle: () => this.nextVideoTitle,
649 next: () => this.zone.run(() => this.autoplayNext()),
650 condition: () => {
651 if (this.playlist) {
652 if (this.isPlaylistAutoPlayEnabled()) {
653 // upnext will not trigger, and instead the next video will play immediately
654 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
655 }
656 } else if (this.isAutoPlayEnabled()) {
657 return true // upnext will trigger
658 }
659 return false // upnext will not trigger, and instead leave the video stopping
223b24e6
RK
660 },
661 suspended: () => {
662 return (
663 !isXPercentInViewport(this.player.el(), 80) ||
664 !document.getElementById('content').contains(document.activeElement)
665 )
e2f01c47
C
666 }
667 })
668
669 this.player.one('stopped', () => {
670 if (this.playlist) {
706c5a47 671 if (this.isPlaylistAutoPlayEnabled()) this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
e2f01c47
C
672 }
673 })
9a18a625 674
e772bdf1
C
675 this.player.one('ended', () => {
676 if (this.video.isLive) {
ceb8f322 677 this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED)
e772bdf1
C
678 }
679 })
680
9a18a625
C
681 this.player.on('theaterChange', (_: any, enabled: boolean) => {
682 this.zone.run(() => this.theaterEnabled = enabled)
683 })
5f85f8aa 684
781ba981 685 this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video })
b891f9bc 686 })
92fb909c
C
687 }
688
6aa54148 689 private autoplayNext () {
6dd873d6
RK
690 if (this.playlist) {
691 this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo())
692 } else if (this.nextVideoUuid) {
a1eda903 693 this.router.navigate([ '/w', this.nextVideoUuid ])
6aa54148
L
694 }
695 }
696
5c6d985f 697 private setRating (nextRating: UserVideoRateType) {
4c72c1cd
C
698 const ratingMethods: { [id in UserVideoRateType]: (id: number) => Observable<any> } = {
699 like: this.videoService.setVideoLike,
700 dislike: this.videoService.setVideoDislike,
701 none: this.videoService.unsetVideoLike
57a49263
BB
702 }
703
4c72c1cd 704 ratingMethods[nextRating].call(this.videoService, this.video.id)
2186386c
C
705 .subscribe(
706 () => {
707 // Update the video like attribute
708 this.updateVideoRating(this.userRating, nextRating)
709 this.userRating = nextRating
710 },
711
f8b2c1b4 712 (err: { message: string }) => this.notifier.error(err.message)
2186386c 713 )
57a49263
BB
714 }
715
5c6d985f 716 private updateVideoRating (oldRating: UserVideoRateType, newRating: UserVideoRateType) {
df98563e
C
717 let likesToIncrement = 0
718 let dislikesToIncrement = 0
d38b8281
C
719
720 if (oldRating) {
df98563e
C
721 if (oldRating === 'like') likesToIncrement--
722 if (oldRating === 'dislike') dislikesToIncrement--
d38b8281
C
723 }
724
df98563e
C
725 if (newRating === 'like') likesToIncrement++
726 if (newRating === 'dislike') dislikesToIncrement++
d38b8281 727
df98563e
C
728 this.video.likes += likesToIncrement
729 this.video.dislikes += dislikesToIncrement
20b40b19 730
22b59e80 731 this.video.buildLikeAndDislikePercents()
20b40b19 732 this.setVideoLikesBarTooltipText()
d38b8281
C
733 }
734
df98563e
C
735 private setOpenGraphTags () {
736 this.metaService.setTitle(this.video.name)
758b996d 737
df98563e 738 this.metaService.setTag('og:type', 'video')
3ec343a4 739
df98563e
C
740 this.metaService.setTag('og:title', this.video.name)
741 this.metaService.setTag('name', this.video.name)
3ec343a4 742
df98563e
C
743 this.metaService.setTag('og:description', this.video.description)
744 this.metaService.setTag('description', this.video.description)
3ec343a4 745
d38309c3 746 this.metaService.setTag('og:image', this.video.previewPath)
3ec343a4 747
df98563e 748 this.metaService.setTag('og:duration', this.video.duration.toString())
3ec343a4 749
df98563e 750 this.metaService.setTag('og:site_name', 'PeerTube')
3ec343a4 751
df98563e
C
752 this.metaService.setTag('og:url', window.location.href)
753 this.metaService.setTag('url', window.location.href)
3ec343a4 754 }
1f3e9fec 755
d4c6a3b9 756 private isAutoplay () {
bf079b7b
C
757 // We'll jump to the thread id, so do not play the video
758 if (this.route.snapshot.params['threadId']) return false
759
760 // Otherwise true by default
d4c6a3b9
C
761 if (!this.user) return true
762
763 // Be sure the autoPlay is set to false
764 return this.user.autoPlayVideo !== false
765 }
09edde40
C
766
767 private flushPlayer () {
768 // Remove player if it exists
769 if (this.player) {
536598cf
C
770 try {
771 this.player.dispose()
772 this.player = undefined
773 } catch (err) {
774 console.error('Cannot dispose player.', err)
775 }
09edde40
C
776 }
777 }
1c8ddbfa 778
3d9a63d3
C
779 private buildPlayerManagerOptions (params: {
780 video: VideoDetails,
781 videoCaptions: VideoCaption[],
782 urlOptions: CustomizationOptions & { playerMode: PlayerMode },
783 user?: AuthUser
784 }) {
785 const { video, videoCaptions, urlOptions, user } = params
706c5a47
RK
786 const getStartTime = () => {
787 const byUrl = urlOptions.startTime !== undefined
96f6278f 788 const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined)
58b9ce30 789 const byLocalStorage = getStoredVideoWatchHistory(video.uuid)
706c5a47 790
3c6a44a1
C
791 if (byUrl) return timeToInt(urlOptions.startTime)
792 if (byHistory) return video.userHistory.currentTime
58b9ce30 793 if (byLocalStorage) return byLocalStorage.duration
3c6a44a1
C
794
795 return 0
706c5a47 796 }
3d9a63d3 797
706c5a47 798 let startTime = getStartTime()
3c6a44a1 799
3d9a63d3
C
800 // If we are at the end of the video, reset the timer
801 if (video.duration - startTime <= 1) startTime = 0
802
803 const playerCaptions = videoCaptions.map(c => ({
804 label: c.language.label,
805 language: c.language.id,
806 src: environment.apiUrl + c.captionPath
807 }))
808
809 const options: PeertubePlayerManagerOptions = {
810 common: {
811 autoplay: this.isAutoplay(),
1dc240a9 812 nextVideo: () => this.zone.run(() => this.autoplayNext()),
3d9a63d3
C
813
814 playerElement: this.playerElement,
815 onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element,
816
817 videoDuration: video.duration,
818 enableHotkeys: true,
819 inactivityTimeout: 2500,
820 poster: video.previewUrl,
821
822 startTime,
823 stopTime: urlOptions.stopTime,
824 controls: urlOptions.controls,
825 muted: urlOptions.muted,
826 loop: urlOptions.loop,
827 subtitle: urlOptions.subtitle,
828
829 peertubeLink: urlOptions.peertubeLink,
830
831 theaterButton: true,
832 captions: videoCaptions.length !== 0,
833
834 videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE
835 ? this.videoService.getVideoViewUrl(video.uuid)
836 : null,
837 embedUrl: video.embedUrl,
4097c6d6 838 embedTitle: video.name,
3d9a63d3 839
25b7c847
C
840 isLive: video.isLive,
841
3d9a63d3
C
842 language: this.localeId,
843
844 userWatching: user && user.videosHistoryEnabled === true ? {
845 url: this.videoService.getUserWatchingVideoUrl(video.uuid),
846 authorizationHeader: this.authService.getRequestHeaderValue()
847 } : undefined,
848
849 serverUrl: environment.apiUrl,
850
58b9ce30 851 videoCaptions: playerCaptions,
852
3e0e8d4a 853 videoUUID: video.uuid
3d9a63d3
C
854 },
855
856 webtorrent: {
857 videoFiles: video.files
858 }
859 }
860
dfdcbb94 861 // Only set this if we're in a playlist
5bb2ed6b
P
862 if (this.playlist) {
863 options.common.previousVideo = () => {
864 this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo())
865 }
dfdcbb94
P
866 }
867
3d9a63d3
C
868 let mode: PlayerMode
869
870 if (urlOptions.playerMode) {
871 if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader'
872 else mode = 'webtorrent'
873 } else {
874 if (video.hasHlsPlaylist()) mode = 'p2p-media-loader'
875 else mode = 'webtorrent'
876 }
877
089af69b
C
878 // p2p-media-loader needs TextEncoder, try to fallback on WebTorrent
879 if (typeof TextEncoder === 'undefined') {
880 mode = 'webtorrent'
881 }
882
3d9a63d3
C
883 if (mode === 'p2p-media-loader') {
884 const hlsPlaylist = video.getHlsPlaylist()
885
886 const p2pMediaLoader = {
887 playlistUrl: hlsPlaylist.playlistUrl,
888 segmentsSha256Url: hlsPlaylist.segmentsSha256Url,
889 redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl),
890 trackerAnnounce: video.trackerUrls,
891 videoFiles: hlsPlaylist.files
892 } as P2PMediaLoaderOptions
893
894 Object.assign(options, { p2pMediaLoader })
895 }
896
897 return { playerMode: mode, playerOptions: options }
898 }
899
a5cf76af
C
900 private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) {
901 if (!this.liveVideosSub) {
a800dbf3 902 this.liveVideosSub = this.buildLiveEventsSubscription()
a5cf76af
C
903 }
904
905 if (oldVideo && oldVideo.id !== newVideo.id) {
906 await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id)
907 }
908
909 if (!newVideo.isLive) return
910
911 await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id)
912 }
913
a800dbf3
C
914 private buildLiveEventsSubscription () {
915 return this.peertubeSocket.getLiveVideosObservable()
916 .subscribe(({ type, payload }) => {
917 if (type === 'state-change') return this.handleLiveStateChange(payload.state)
918 if (type === 'views-change') return this.handleLiveViewsChange(payload.views)
919 })
920 }
921
922 private handleLiveStateChange (newState: VideoState) {
923 if (newState !== VideoState.PUBLISHED) return
924
925 const videoState = this.video.state.id
926 if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return
927
928 console.log('Loading video after live update.')
929
930 const videoUUID = this.video.uuid
931
932 // Reset to refetch the video
933 this.video = undefined
934 this.loadVideo(videoUUID)
935 }
936
937 private handleLiveViewsChange (newViews: number) {
938 if (!this.video) {
939 console.error('Cannot update video live views because video is no defined.')
940 return
941 }
942
e43b5a3f
C
943 console.log('Updating live views.')
944
a800dbf3
C
945 this.video.views = newViews
946 }
947
941c5eac
C
948 private initHotkeys () {
949 this.hotkeys = [
941c5eac 950 // These hotkeys are managed by the player
66357162
C
951 new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`),
952 new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`),
953 new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`),
941c5eac 954
66357162 955 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 956
66357162
C
957 new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`),
958 new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`),
941c5eac 959
66357162
C
960 new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`),
961 new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`),
941c5eac 962
66357162
C
963 new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`),
964 new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`),
941c5eac 965
66357162 966 new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`)
941c5eac 967 ]
3d216ea0
C
968
969 if (this.isUserLoggedIn()) {
970 this.hotkeys = this.hotkeys.concat([
971 new Hotkey('shift+l', () => {
972 this.setLike()
973 return false
66357162 974 }, undefined, $localize`Like the video`),
3d216ea0
C
975
976 new Hotkey('shift+d', () => {
977 this.setDislike()
978 return false
66357162 979 }, undefined, $localize`Dislike the video`),
3d216ea0
C
980
981 new Hotkey('shift+s', () => {
982 this.subscribeButton.subscribed ? this.subscribeButton.unsubscribe() : this.subscribeButton.subscribe()
983 return false
66357162 984 }, undefined, $localize`Subscribe to the account`)
3d216ea0
C
985 ])
986 }
987
988 this.hotkeysService.add(this.hotkeys)
941c5eac 989 }
dc8bc31b 990}