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