feat: swap core and _core

This commit is contained in:
TrèsAbhi committed 2023-10-14 11:06:03 -05:00
1 parent 07e3660388
commit b827f7f730
113 files changed
+254 -247

No files matched your search

@@ -1,18 +0,0 @@
import { getAccountInfo } from '../../_core/blitz/getAccountInfo';
import { Region } from '../../constants/regions';
import linkButton from '../discord/linkButton';
export async function getBlitzStarsLinkButton(
region: Region,
id: number,
tankId?: number,
) {
const { nickname } = await getAccountInfo(region, id);
return linkButton(
`https://www.blitzstars.com/player/${region}/${nickname}${
tankId ? `/tank/${tankId!}` : ''
}`,
'BlitzStars',
);
}
-125
View File
@@ -1,125 +0,0 @@
import { AllStats } from '../../_core/blitz/getAccountInfo';
import { Region } from '../../constants/regions';
import getTankHistories, {
TankHistories,
TankHistoryRaw,
} from './getTankHistories';
export const emptyAllStats: AllStats = {
battles: 0,
capture_points: 0,
damage_dealt: 0,
damage_received: 0,
dropped_capture_points: 0,
frags: 0,
frags8p: 0,
hits: 0,
losses: 0,
max_frags: 0,
max_xp: 0,
shots: 0,
spotted: 0,
survived_battles: 0,
xp: 0,
win_and_survived: 0,
wins: 0,
};
export const emptyTankHistoryNode: TankHistoryRaw = {
account_id: 0,
battle_life_time: 0,
last_battle_time: 0,
mark_of_mastery: 0,
tank_id: 0,
all: emptyAllStats,
};
export interface DiffedTankStats {
diff: Record<number, AllStats>;
order: number[];
}
// BIG TODO: merge this neatly with diffNormalizedTankStats
export default async function getDiffedTankStats(
server: Region,
id: number,
start: number,
end: number,
) {
const history = await getTankHistories(server, id, {
includeLatestHistories: true,
});
// sort them even though most won't be used
const tankSortedHistory: Record<number, TankHistories> = {};
const tanks: number[] = [];
history.forEach((node) => {
if (!tankSortedHistory[node.tank_id]) {
tankSortedHistory[node.tank_id] = [node];
tanks.push(node.tank_id);
} else {
tankSortedHistory[node.tank_id].push(node);
}
});
// find the ones played within the range
const inRangeTanks = tanks.filter((tankId) =>
tankSortedHistory[tankId].some(
(node) => node.last_battle_time > start && node.last_battle_time < end,
),
);
const playedTanks: number[] = [];
// fetch history node right before "start" and right before "end"
const diff: Record<number, AllStats> = {};
inRangeTanks.forEach((tankId) => {
const sortedHistory = tankSortedHistory[tankId];
const previousIndex =
sortedHistory.findIndex((node) => node.last_battle_time > start) - 1;
const latestIndex =
sortedHistory.findIndex((node) => node.last_battle_time > end) - 1;
const previous = sortedHistory[previousIndex] ?? emptyTankHistoryNode;
const latest =
sortedHistory[latestIndex] ?? sortedHistory[sortedHistory.length - 1];
function d(get: (allStats: AllStats) => number) {
return get(latest.all) - get(previous.all);
}
// check if there was a change in battles as games in ratings do update last_battle_time
if (d((a) => a.battles) > 0) {
diff[tankId] = {
battles: d((a) => a.battles),
capture_points: d((a) => a.capture_points),
damage_dealt: d((a) => a.damage_dealt),
damage_received: d((a) => a.damage_received),
dropped_capture_points: d((a) => a.dropped_capture_points),
frags: d((a) => a.frags),
frags8p: d((a) => a.frags8p),
hits: d((a) => a.hits),
losses: d((a) => a.losses),
max_frags: latest.all.max_frags,
max_xp: latest.all.max_xp,
shots: d((a) => a.shots),
spotted: d((a) => a.spotted),
survived_battles: d((a) => a.survived_battles),
win_and_survived: d((a) => a.win_and_survived),
wins: d((a) => a.wins),
xp: d((a) => a.xp),
};
playedTanks.push(tankId);
}
});
const order = playedTanks.sort((a, b) => {
const aHistories = tankSortedHistory[a];
const bHistories = tankSortedHistory[b];
const aLatest = aHistories[aHistories.length - 1];
const bLatest = bHistories[bHistories.length - 1];
return bLatest.last_battle_time - aLatest.last_battle_time;
});
return { diff, order } satisfies DiffedTankStats;
}
-3
View File
@@ -1,3 +0,0 @@
export default function getPeriodNow() {
return Date.now() / 1000;
}
-9
View File
@@ -1,9 +0,0 @@
import { Region } from '../../constants/regions';
import { PeriodSize } from '../discord/addPeriodSubCommands';
import getTimeDaysAgo from './getTimeDaysAgo';
export default function getPeriodStart(region: Region, period: PeriodSize) {
if (period === 'career') return 0;
if (period === 'today') return getTimeDaysAgo(region, 1);
return getTimeDaysAgo(region, parseInt(period));
}
-64
View File
@@ -1,64 +0,0 @@
import { getAccountInfo } from '../../_core/blitz/getAccountInfo';
import { PlayerStats } from '../../_core/blitzstars/getPlayerStats';
import { Region } from '../../constants/regions';
import {
GetHistoriesOptions,
Histories,
History,
getHistoriesDefaultOptions,
} from '../../types/histories';
import { emptyAllStats } from './getDiffedTankStats';
export default async function getPlayerHistories(
server: Region,
id: number,
options?: Partial<GetHistoriesOptions>,
) {
const mergedOptions = { ...getHistoriesDefaultOptions, ...options };
const response = await fetch(
`https://www.blitzstars.com/api/playerstats/${id}`,
);
const playerHistories = ((await response.json()) as PlayerStats).map(
(history) =>
({
all: history.statistics.all,
last_battle_time: history.last_battle_time,
}) satisfies History,
);
let lastNonCompliantIndex = -1;
let hasCompliedOnce = false;
const filtered = playerHistories.filter(({ last_battle_time }, index) => {
const complies =
last_battle_time >= mergedOptions.start &&
last_battle_time <= mergedOptions.end;
if (complies && !hasCompliedOnce) hasCompliedOnce = true;
if (!hasCompliedOnce) lastNonCompliantIndex = index;
return complies;
});
const latestNodes: Histories = [];
if (mergedOptions.includeLatestHistories) {
const { last_battle_time, statistics } = await getAccountInfo(server, id);
latestNodes.push({ all: statistics.all, last_battle_time });
}
const previousNodes: Histories = [];
if (mergedOptions.includePreviousHistories) {
if (lastNonCompliantIndex !== -1) {
previousNodes.push(
playerHistories[lastNonCompliantIndex] ??
({
all: emptyAllStats,
last_battle_time: -Infinity,
} satisfies History),
);
}
}
return [...latestNodes, ...filtered, ...previousNodes] satisfies Histories;
}
+38
View File
@@ -0,0 +1,38 @@
import { Region } from '../../constants/regions';
import { AllStats } from '../blitz/getAccountInfo';
export interface IndividualPlayerStats {
clan: { clan_id: number; name: string; tag: string };
statistics: {
all: AllStats;
wn8: number;
wn7: number;
average_tier: number;
};
last_battle_time: number;
nickname: string;
account_id: number;
achievements: {
account_id: number;
[key: string]: number;
};
region: Region;
}
export type PlayerStats = IndividualPlayerStats[];
export async function getPlayerStats<
Ids extends number | number[],
ReturnType = Ids extends number ? PlayerStats : PlayerStats[],
>(region: Region, ids: Ids) {
const stats = await Promise.all(
((typeof ids === 'number' ? [ids] : ids) as number[]).map((id) =>
fetch(`https://www.blitzstars.com/api/playerstats/${id}`).then(
(response) => response.json() as Promise<PlayerStats>,
),
),
);
if (typeof ids === 'number') return stats[0] as ReturnType;
return stats as ReturnType;
}
-113
View File
@@ -1,113 +0,0 @@
import getTankStats from '../../_core/blitz/getTankStats';
import { Region } from '../../constants/regions';
import {
GetHistoriesOptions,
Histories,
History,
getHistoriesDefaultOptions,
} from '../../types/histories';
import { emptyAllStats } from './getDiffedTankStats';
export interface TankHistory extends History {
tank_id: number;
}
export type TankHistories = TankHistory[];
export interface TankHistoryRaw extends TankHistory {
mark_of_mastery: number;
battle_life_time: number;
account_id: number;
}
export type TankHistoriesRaw = TankHistoryRaw[];
export interface GetTankHistoriesOptions extends GetHistoriesOptions {
tankId?: number;
}
export const getTankHistoriesDefaultOptions: GetTankHistoriesOptions = {
...getHistoriesDefaultOptions,
tankId: undefined,
};
export default async function getTankHistories(
server: Region,
id: number,
options?: Partial<GetTankHistoriesOptions>,
) {
const mergedOptions = { ...getTankHistoriesDefaultOptions, ...options };
const tankHistoriesResponse = await fetch(
`https://www.blitzstars.com/api/tankhistories/for/${id}/`,
);
const tankHistories = (
(await tankHistoriesResponse.json()) as TankHistoriesRaw
).map(
(history) =>
({
all: history.all,
last_battle_time: history.last_battle_time,
tank_id: history.tank_id,
}) satisfies TankHistory,
);
const compliantTanks: number[] = [];
const lastBattles: Record<number, number> = {};
const lastNonCompliantIndex: Record<number, number> = {};
const hasCompliedOnce: Record<number, boolean> = {};
const filtered = tankHistories.filter(
({ last_battle_time, tank_id, all: { battles } }, index) => {
const complies =
last_battle_time >= mergedOptions.start &&
last_battle_time <= mergedOptions.end &&
(mergedOptions.tankId === undefined ||
tank_id === mergedOptions.tankId);
if (complies && !hasCompliedOnce[tank_id]) {
hasCompliedOnce[tank_id] = true;
compliantTanks.push(tank_id);
}
if (!hasCompliedOnce[tank_id]) lastNonCompliantIndex[tank_id] = index;
lastBattles[tank_id] = battles;
return complies;
},
);
const latestNodes: TankHistories = [];
if (mergedOptions.includeLatestHistories) {
(await getTankStats(server, id)).forEach((tankHistory) => {
if (
tankHistory.all.battles > (lastBattles[tankHistory.tank_id] ?? 0) &&
(mergedOptions.tankId === undefined ||
tankHistory.tank_id === mergedOptions.tankId)
) {
if (!hasCompliedOnce[tankHistory.tank_id]) {
// was played today for the first time... I think???
hasCompliedOnce[tankHistory.tank_id] = true;
compliantTanks.push(tankHistory.tank_id);
}
latestNodes.push(tankHistory);
}
});
}
const previousNodes: TankHistories = [];
if (mergedOptions.includePreviousHistories) {
compliantTanks.forEach((tankId) => {
if (tankId in lastNonCompliantIndex) {
previousNodes.push(
tankHistories[lastNonCompliantIndex[tankId]] ??
({
all: emptyAllStats,
last_battle_time: -Infinity,
tank_id: tankId,
} satisfies TankHistory),
);
}
});
}
return [...previousNodes, ...filtered, ...latestNodes] satisfies Histories;
}
-20
View File
@@ -1,20 +0,0 @@
import { Region } from '../../constants/regions';
export const TIME_ZONE_MAPPINGS: Record<Region, number> = {
com: -5, // Central North American Time
eu: +1, // Central European Time
asia: +7, // Central Asia Standard Time
};
export default function getTimeDaysAgo(region: Region, daysAgo: number) {
const now = new Date();
if (daysAgo === 0) now.getTime() / 1000;
const time = new Date();
time.setUTCHours(-TIME_ZONE_MAPPINGS[region], 0, 0, 0);
if (time > now) time.setUTCDate(time.getUTCDate() - 1);
time.setUTCDate(time.getUTCDate() - daysAgo + 1);
return time.getTime() / 1000;
}
-106
View File
@@ -1,106 +0,0 @@
import { AllStats } from '../../_core/blitz/getAccountInfo';
import { context } from '../blitzkrieg/context';
export interface SpecialStats {
winrate: number;
damageRatio: number;
kdr: number;
damagePerBattle: number;
killsPerBattle: number;
hitsPerBattle: number;
spotsPerBattle: number;
wpm: number;
dpm: number;
kpm: number;
hitRate: number;
survivalRate: number;
}
export type Percentiles = [
number,
number,
number,
number,
number,
number,
number,
number,
number,
];
export interface SpecialPercentiles {
winRate: Percentiles;
damageRatio: Percentiles;
kdr: Percentiles;
damagePerBattle: Percentiles;
killsPerBattle: Percentiles;
hitsPerBattle: Percentiles;
spotsPerBattle: Percentiles;
wpm: Percentiles;
dpm: Percentiles;
kpm: Percentiles;
hitRate: Percentiles;
survivalRate: Percentiles;
}
export interface MeanSd {
winrateMean: number;
winrateSd: number;
hitRateMean: number;
hitRateSd: number;
survivalRateMean: number;
survivalRateSd: number;
damageRatioMean: number;
damageRatioSd: number;
kdrMean: number;
kdrSd: number;
dpbMean: number;
dpbSd: number;
kpbMean: number;
kpbSd: number;
hpbMean: number;
hpbSd: number;
spbMean: number;
spbSd: number;
}
export interface IndividualTankAverage {
_id: number;
battle_life_time: number;
total_battle_life_time: number;
number_of_players: number;
tank_id: number;
all: AllStats;
special: SpecialStats;
percentiles: SpecialPercentiles;
percentiles_player_count: number;
meanSd: MeanSd;
shotEff: number;
last_update: number;
}
export type TankAverages = Record<number, IndividualTankAverage>;
console.log('Caching tank averages...');
export const tankAverages = fetch(
context === 'bot'
? 'https://www.blitzstars.com/api/tankaverages.json'
: '/api/tank-averages',
)
.then((response) => response.json())
.then((json) => {
if (context === 'bot') {
const partialTankAverages: TankAverages = {};
(json as IndividualTankAverage[]).forEach((individualTankAverage) => {
partialTankAverages[individualTankAverage.tank_id] =
individualTankAverage;
});
console.log('Tank averages cached');
return partialTankAverages;
} else {
return json as TankAverages;
}
});