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