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