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