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