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