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