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