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