codeforces-plus
Version:
A Typescript library to simplify Codeforces API
254 lines (241 loc) • 13.9 kB
JavaScript
;
var crypto = require('node:crypto');
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
var baseUrl = "https://codeforces.com/api";
var fetchCodeforcesData = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
var params, apiKey, apiSecret, time, rand, sortedParams, apiSig, hashedApiSig, queryUrl, statusResponse, data, error_1;
var creds = _b.creds, method = _b.method, props = _b.props;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
params = __assign({}, props);
if (params.asManager && creds) {
apiKey = creds.apiKey, apiSecret = creds.apiSecret;
time = Math.floor(Date.now() / 1000);
rand = Math.random().toString().substring(2, 8);
params.time = time;
params.apiKey = apiKey;
sortedParams = Object.keys(params).sort().map(function (key) { return "".concat(key, "=").concat(params[key]); }).join('&');
apiSig = "".concat(rand, "/").concat(method, "?").concat(sortedParams, "#").concat(apiSecret);
hashedApiSig = crypto.createHash('sha512').update(apiSig).digest('hex');
params.apiSig = rand + hashedApiSig;
}
queryUrl = "".concat(baseUrl, "/").concat(method, "?").concat(new URLSearchParams(params).toString());
_c.label = 1;
case 1:
_c.trys.push([1, 4, , 5]);
return [4, fetch(queryUrl)];
case 2:
statusResponse = _c.sent();
return [4, statusResponse.json()];
case 3:
data = _c.sent();
return [2, __assign(__assign({}, data), { queryUrl: queryUrl })];
case 4:
error_1 = _c.sent();
console.log(error_1);
return [2, { error: "Error fetching data from Codeforces", queryUrl: queryUrl, status: "FAILED" }];
case 5: return [2];
}
});
}); };
var makeLeaderboard = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
var restProps, allContestsSubmissions, data, list, problemIndexes, problemLinks, zeros, totalAccepts, totalTries, sortedList;
var _c;
var creds = _b.creds, contestIds = _b.contestIds, asManager = _b.asManager, count = _b.count, from = _b.from, participantTypes = _b.participantTypes;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
restProps = {};
if (asManager !== undefined)
restProps.asManager = asManager;
if (count !== undefined)
restProps.count = count;
if (from !== undefined)
restProps.from = from;
return [4, Promise.all(contestIds.map(function (contestId) { return __awaiter(void 0, void 0, void 0, function () {
var res, submissions;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4, fetchCodeforcesData({
creds: creds !== null && creds !== void 0 ? creds : undefined,
method: "contest.status",
props: __assign({ contestId: contestId }, restProps),
})];
case 1:
res = _a.sent();
submissions = res === null || res === void 0 ? void 0 : res.result;
return [2, submissions];
}
});
}); }))];
case 1:
allContestsSubmissions = _d.sent();
data = [];
allContestsSubmissions.forEach(function (contestSubmissions) {
contestSubmissions === null || contestSubmissions === void 0 ? void 0 : contestSubmissions.forEach(function (submimission) { return data.push(submimission); });
});
list = {};
problemIndexes = contestIds.map(function (contestId, idx) { return (String.fromCharCode("A".charCodeAt(0) + idx)); });
problemLinks = contestIds.map(function (contest) { return "https://codeforces.com/gym/" + contest.toString() + "/problem/A"; });
zeros = contestIds.map(function (contest) { return 0; });
totalAccepts = zeros;
totalTries = zeros;
data === null || data === void 0 ? void 0 : data.forEach(function (submission) {
var _a, _b;
if (participantTypes.includes((_a = submission === null || submission === void 0 ? void 0 : submission.author) === null || _a === void 0 ? void 0 : _a.participantType)) {
var handle = submission.author.members[0].handle;
var problemIndex = submission.problem.index;
var time = submission.relativeTimeSeconds;
var verdict = submission.verdict;
var passedTestCount = submission.passedTestCount;
var ind = problemIndex.charCodeAt(0) - 'A'.charCodeAt(0);
if ((!list[handle])) {
list[handle] = {
acceptedCount: 0,
totalWrongs: 0,
totalSubmissionTime: 0,
totalPenality: 0,
submissions: {},
profileLink: "https://codeforces.com/profile/" + handle
};
}
if (!list[handle].submissions[problemIndex]) {
list[handle].submissions[problemIndex] = {
contestId: (_b = submission.contestId) !== null && _b !== void 0 ? _b : -1,
accepted: false,
wrongs: 0,
time: 0
};
totalTries[ind]++;
}
var userProblem = list[handle].submissions[problemIndex];
if (!userProblem.accepted) {
if (verdict === "OK") {
list[handle].totalWrongs -= userProblem.wrongs;
userProblem.wrongs = 0;
list[handle].acceptedCount++;
userProblem.accepted = true;
userProblem.time = time;
}
else {
if (passedTestCount > 0) {
userProblem.wrongs++;
list[handle].totalWrongs++;
}
}
}
else {
if (verdict === "OK") {
list[handle].totalWrongs -= userProblem.wrongs;
userProblem.wrongs = 0;
userProblem.time = time;
}
else {
if (passedTestCount > 0) {
userProblem.wrongs++;
list[handle].totalWrongs++;
}
}
}
}
});
Object.keys(list).forEach(function (key) {
var user = list[key];
Object.keys(user.submissions).forEach(function (ques) {
var ind = ques.charCodeAt(0) - 'A'.charCodeAt(0);
if (user.submissions[ques].accepted) {
totalAccepts[ind]++;
}
});
});
(_c = Object.keys(list)) === null || _c === void 0 ? void 0 : _c.forEach(function (key) {
var user = list[key];
var totalSubmissionTime = 0;
var totalWrongs = 0;
Object.values(user.submissions).forEach(function (submission) {
totalSubmissionTime += (submission.accepted ? Math.floor(submission.time / 60) : 0);
totalWrongs += (submission.accepted ? submission.wrongs : 0);
});
user.totalSubmissionTime = totalSubmissionTime;
user.totalWrongs = totalWrongs;
user.totalPenality = 10 * user.totalWrongs + Math.floor(user.totalSubmissionTime);
});
sortedList = Object.fromEntries(Object.entries(list).sort(function (_a, _b) {
var userA = _a[1];
var userB = _b[1];
if (userB.acceptedCount !== userA.acceptedCount) {
return userB.acceptedCount - userA.acceptedCount;
}
else {
return userA.totalPenality - userB.totalPenality;
}
}));
return [2, { contestants: sortedList, problemIndexes: problemIndexes, problemLinks: problemLinks, totalAccepts: totalAccepts, totalTries: totalTries }];
}
});
}); };
exports.fetchCodeforcesData = fetchCodeforcesData;
exports.makeLeaderboard = makeLeaderboard;