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