]>
Commit | Line | Data |
---|---|---|
1 | import { Hotkey, HotkeysService } from 'angular2-hotkeys' | |
2 | import { forkJoin, Subscription } from 'rxjs' | |
3 | import { PlatformLocation } from '@angular/common' | |
4 | import { Component, ElementRef, Inject, LOCALE_ID, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core' | |
5 | import { ActivatedRoute, Router } from '@angular/router' | |
6 | import { | |
7 | AuthService, | |
8 | AuthUser, | |
9 | ConfirmService, | |
10 | MetaService, | |
11 | Notifier, | |
12 | PeerTubeSocket, | |
13 | PluginService, | |
14 | RestExtractor, | |
15 | ScreenService, | |
16 | ServerService, | |
17 | UserService | |
18 | } from '@app/core' | |
19 | import { HooksService } from '@app/core/plugins/hooks.service' | |
20 | import { isXPercentInViewport, scrollToTop } from '@app/helpers' | |
21 | import { Video, VideoCaptionService, VideoDetails, VideoService } from '@app/shared/shared-main' | |
22 | import { SubscribeButtonComponent } from '@app/shared/shared-user-subscription' | |
23 | import { VideoPlaylist, VideoPlaylistService } from '@app/shared/shared-video-playlist' | |
24 | import { timeToInt } from '@shared/core-utils' | |
25 | import { | |
26 | HTMLServerConfig, | |
27 | HttpStatusCode, | |
28 | PeerTubeProblemDocument, | |
29 | ServerErrorCode, | |
30 | VideoCaption, | |
31 | VideoPrivacy, | |
32 | VideoState | |
33 | } from '@shared/models' | |
34 | import { cleanupVideoWatch, getStoredTheater, getStoredVideoWatchHistory } from '../../../assets/player/peertube-player-local-storage' | |
35 | import { | |
36 | CustomizationOptions, | |
37 | P2PMediaLoaderOptions, | |
38 | PeertubePlayerManager, | |
39 | PeertubePlayerManagerOptions, | |
40 | PlayerMode, | |
41 | videojs | |
42 | } from '../../../assets/player/peertube-player-manager' | |
43 | import { environment } from '../../../environments/environment' | |
44 | import { VideoWatchPlaylistComponent } from './shared' | |
45 | ||
46 | type URLOptions = CustomizationOptions & { playerMode: PlayerMode } | |
47 | ||
48 | @Component({ | |
49 | selector: 'my-video-watch', | |
50 | templateUrl: './video-watch.component.html', | |
51 | styleUrls: [ './video-watch.component.scss' ] | |
52 | }) | |
53 | export class VideoWatchComponent implements OnInit, OnDestroy { | |
54 | @ViewChild('videoWatchPlaylist', { static: true }) videoWatchPlaylist: VideoWatchPlaylistComponent | |
55 | @ViewChild('subscribeButton') subscribeButton: SubscribeButtonComponent | |
56 | ||
57 | player: any | |
58 | playerElement: HTMLVideoElement | |
59 | playerPlaceholderImgSrc: string | |
60 | theaterEnabled = false | |
61 | ||
62 | video: VideoDetails = null | |
63 | videoCaptions: VideoCaption[] = [] | |
64 | ||
65 | playlistPosition: number | |
66 | playlist: VideoPlaylist = null | |
67 | ||
68 | remoteServerDown = false | |
69 | ||
70 | private nextVideoUUID = '' | |
71 | private nextVideoTitle = '' | |
72 | ||
73 | private currentTime: number | |
74 | ||
75 | private paramsSub: Subscription | |
76 | private queryParamsSub: Subscription | |
77 | private configSub: Subscription | |
78 | private liveVideosSub: Subscription | |
79 | ||
80 | private serverConfig: HTMLServerConfig | |
81 | ||
82 | private hotkeys: Hotkey[] = [] | |
83 | ||
84 | constructor ( | |
85 | private elementRef: ElementRef, | |
86 | private route: ActivatedRoute, | |
87 | private router: Router, | |
88 | private videoService: VideoService, | |
89 | private playlistService: VideoPlaylistService, | |
90 | private confirmService: ConfirmService, | |
91 | private metaService: MetaService, | |
92 | private authService: AuthService, | |
93 | private userService: UserService, | |
94 | private serverService: ServerService, | |
95 | private restExtractor: RestExtractor, | |
96 | private notifier: Notifier, | |
97 | private zone: NgZone, | |
98 | private videoCaptionService: VideoCaptionService, | |
99 | private hotkeysService: HotkeysService, | |
100 | private hooks: HooksService, | |
101 | private pluginService: PluginService, | |
102 | private peertubeSocket: PeerTubeSocket, | |
103 | private screenService: ScreenService, | |
104 | private location: PlatformLocation, | |
105 | @Inject(LOCALE_ID) private localeId: string | |
106 | ) { } | |
107 | ||
108 | get user () { | |
109 | return this.authService.getUser() | |
110 | } | |
111 | ||
112 | get anonymousUser () { | |
113 | return this.userService.getAnonymousUser() | |
114 | } | |
115 | ||
116 | async ngOnInit () { | |
117 | this.serverConfig = this.serverService.getHTMLConfig() | |
118 | ||
119 | PeertubePlayerManager.initState() | |
120 | ||
121 | this.loadRouteParams() | |
122 | this.loadRouteQuery() | |
123 | ||
124 | this.initHotkeys() | |
125 | ||
126 | this.theaterEnabled = getStoredTheater() | |
127 | ||
128 | this.hooks.runAction('action:video-watch.init', 'video-watch') | |
129 | ||
130 | setTimeout(cleanupVideoWatch, 1500) // Run in timeout to ensure we're not blocking the UI | |
131 | } | |
132 | ||
133 | ngOnDestroy () { | |
134 | this.flushPlayer() | |
135 | ||
136 | // Unsubscribe subscriptions | |
137 | if (this.paramsSub) this.paramsSub.unsubscribe() | |
138 | if (this.queryParamsSub) this.queryParamsSub.unsubscribe() | |
139 | if (this.configSub) this.configSub.unsubscribe() | |
140 | if (this.liveVideosSub) this.liveVideosSub.unsubscribe() | |
141 | ||
142 | // Unbind hotkeys | |
143 | this.hotkeysService.remove(this.hotkeys) | |
144 | } | |
145 | ||
146 | getCurrentTime () { | |
147 | return this.currentTime | |
148 | } | |
149 | ||
150 | getCurrentPlaylistPosition () { | |
151 | return this.videoWatchPlaylist.currentPlaylistPosition | |
152 | } | |
153 | ||
154 | onRecommendations (videos: Video[]) { | |
155 | if (videos.length === 0) return | |
156 | ||
157 | // The recommended videos's first element should be the next video | |
158 | const video = videos[0] | |
159 | this.nextVideoUUID = video.uuid | |
160 | this.nextVideoTitle = video.name | |
161 | } | |
162 | ||
163 | handleTimestampClicked (timestamp: number) { | |
164 | if (!this.player || this.video.isLive) return | |
165 | ||
166 | this.player.currentTime(timestamp) | |
167 | scrollToTop() | |
168 | } | |
169 | ||
170 | onPlaylistVideoFound (videoId: string) { | |
171 | this.loadVideo(videoId) | |
172 | } | |
173 | ||
174 | isUserLoggedIn () { | |
175 | return this.authService.isLoggedIn() | |
176 | } | |
177 | ||
178 | isVideoBlur (video: Video) { | |
179 | return video.isVideoNSFWForUser(this.user, this.serverConfig) | |
180 | } | |
181 | ||
182 | isChannelDisplayNameGeneric () { | |
183 | const genericChannelDisplayName = [ | |
184 | `Main ${this.video.channel.ownerAccount.name} channel`, | |
185 | `Default ${this.video.channel.ownerAccount.name} channel` | |
186 | ] | |
187 | ||
188 | return genericChannelDisplayName.includes(this.video.channel.displayName) | |
189 | } | |
190 | ||
191 | displayOtherVideosAsRow () { | |
192 | // Use the same value as in the SASS file | |
193 | return this.screenService.getWindowInnerWidth() <= 1100 | |
194 | } | |
195 | ||
196 | private loadRouteParams () { | |
197 | this.paramsSub = this.route.params.subscribe(routeParams => { | |
198 | const videoId = routeParams['videoId'] | |
199 | if (videoId) return this.loadVideo(videoId) | |
200 | ||
201 | const playlistId = routeParams['playlistId'] | |
202 | if (playlistId) return this.loadPlaylist(playlistId) | |
203 | }) | |
204 | } | |
205 | ||
206 | private loadRouteQuery () { | |
207 | this.queryParamsSub = this.route.queryParams.subscribe(queryParams => { | |
208 | // Handle the ?playlistPosition | |
209 | const positionParam = queryParams['playlistPosition'] ?? 1 | |
210 | ||
211 | this.playlistPosition = positionParam === 'last' | |
212 | ? -1 // Handle the "last" index | |
213 | : parseInt(positionParam + '', 10) | |
214 | ||
215 | if (isNaN(this.playlistPosition)) { | |
216 | console.error(`playlistPosition query param '${positionParam}' was parsed as NaN, defaulting to 1.`) | |
217 | this.playlistPosition = 1 | |
218 | } | |
219 | ||
220 | this.videoWatchPlaylist.updatePlaylistIndex(this.playlistPosition) | |
221 | ||
222 | const start = queryParams['start'] | |
223 | if (this.player && start) this.player.currentTime(parseInt(start, 10)) | |
224 | }) | |
225 | } | |
226 | ||
227 | private loadVideo (videoId: string) { | |
228 | if (this.isSameElement(this.video, videoId)) return | |
229 | ||
230 | if (this.player) this.player.pause() | |
231 | ||
232 | const videoObs = this.hooks.wrapObsFun( | |
233 | this.videoService.getVideo.bind(this.videoService), | |
234 | { videoId }, | |
235 | 'video-watch', | |
236 | 'filter:api.video-watch.video.get.params', | |
237 | 'filter:api.video-watch.video.get.result' | |
238 | ) | |
239 | ||
240 | forkJoin([ videoObs, this.videoCaptionService.listCaptions(videoId) ]) | |
241 | .subscribe({ | |
242 | next: ([ video, captionsResult ]) => { | |
243 | const queryParams = this.route.snapshot.queryParams | |
244 | ||
245 | const urlOptions = { | |
246 | resume: queryParams.resume, | |
247 | ||
248 | startTime: queryParams.start, | |
249 | stopTime: queryParams.stop, | |
250 | ||
251 | muted: queryParams.muted, | |
252 | loop: queryParams.loop, | |
253 | subtitle: queryParams.subtitle, | |
254 | ||
255 | playerMode: queryParams.mode, | |
256 | peertubeLink: false | |
257 | } | |
258 | ||
259 | this.onVideoFetched(video, captionsResult.data, urlOptions) | |
260 | .catch(err => this.handleGlobalError(err)) | |
261 | }, | |
262 | ||
263 | error: err => this.handleRequestError(err) | |
264 | }) | |
265 | } | |
266 | ||
267 | private loadPlaylist (playlistId: string) { | |
268 | if (this.isSameElement(this.playlist, playlistId)) return | |
269 | ||
270 | this.playlistService.getVideoPlaylist(playlistId) | |
271 | .subscribe({ | |
272 | next: playlist => { | |
273 | this.playlist = playlist | |
274 | ||
275 | this.videoWatchPlaylist.loadPlaylistElements(playlist, !this.playlistPosition, this.playlistPosition) | |
276 | }, | |
277 | ||
278 | error: err => this.handleRequestError(err) | |
279 | }) | |
280 | } | |
281 | ||
282 | private isSameElement (element: VideoDetails | VideoPlaylist, newId: string) { | |
283 | if (!element) return false | |
284 | ||
285 | return (element.id + '') === newId || element.uuid === newId || element.shortUUID === newId | |
286 | } | |
287 | ||
288 | private async handleRequestError (err: any) { | |
289 | const errorBody = err.body as PeerTubeProblemDocument | |
290 | ||
291 | if (errorBody.code === ServerErrorCode.DOES_NOT_RESPECT_FOLLOW_CONSTRAINTS && errorBody.originUrl) { | |
292 | const originUrl = errorBody.originUrl + (window.location.search ?? '') | |
293 | ||
294 | const res = await this.confirmService.confirm( | |
295 | // eslint-disable-next-line max-len | |
296 | $localize`This video is not available on this instance. Do you want to be redirected on the origin instance: <a href="${originUrl}">${originUrl}</a>?`, | |
297 | $localize`Redirection` | |
298 | ) | |
299 | ||
300 | if (res === true) return window.location.href = originUrl | |
301 | } | |
302 | ||
303 | // If 400, 403 or 404, the video is private or blocked so redirect to 404 | |
304 | return this.restExtractor.redirectTo404IfNotFound(err, 'video', [ | |
305 | HttpStatusCode.BAD_REQUEST_400, | |
306 | HttpStatusCode.FORBIDDEN_403, | |
307 | HttpStatusCode.NOT_FOUND_404 | |
308 | ]) | |
309 | } | |
310 | ||
311 | private handleGlobalError (err: any) { | |
312 | const errorMessage: string = typeof err === 'string' ? err : err.message | |
313 | if (!errorMessage) return | |
314 | ||
315 | // Display a message in the video player instead of a notification | |
316 | if (errorMessage.includes('from xs param')) { | |
317 | this.flushPlayer() | |
318 | this.remoteServerDown = true | |
319 | ||
320 | return | |
321 | } | |
322 | ||
323 | this.notifier.error(errorMessage) | |
324 | } | |
325 | ||
326 | private async onVideoFetched ( | |
327 | video: VideoDetails, | |
328 | videoCaptions: VideoCaption[], | |
329 | urlOptions: URLOptions | |
330 | ) { | |
331 | this.subscribeToLiveEventsIfNeeded(this.video, video) | |
332 | ||
333 | this.video = video | |
334 | this.videoCaptions = videoCaptions | |
335 | ||
336 | // Re init attributes | |
337 | this.playerPlaceholderImgSrc = undefined | |
338 | this.remoteServerDown = false | |
339 | this.currentTime = undefined | |
340 | ||
341 | if (this.isVideoBlur(this.video)) { | |
342 | const res = await this.confirmService.confirm( | |
343 | $localize`This video contains mature or explicit content. Are you sure you want to watch it?`, | |
344 | $localize`Mature or explicit content` | |
345 | ) | |
346 | if (res === false) return this.location.back() | |
347 | } | |
348 | ||
349 | this.buildPlayer(urlOptions) | |
350 | .catch(err => console.error('Cannot build the player', err)) | |
351 | ||
352 | this.setOpenGraphTags() | |
353 | ||
354 | const hookOptions = { | |
355 | videojs, | |
356 | video: this.video, | |
357 | playlist: this.playlist | |
358 | } | |
359 | this.hooks.runAction('action:video-watch.video.loaded', 'video-watch', hookOptions) | |
360 | } | |
361 | ||
362 | private async buildPlayer (urlOptions: URLOptions) { | |
363 | // Flush old player if needed | |
364 | this.flushPlayer() | |
365 | ||
366 | const videoState = this.video.state.id | |
367 | if (videoState === VideoState.LIVE_ENDED || videoState === VideoState.WAITING_FOR_LIVE) { | |
368 | this.playerPlaceholderImgSrc = this.video.previewPath | |
369 | return | |
370 | } | |
371 | ||
372 | // Build video element, because videojs removes it on dispose | |
373 | const playerElementWrapper = this.elementRef.nativeElement.querySelector('#videojs-wrapper') | |
374 | this.playerElement = document.createElement('video') | |
375 | this.playerElement.className = 'video-js vjs-peertube-skin' | |
376 | this.playerElement.setAttribute('playsinline', 'true') | |
377 | playerElementWrapper.appendChild(this.playerElement) | |
378 | ||
379 | const params = { | |
380 | video: this.video, | |
381 | videoCaptions: this.videoCaptions, | |
382 | urlOptions, | |
383 | user: this.user | |
384 | } | |
385 | const { playerMode, playerOptions } = await this.hooks.wrapFun( | |
386 | this.buildPlayerManagerOptions.bind(this), | |
387 | params, | |
388 | 'video-watch', | |
389 | 'filter:internal.video-watch.player.build-options.params', | |
390 | 'filter:internal.video-watch.player.build-options.result' | |
391 | ) | |
392 | ||
393 | this.zone.runOutsideAngular(async () => { | |
394 | this.player = await PeertubePlayerManager.initialize(playerMode, playerOptions, player => this.player = player) | |
395 | ||
396 | this.player.on('customError', ({ err }: { err: any }) => { | |
397 | this.zone.run(() => this.handleGlobalError(err)) | |
398 | }) | |
399 | ||
400 | this.player.on('timeupdate', () => { | |
401 | // Don't need to trigger angular change for this variable, that is sent to children components on click | |
402 | this.currentTime = Math.floor(this.player.currentTime()) | |
403 | }) | |
404 | ||
405 | /** | |
406 | * condition: true to make the upnext functionality trigger, false to disable the upnext functionality | |
407 | * go to the next video in 'condition()' if you don't want of the timer. | |
408 | * next: function triggered at the end of the timer. | |
409 | * suspended: function used at each click of the timer checking if we need to reset progress | |
410 | * and wait until suspended becomes truthy again. | |
411 | */ | |
412 | this.player.upnext({ | |
413 | timeout: 5000, // 5s | |
414 | ||
415 | headText: $localize`Up Next`, | |
416 | cancelText: $localize`Cancel`, | |
417 | suspendedText: $localize`Autoplay is suspended`, | |
418 | ||
419 | getTitle: () => this.nextVideoTitle, | |
420 | ||
421 | next: () => this.zone.run(() => this.playNextVideoInAngularZone()), | |
422 | condition: () => { | |
423 | if (!this.playlist) return this.isAutoPlayNext() | |
424 | ||
425 | // Don't wait timeout to play the next playlist video | |
426 | if (this.isPlaylistAutoPlayNext()) { | |
427 | this.playNextVideoInAngularZone() | |
428 | return undefined | |
429 | } | |
430 | ||
431 | return false | |
432 | }, | |
433 | ||
434 | suspended: () => { | |
435 | return ( | |
436 | !isXPercentInViewport(this.player.el(), 80) || | |
437 | !document.getElementById('content').contains(document.activeElement) | |
438 | ) | |
439 | } | |
440 | }) | |
441 | ||
442 | this.player.one('stopped', () => { | |
443 | if (this.playlist && this.isPlaylistAutoPlayNext()) { | |
444 | this.playNextVideoInAngularZone() | |
445 | } | |
446 | }) | |
447 | ||
448 | this.player.one('ended', () => { | |
449 | if (this.video.isLive) { | |
450 | this.zone.run(() => this.video.state.id = VideoState.LIVE_ENDED) | |
451 | } | |
452 | }) | |
453 | ||
454 | this.player.on('theaterChange', (_: any, enabled: boolean) => { | |
455 | this.zone.run(() => this.theaterEnabled = enabled) | |
456 | }) | |
457 | ||
458 | this.hooks.runAction('action:video-watch.player.loaded', 'video-watch', { player: this.player, videojs, video: this.video }) | |
459 | }) | |
460 | } | |
461 | ||
462 | private playNextVideoInAngularZone () { | |
463 | if (this.playlist) { | |
464 | this.zone.run(() => this.videoWatchPlaylist.navigateToNextPlaylistVideo()) | |
465 | return | |
466 | } | |
467 | ||
468 | if (this.nextVideoUUID) { | |
469 | this.router.navigate([ '/w', this.nextVideoUUID ]) | |
470 | } | |
471 | } | |
472 | ||
473 | private isAutoplay () { | |
474 | // We'll jump to the thread id, so do not play the video | |
475 | if (this.route.snapshot.params['threadId']) return false | |
476 | ||
477 | // Otherwise true by default | |
478 | if (!this.user) return true | |
479 | ||
480 | // Be sure the autoPlay is set to false | |
481 | return this.user.autoPlayVideo !== false | |
482 | } | |
483 | ||
484 | private isAutoPlayNext () { | |
485 | return ( | |
486 | (this.user?.autoPlayNextVideo) || | |
487 | this.anonymousUser.autoPlayNextVideo | |
488 | ) | |
489 | } | |
490 | ||
491 | private isPlaylistAutoPlayNext () { | |
492 | return ( | |
493 | (this.user?.autoPlayNextVideoPlaylist) || | |
494 | this.anonymousUser.autoPlayNextVideoPlaylist | |
495 | ) | |
496 | } | |
497 | ||
498 | private flushPlayer () { | |
499 | // Remove player if it exists | |
500 | if (!this.player) return | |
501 | ||
502 | try { | |
503 | this.player.dispose() | |
504 | this.player = undefined | |
505 | } catch (err) { | |
506 | console.error('Cannot dispose player.', err) | |
507 | } | |
508 | } | |
509 | ||
510 | private buildPlayerManagerOptions (params: { | |
511 | video: VideoDetails | |
512 | videoCaptions: VideoCaption[] | |
513 | urlOptions: CustomizationOptions & { playerMode: PlayerMode } | |
514 | user?: AuthUser | |
515 | }) { | |
516 | const { video, videoCaptions, urlOptions, user } = params | |
517 | ||
518 | const getStartTime = () => { | |
519 | const byUrl = urlOptions.startTime !== undefined | |
520 | const byHistory = video.userHistory && (!this.playlist || urlOptions.resume !== undefined) | |
521 | const byLocalStorage = getStoredVideoWatchHistory(video.uuid) | |
522 | ||
523 | if (byUrl) return timeToInt(urlOptions.startTime) | |
524 | if (byHistory) return video.userHistory.currentTime | |
525 | if (byLocalStorage) return byLocalStorage.duration | |
526 | ||
527 | return 0 | |
528 | } | |
529 | ||
530 | let startTime = getStartTime() | |
531 | ||
532 | // If we are at the end of the video, reset the timer | |
533 | if (video.duration - startTime <= 1) startTime = 0 | |
534 | ||
535 | const playerCaptions = videoCaptions.map(c => ({ | |
536 | label: c.language.label, | |
537 | language: c.language.id, | |
538 | src: environment.apiUrl + c.captionPath | |
539 | })) | |
540 | ||
541 | const options: PeertubePlayerManagerOptions = { | |
542 | common: { | |
543 | autoplay: this.isAutoplay(), | |
544 | nextVideo: () => this.playNextVideoInAngularZone(), | |
545 | ||
546 | playerElement: this.playerElement, | |
547 | onPlayerElementChange: (element: HTMLVideoElement) => this.playerElement = element, | |
548 | ||
549 | videoDuration: video.duration, | |
550 | enableHotkeys: true, | |
551 | inactivityTimeout: 2500, | |
552 | poster: video.previewUrl, | |
553 | ||
554 | startTime, | |
555 | stopTime: urlOptions.stopTime, | |
556 | controls: urlOptions.controls, | |
557 | muted: urlOptions.muted, | |
558 | loop: urlOptions.loop, | |
559 | subtitle: urlOptions.subtitle, | |
560 | ||
561 | peertubeLink: urlOptions.peertubeLink, | |
562 | ||
563 | theaterButton: true, | |
564 | captions: videoCaptions.length !== 0, | |
565 | ||
566 | videoViewUrl: video.privacy.id !== VideoPrivacy.PRIVATE | |
567 | ? this.videoService.getVideoViewUrl(video.uuid) | |
568 | : null, | |
569 | embedUrl: video.embedUrl, | |
570 | embedTitle: video.name, | |
571 | ||
572 | isLive: video.isLive, | |
573 | ||
574 | language: this.localeId, | |
575 | ||
576 | userWatching: user && user.videosHistoryEnabled === true | |
577 | ? { | |
578 | url: this.videoService.getUserWatchingVideoUrl(video.uuid), | |
579 | authorizationHeader: this.authService.getRequestHeaderValue() | |
580 | } | |
581 | : undefined, | |
582 | ||
583 | serverUrl: environment.apiUrl, | |
584 | ||
585 | videoCaptions: playerCaptions, | |
586 | ||
587 | videoShortUUID: video.shortUUID, | |
588 | videoUUID: video.uuid | |
589 | }, | |
590 | ||
591 | webtorrent: { | |
592 | videoFiles: video.files | |
593 | }, | |
594 | ||
595 | pluginsManager: this.pluginService.getPluginsManager() | |
596 | } | |
597 | ||
598 | // Only set this if we're in a playlist | |
599 | if (this.playlist) { | |
600 | options.common.previousVideo = () => { | |
601 | this.zone.run(() => this.videoWatchPlaylist.navigateToPreviousPlaylistVideo()) | |
602 | } | |
603 | } | |
604 | ||
605 | let mode: PlayerMode | |
606 | ||
607 | if (urlOptions.playerMode) { | |
608 | if (urlOptions.playerMode === 'p2p-media-loader') mode = 'p2p-media-loader' | |
609 | else mode = 'webtorrent' | |
610 | } else { | |
611 | if (video.hasHlsPlaylist()) mode = 'p2p-media-loader' | |
612 | else mode = 'webtorrent' | |
613 | } | |
614 | ||
615 | // p2p-media-loader needs TextEncoder, fallback on WebTorrent if not available | |
616 | if (typeof TextEncoder === 'undefined') { | |
617 | mode = 'webtorrent' | |
618 | } | |
619 | ||
620 | if (mode === 'p2p-media-loader') { | |
621 | const hlsPlaylist = video.getHlsPlaylist() | |
622 | ||
623 | const p2pMediaLoader = { | |
624 | playlistUrl: hlsPlaylist.playlistUrl, | |
625 | segmentsSha256Url: hlsPlaylist.segmentsSha256Url, | |
626 | redundancyBaseUrls: hlsPlaylist.redundancies.map(r => r.baseUrl), | |
627 | trackerAnnounce: video.trackerUrls, | |
628 | videoFiles: hlsPlaylist.files | |
629 | } as P2PMediaLoaderOptions | |
630 | ||
631 | Object.assign(options, { p2pMediaLoader }) | |
632 | } | |
633 | ||
634 | return { playerMode: mode, playerOptions: options } | |
635 | } | |
636 | ||
637 | private async subscribeToLiveEventsIfNeeded (oldVideo: VideoDetails, newVideo: VideoDetails) { | |
638 | if (!this.liveVideosSub) { | |
639 | this.liveVideosSub = this.buildLiveEventsSubscription() | |
640 | } | |
641 | ||
642 | if (oldVideo && oldVideo.id !== newVideo.id) { | |
643 | await this.peertubeSocket.unsubscribeLiveVideos(oldVideo.id) | |
644 | } | |
645 | ||
646 | if (!newVideo.isLive) return | |
647 | ||
648 | await this.peertubeSocket.subscribeToLiveVideosSocket(newVideo.id) | |
649 | } | |
650 | ||
651 | private buildLiveEventsSubscription () { | |
652 | return this.peertubeSocket.getLiveVideosObservable() | |
653 | .subscribe(({ type, payload }) => { | |
654 | if (type === 'state-change') return this.handleLiveStateChange(payload.state) | |
655 | if (type === 'views-change') return this.handleLiveViewsChange(payload.views) | |
656 | }) | |
657 | } | |
658 | ||
659 | private handleLiveStateChange (newState: VideoState) { | |
660 | if (newState !== VideoState.PUBLISHED) return | |
661 | ||
662 | const videoState = this.video.state.id | |
663 | if (videoState !== VideoState.WAITING_FOR_LIVE && videoState !== VideoState.LIVE_ENDED) return | |
664 | ||
665 | console.log('Loading video after live update.') | |
666 | ||
667 | const videoUUID = this.video.uuid | |
668 | ||
669 | // Reset to force refresh the video | |
670 | this.video = undefined | |
671 | this.loadVideo(videoUUID) | |
672 | } | |
673 | ||
674 | private handleLiveViewsChange (newViews: number) { | |
675 | if (!this.video) { | |
676 | console.error('Cannot update video live views because video is no defined.') | |
677 | return | |
678 | } | |
679 | ||
680 | console.log('Updating live views.') | |
681 | ||
682 | this.video.views = newViews | |
683 | } | |
684 | ||
685 | private initHotkeys () { | |
686 | this.hotkeys = [ | |
687 | // These hotkeys are managed by the player | |
688 | new Hotkey('f', e => e, undefined, $localize`Enter/exit fullscreen (requires player focus)`), | |
689 | new Hotkey('space', e => e, undefined, $localize`Play/Pause the video (requires player focus)`), | |
690 | new Hotkey('m', e => e, undefined, $localize`Mute/unmute the video (requires player focus)`), | |
691 | ||
692 | 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)`), | |
693 | ||
694 | new Hotkey('up', e => e, undefined, $localize`Increase the volume (requires player focus)`), | |
695 | new Hotkey('down', e => e, undefined, $localize`Decrease the volume (requires player focus)`), | |
696 | ||
697 | new Hotkey('right', e => e, undefined, $localize`Seek the video forward (requires player focus)`), | |
698 | new Hotkey('left', e => e, undefined, $localize`Seek the video backward (requires player focus)`), | |
699 | ||
700 | new Hotkey('>', e => e, undefined, $localize`Increase playback rate (requires player focus)`), | |
701 | new Hotkey('<', e => e, undefined, $localize`Decrease playback rate (requires player focus)`), | |
702 | ||
703 | new Hotkey('.', e => e, undefined, $localize`Navigate in the video frame by frame (requires player focus)`) | |
704 | ] | |
705 | ||
706 | if (this.isUserLoggedIn()) { | |
707 | this.hotkeys = this.hotkeys.concat([ | |
708 | new Hotkey('shift+s', () => { | |
709 | if (this.subscribeButton.isSubscribedToAll()) this.subscribeButton.unsubscribe() | |
710 | else this.subscribeButton.subscribe() | |
711 | ||
712 | return false | |
713 | }, undefined, $localize`Subscribe to the account`) | |
714 | ]) | |
715 | } | |
716 | ||
717 | this.hotkeysService.add(this.hotkeys) | |
718 | } | |
719 | ||
720 | private setOpenGraphTags () { | |
721 | this.metaService.setTitle(this.video.name) | |
722 | ||
723 | this.metaService.setTag('og:type', 'video') | |
724 | ||
725 | this.metaService.setTag('og:title', this.video.name) | |
726 | this.metaService.setTag('name', this.video.name) | |
727 | ||
728 | this.metaService.setTag('og:description', this.video.description) | |
729 | this.metaService.setTag('description', this.video.description) | |
730 | ||
731 | this.metaService.setTag('og:image', this.video.previewPath) | |
732 | ||
733 | this.metaService.setTag('og:duration', this.video.duration.toString()) | |
734 | ||
735 | this.metaService.setTag('og:site_name', 'PeerTube') | |
736 | ||
737 | this.metaService.setTag('og:url', window.location.href) | |
738 | this.metaService.setTag('url', window.location.href) | |
739 | } | |
740 | } |