368 lines
12 KiB
TypeScript
368 lines
12 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import mongoose from 'mongoose';
|
|
import type {
|
|
MatchDocument,
|
|
MatchGameResultParticipant,
|
|
TeamSide,
|
|
} from '../global/database/schema';
|
|
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
|
|
import type { InternalMatchCardView } from './community-stats.types';
|
|
import type {
|
|
InternalGameDetail,
|
|
InternalRecord,
|
|
MatchStatsFragment,
|
|
} from './match-stats.types';
|
|
|
|
@Injectable()
|
|
export class MatchStatsFragmentBuilder {
|
|
public buildFragment(params: {
|
|
match: MatchDocument;
|
|
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
|
}): MatchStatsFragment {
|
|
const games = [...(params.match.result?.games ?? [])].sort(
|
|
(left, right) => left.gameNumber - right.gameNumber,
|
|
);
|
|
const matchCard = this.toMatchCard(params.match, games);
|
|
const gameDetails = games.map((game) => {
|
|
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
|
return raw
|
|
? this.toGameDetail(params.match, game, raw)
|
|
: this.toFallbackGameDetail(params.match, game);
|
|
});
|
|
const records = gameDetails.flatMap((detail) =>
|
|
detail.teams.flatMap((team) => team.participants),
|
|
);
|
|
const gameCreations = gameDetails.map((detail) => detail.gameCreation);
|
|
|
|
return {
|
|
matchCard,
|
|
records,
|
|
gameDetails,
|
|
userIds: [
|
|
...new Map(
|
|
records
|
|
.filter((record) => mongoose.isValidObjectId(record.userId))
|
|
.map((record) => [
|
|
record.userId,
|
|
new mongoose.Types.ObjectId(record.userId),
|
|
]),
|
|
).values(),
|
|
],
|
|
championIds: [...new Set(records.map((record) => record.championId))],
|
|
gameCreationMin:
|
|
gameCreations.length > 0
|
|
? Math.min(...gameCreations)
|
|
: params.match.scheduledAt.getTime(),
|
|
gameCreationMax:
|
|
gameCreations.length > 0
|
|
? Math.max(...gameCreations)
|
|
: params.match.scheduledAt.getTime(),
|
|
};
|
|
}
|
|
|
|
private toMatchCard(
|
|
match: MatchDocument,
|
|
games: NonNullable<MatchDocument['result']>['games'],
|
|
): InternalMatchCardView {
|
|
const participantById = new Map(
|
|
match.participants.map((participant) => [
|
|
participant.userId.toString(),
|
|
participant,
|
|
]),
|
|
);
|
|
return {
|
|
matchId: match._id.toString(),
|
|
title: match.title,
|
|
scheduledAt: match.scheduledAt.toISOString(),
|
|
status: match.status === 'finished' ? 'finished' : 'in-progress',
|
|
gameCount: match.gameCount,
|
|
winnerTeamIndex: match.result?.winnerTeamIndex,
|
|
seriesResults: match.result?.seriesResults ?? [],
|
|
games: games.map((game) => ({
|
|
gameNumber: game.gameNumber,
|
|
riotMatchId: game.riotMatchId ?? null,
|
|
blueTeamIndex: game.blueTeamIndex,
|
|
redTeamIndex: game.redTeamIndex,
|
|
winnerTeamIndex: game.winnerTeamIndex ?? null,
|
|
winnerSide: game.winnerSide ?? null,
|
|
gameDuration: game.gameDuration,
|
|
})),
|
|
teams: match.teams.map((team) => ({
|
|
teamIndex: team.teamIndex,
|
|
name: team.name,
|
|
members: team.members.map((member) => {
|
|
const participant = participantById.get(member.userId.toString());
|
|
return {
|
|
userId: member.userId.toString(),
|
|
summonerName: participant?.gameName ?? 'Unknown',
|
|
profileIconId: participant?.profileIconId ?? 0,
|
|
};
|
|
}),
|
|
})),
|
|
};
|
|
}
|
|
|
|
private toGameDetail(
|
|
match: MatchDocument,
|
|
game: NonNullable<MatchDocument['result']>['games'][number],
|
|
raw: RiotMatchDto,
|
|
): InternalGameDetail {
|
|
const puuidByUserId = new Map(
|
|
match.participants
|
|
.filter((participant) => participant.puuid)
|
|
.map((participant) => [
|
|
participant.userId.toString(),
|
|
participant.puuid as string,
|
|
]),
|
|
);
|
|
const rawByPuuid = new Map(
|
|
raw.info.participants.map((participant) => [
|
|
participant.puuid,
|
|
participant,
|
|
]),
|
|
);
|
|
const rawTeamIdBySide = new Map<TeamSide, number>();
|
|
for (const participant of game.participants) {
|
|
const puuid = puuidByUserId.get(participant.userId.toString());
|
|
const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined;
|
|
if (rawParticipant) {
|
|
rawTeamIdBySide.set(participant.side, rawParticipant.teamId);
|
|
}
|
|
}
|
|
|
|
return {
|
|
gameNumber: game.gameNumber,
|
|
riotMatchId: game.riotMatchId,
|
|
gameCreation: game.gameCreation,
|
|
gameDuration: game.gameDuration,
|
|
winnerSide: game.winnerSide,
|
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
|
const teamIndex =
|
|
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
|
const rawTeamId = rawTeamIdBySide.get(side);
|
|
const rawTeam = raw.info.teams.find(
|
|
(team) => team.teamId === rawTeamId,
|
|
);
|
|
const teamRawParticipants = raw.info.participants.filter(
|
|
(participant) => participant.teamId === rawTeamId,
|
|
);
|
|
const teamKills = teamRawParticipants.reduce(
|
|
(sum, participant) => sum + participant.kills,
|
|
0,
|
|
);
|
|
const teamDamage = teamRawParticipants.reduce(
|
|
(sum, participant) => sum + participant.totalDamageDealtToChampions,
|
|
0,
|
|
);
|
|
return {
|
|
teamIndex,
|
|
side,
|
|
win: game.winnerSide === side,
|
|
objectives: {
|
|
baron: rawTeam?.objectives?.baron?.kills ?? 0,
|
|
dragon: rawTeam?.objectives?.dragon?.kills ?? 0,
|
|
tower: rawTeam?.objectives?.tower?.kills ?? 0,
|
|
},
|
|
participants: game.participants
|
|
.filter((participant) => participant.side === side)
|
|
.map((participant) =>
|
|
this.toRecord({
|
|
match,
|
|
game,
|
|
participant,
|
|
rawParticipant: rawByPuuid.get(
|
|
puuidByUserId.get(participant.userId.toString()) ?? '',
|
|
),
|
|
teamKills,
|
|
teamDamage,
|
|
}),
|
|
),
|
|
};
|
|
}),
|
|
};
|
|
}
|
|
|
|
private toFallbackGameDetail(
|
|
match: MatchDocument,
|
|
game: NonNullable<MatchDocument['result']>['games'][number],
|
|
): InternalGameDetail {
|
|
return {
|
|
gameNumber: game.gameNumber,
|
|
riotMatchId: game.riotMatchId,
|
|
gameCreation: game.gameCreation,
|
|
gameDuration: game.gameDuration,
|
|
winnerSide: game.winnerSide,
|
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
|
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
|
side,
|
|
win: game.winnerSide === side,
|
|
objectives: { baron: 0, dragon: 0, tower: 0 },
|
|
participants: game.participants
|
|
.filter((participant) => participant.side === side)
|
|
.map((participant) =>
|
|
this.toRecord({
|
|
match,
|
|
game,
|
|
participant,
|
|
teamKills: 0,
|
|
teamDamage: 0,
|
|
}),
|
|
),
|
|
})),
|
|
};
|
|
}
|
|
|
|
private toRecord(params: {
|
|
match: MatchDocument;
|
|
game: NonNullable<MatchDocument['result']>['games'][number];
|
|
participant: MatchGameResultParticipant;
|
|
rawParticipant?: RiotMatchParticipantDto;
|
|
teamKills: number;
|
|
teamDamage: number;
|
|
}): InternalRecord {
|
|
const { match, game, participant, rawParticipant, teamKills, teamDamage } =
|
|
params;
|
|
const snapshot = match.participants.find((item) =>
|
|
item.userId.equals(participant.userId),
|
|
);
|
|
const minutes = Math.max(
|
|
(rawParticipant?.timePlayed ?? game.gameDuration) / 60,
|
|
1,
|
|
);
|
|
const cs = rawParticipant
|
|
? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled
|
|
: 0;
|
|
const damage = rawParticipant?.totalDamageDealtToChampions ?? 0;
|
|
const killParticipation = percent(
|
|
participant.kills + participant.assists,
|
|
teamKills,
|
|
);
|
|
const damageShare = percent(damage, teamDamage);
|
|
const rating = this.resolveRating({
|
|
kills: participant.kills,
|
|
deaths: participant.deaths,
|
|
assists: participant.assists,
|
|
killParticipation,
|
|
csPerMin: average(cs, minutes),
|
|
damageShare,
|
|
visionPerMin: average(rawParticipant?.visionScore ?? 0, minutes),
|
|
});
|
|
|
|
return {
|
|
matchId: match._id.toString(),
|
|
title: match.title,
|
|
scheduledAt: match.scheduledAt,
|
|
gameNumber: game.gameNumber,
|
|
riotMatchId: game.riotMatchId,
|
|
gameCreation: game.gameCreation,
|
|
gameDuration: game.gameDuration,
|
|
userId: participant.userId.toString(),
|
|
summonerName:
|
|
snapshot?.gameName ??
|
|
rawParticipant?.riotIdGameName ??
|
|
rawParticipant?.summonerName ??
|
|
'Unknown',
|
|
profileIconId: snapshot?.profileIconId ?? 0,
|
|
teamIndex: participant.teamIndex,
|
|
side: participant.side,
|
|
championId: participant.championId,
|
|
championLevel: rawParticipant?.champLevel ?? 0,
|
|
teamPosition:
|
|
rawParticipant?.teamPosition ||
|
|
rawParticipant?.individualPosition ||
|
|
'',
|
|
kills: participant.kills,
|
|
deaths: participant.deaths,
|
|
assists: participant.assists,
|
|
win: participant.win,
|
|
cs,
|
|
csPerMin: average(cs, minutes),
|
|
gold: rawParticipant?.goldEarned ?? 0,
|
|
gpm: average(rawParticipant?.goldEarned ?? 0, minutes),
|
|
damageDealtToChampions: damage,
|
|
damageTaken: rawParticipant?.totalDamageTaken ?? 0,
|
|
damageShare,
|
|
killParticipation,
|
|
visionScore: rawParticipant?.visionScore ?? 0,
|
|
controlWardsBought: numberField(
|
|
rawParticipant,
|
|
'visionWardsBoughtInGame',
|
|
),
|
|
wardsPlaced: rawParticipant?.wardsPlaced ?? 0,
|
|
wardsKilled: rawParticipant?.wardsKilled ?? 0,
|
|
items: [
|
|
rawParticipant?.item0 ?? 0,
|
|
rawParticipant?.item1 ?? 0,
|
|
rawParticipant?.item2 ?? 0,
|
|
rawParticipant?.item3 ?? 0,
|
|
rawParticipant?.item4 ?? 0,
|
|
rawParticipant?.item5 ?? 0,
|
|
],
|
|
trinket: rawParticipant?.item6 ?? 0,
|
|
summonerSpells: [
|
|
rawParticipant?.summoner1Id ?? 0,
|
|
rawParticipant?.summoner2Id ?? 0,
|
|
],
|
|
perks: rawParticipant ? this.resolvePerks(rawParticipant) : {},
|
|
rating,
|
|
};
|
|
}
|
|
|
|
private resolvePerks(participant: RiotMatchParticipantDto) {
|
|
const primary = participant.perks.styles.find(
|
|
(style) => style.description === 'primaryStyle',
|
|
);
|
|
const sub = participant.perks.styles.find(
|
|
(style) => style.description === 'subStyle',
|
|
);
|
|
return {
|
|
primaryStyle: primary?.style,
|
|
subStyle: sub?.style,
|
|
keystone: primary?.selections[0]?.perk,
|
|
};
|
|
}
|
|
|
|
private resolveRating(params: {
|
|
kills: number;
|
|
deaths: number;
|
|
assists: number;
|
|
killParticipation: number;
|
|
csPerMin: number;
|
|
damageShare: number;
|
|
visionPerMin: number;
|
|
}): number {
|
|
const kdaScore = kda(params.kills, params.deaths, params.assists);
|
|
const score =
|
|
Math.min(kdaScore / 6, 1) * 4 +
|
|
Math.min(params.killParticipation / 100, 1) * 2 +
|
|
Math.min(params.csPerMin / 9, 1) * 2 +
|
|
Math.min(params.damageShare / 35, 1) +
|
|
Math.min(params.visionPerMin / 2, 1);
|
|
return round(score);
|
|
}
|
|
}
|
|
|
|
function kda(kills: number, deaths: number, assists: number): number {
|
|
return deaths === 0 ? kills + assists : round((kills + assists) / deaths);
|
|
}
|
|
|
|
function percent(value: number, total: number): number {
|
|
return total > 0 ? Math.round((value / total) * 100) : 0;
|
|
}
|
|
|
|
function average(value: number, total: number): number {
|
|
return total > 0 ? round(value / total) : 0;
|
|
}
|
|
|
|
function round(value: number): number {
|
|
return Math.round(value * 10) / 10;
|
|
}
|
|
|
|
function numberField(
|
|
participant: RiotMatchParticipantDto | undefined,
|
|
key: string,
|
|
): number {
|
|
const value = participant?.[key];
|
|
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
}
|