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