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