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