nise/nise-frontend/src/app/home/home.component.ts

96 lines
2.5 KiB
TypeScript
Raw Normal View History

2024-02-14 16:43:11 +00:00
import {Component, OnDestroy, OnInit} from '@angular/core';
import {Observable, Subscription} from "rxjs";
import {environment} from "../../environments/environment";
import {LocalCacheService} from "../../corelib/service/local-cache.service";
2024-02-14 16:43:11 +00:00
import {RxStompService} from "../../corelib/stomp/stomp.service";
import {Message} from "@stomp/stompjs/esm6";
import {ReplayData} from "../replays";
import {DecimalPipe, NgForOf, NgIf} from "@angular/common";
import {RouterLink} from "@angular/router";
2024-02-14 16:43:11 +00:00
interface Statistics {
total_beatmaps: number;
total_users: number;
total_scores: number;
total_replay_scores: number;
total_replay_similarity: number;
}
@Component({
selector: 'app-home',
standalone: true,
2024-02-14 16:43:11 +00:00
templateUrl: './home.component.html',
imports: [
DecimalPipe,
RouterLink,
NgIf,
NgForOf
],
2024-02-14 16:43:11 +00:00
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit, OnDestroy {
liveScores: ReplayData[] = [];
liveScoresSub: Subscription | undefined;
statistics: Statistics | null = null;
wantsConnection: boolean = true;
constructor(
private localCacheService: LocalCacheService,
private rxStompService: RxStompService,
) { }
ngOnInit(): void {
const storedWantsConnection = localStorage.getItem('wantsConnection');
if (storedWantsConnection !== null) {
this.wantsConnection = JSON.parse(storedWantsConnection);
if (this.wantsConnection) {
this.subscribe();
}
} else {
this.subscribe();
}
this.getStatistics().subscribe((response: Statistics) => {
this.statistics = response;
});
}
private subscribe() {
this.liveScoresSub = this.rxStompService
.watch("/topic/live-scores/")
.subscribe((message: Message) => {
const data: ReplayData = JSON.parse(message.body);
this.liveScores.unshift(data);
if (this.liveScores.length > 50) {
this.liveScores = this.liveScores.slice(0, 50);
}
});
}
ngOnDestroy(): void {
this.liveScoresSub?.unsubscribe();
}
toggleConnection(): void {
this.wantsConnection = !this.wantsConnection;
localStorage.setItem('wantsConnection', JSON.stringify(this.wantsConnection));
if(!this.wantsConnection) {
this.liveScoresSub?.unsubscribe()
} else {
this.subscribe();
}
}
getStatistics(): Observable<Statistics> {
return this.localCacheService.fetchData<Statistics>(
'statistics',
`${environment.apiUrl}/stats`,
60
);
}
}