import { isPlatformBrowser } from '@angular/common'; import { Component, OnInit, Inject, PLATFORM_ID, NgZone, OnDestroy, inject } from '@angular/core'; import { Router, RouterOutlet } from '@angular/router'; import { HermesClientService } from './hermes-client.service'; import { AuthUserGuard } from './shared/auth/auth.user.guard' import { first, Subscription, timeout } from 'rxjs'; import { NavigationComponent } from "./navigation/navigation.component"; import EventService from './shared/services/EventService'; import { ApiAuthenticationService } from './shared/services/api/api-authentication.service'; import { AuthModule } from './auth/auth.module'; import { ApiKeyService } from './shared/services/api/api-key.service'; import ApiKey from './shared/models/api-key'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet, AuthModule, NavigationComponent], providers: [AuthUserGuard], templateUrl: './app.component.html', styleUrl: './app.component.scss' }) export class AppComponent implements OnInit, OnDestroy { private readonly keyService = inject(ApiKeyService); private isBrowser: boolean; private ngZone: NgZone; private subscriptions: Subscription[]; constructor(private auth: ApiAuthenticationService, private client: HermesClientService, private events: EventService, private router: Router, ngZone: NgZone, @Inject(PLATFORM_ID) private platformId: Object) { this.ngZone = ngZone; this.isBrowser = isPlatformBrowser(this.platformId); this.subscriptions = []; this.subscriptions.push(this.events.listen('tts_login_ack', async _ => { await this.router.navigate(['policies']) })); this.subscriptions.push(this.events.listen('tts_logoff', async _ => { await this.router.navigate(['tts-login']) })); } ngOnInit(): void { if (!this.isBrowser) return; this.auth.update(); this.addSubscription(this.events.listen('logoff', async (message) => { localStorage.removeItem('jwt'); if (!document.location.href.includes('/login')) { if (message) await this.router.navigate(['login'], { queryParams: { message: message } }); else await this.router.navigate(['login']); } })); this.addSubscription(this.events.listen('login', () => { this.keyService.fetch(true) .pipe(timeout(3000), first()) .subscribe(async (d: ApiKey[]) => { if (d.length > 0) this.client.login(d[0].id); else if (['/login', '/auth'].some(partial => document.location.href.includes(partial))) await this.router.navigate(['tts-login']); }); })); this.ngZone.runOutsideAngular(() => setInterval(() => this.client.heartbeat(), 15000)); } ngOnDestroy() { for (let s of this.subscriptions) { s.unsubscribe(); } } private addSubscription(s: Subscription) { this.subscriptions.push(s); } }