44 lines
1.4 KiB
TypeScript
44 lines
1.4 KiB
TypeScript
import { OnStart, Service } from "@flamework/core";
|
|
import { DataStoreService } from "@rbxts/services";
|
|
import { t } from "@rbxts/t";
|
|
import { ProfileServerEvents } from "server/networking";
|
|
import { OnPlayerJoined, OnPlayerQuit } from "shared/modding/player_events";
|
|
|
|
@Service()
|
|
class StatsService implements OnPlayerJoined, OnStart, OnPlayerQuit {
|
|
firstJoinStoreCache = new Map<number, [number, number]>();
|
|
firstJoinStore!: DataStore;
|
|
|
|
onStart(): void {
|
|
this.firstJoinStore = DataStoreService.GetDataStore("Stats_Players_Played_Time");
|
|
|
|
ProfileServerEvents.getPlayerStartTime.setCallback((_, playerId) => {
|
|
const playedtime = this.getPlayerPlayedTime(playerId);
|
|
return playedtime!;
|
|
});
|
|
}
|
|
|
|
onPlayerJoined(player: Player): void {
|
|
const playerId = tostring(player.UserId);
|
|
const [value] = this.firstJoinStore.GetAsync(playerId);
|
|
|
|
if (!t.optional(t.number)(value)) throw `Bad Data in DataBase for ${player.UserId}`;
|
|
|
|
if (value === undefined) {
|
|
this.firstJoinStore.SetAsync(playerId, 0);
|
|
}
|
|
|
|
this.firstJoinStoreCache.set(player.UserId, [value ?? 0, os.time()]);
|
|
}
|
|
|
|
getPlayerPlayedTime(playerId: number) {
|
|
return this.firstJoinStoreCache.get(playerId);
|
|
}
|
|
|
|
onPlayerQuit(player: Player): void {
|
|
const [value, time] = this.firstJoinStoreCache.get(player.UserId)!;
|
|
const t = value + os.time() - time;
|
|
this.firstJoinStore.SetAsync(tostring(player.UserId), t, [player.UserId]);
|
|
}
|
|
}
|