Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Seasons: Fix JSON parsing error for ladder top retrieval #10745

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
42 changes: 37 additions & 5 deletions server/chat-plugins/seasons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,19 @@ export function generateFormatSchedule() {
export async function getLadderTop(format: string) {
try {
const results = await Net(`https://${Config.routes.root}/ladder/?format=${toID(format)}&json`).get();
const reply = JSON.parse(results);
let reply;
try {
reply = JSON.parse(results);
} catch (parseError) {
Monitor.crashlog(parseError, "Invalid JSON response from ladder request");
return null;
}

// Check that toplist is defined and is an array
if (!reply || !Array.isArray(reply.toplist)) {
Monitor.crashlog(new Error(`Invalid toplist format: ${JSON.stringify(reply)}`), "Ladder toplist read error");
return null;
}
return reply.toplist;
} catch (e) {
Monitor.crashlog(e, "A season ladder request");
Expand All @@ -159,22 +171,42 @@ export async function updateBadgeholders() {
if (!data.badgeholders[period]) {
data.badgeholders[period] = {};
}
for (const formatName of data.formatSchedule[findPeriod()]) {

const currentPeriod = findPeriod();
const scheduledFormats = data.formatSchedule[currentPeriod];
if (!scheduledFormats) {
Monitor.crashlog(new Error(`No format schedule found for period ${currentPeriod}`), "Season badge update");
return;
}

for (const formatName of scheduledFormats) {
const formatid = `gen${Dex.gen}${formatName}`;
const response = await getLadderTop(formatid);
if (!response) continue; // ??

// Ensure response is an array
if (!response || !Array.isArray(response)) {
continue;
}
DieterReinert marked this conversation as resolved.
Show resolved Hide resolved

const newHolders: Record<string, string[]> = {};
for (const [i, row] of response.entries()) {
let badgeType = null;
// Ensure row.userid is safe and a string
const userid = Utils.getString(row.userid);
DieterReinert marked this conversation as resolved.
Show resolved Hide resolved
if (!userid) {
DieterReinert marked this conversation as resolved.
Show resolved Hide resolved
continue; // skip if userid isn't readable
}

let badgeType: string | null = null;
for (const type in BADGE_THRESHOLDS) {
if ((i + 1) <= BADGE_THRESHOLDS[type]) {
badgeType = type;
break;
}
}

if (!badgeType) break;
if (!newHolders[badgeType]) newHolders[badgeType] = [];
newHolders[badgeType].push(row.userid);
newHolders[badgeType].push(userid);
}
data.badgeholders[period][formatid] = newHolders;
}
Expand Down
Loading