-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatus-parser.ts
109 lines (96 loc) · 3.64 KB
/
status-parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/**
* External dependencies
*/
import cheerio from "cheerio";
import request from "request-promise";
import httpErrors from "http-errors";
/**
* Internal dependencies
*/
import { log, isLocalhost } from "./utils";
export interface StatusData {
id?: string;
user_id?: string;
problem?: {
num?: string;
name?: string;
};
result?: string;
timestamp?: number;
}
const PROCESSING_STATE = ["기다리는 중", "재채점을 기다리는 중", "채점 준비 중", "채점 중"];
const getGroupURL = (groupCode: number) => `https://www.acmicpc.net/status?group_id=${groupCode}`;
export class StatusParser {
private token: string;
constructor(token: string) {
this.token = token;
}
parse(groupCode: number) {
return new Promise<StatusData[]>((resolve, reject) => {
request(getGroupURL(groupCode), {
headers: { cookie: `OnlineJudge=${this.token}` },
}).then((response) => {
const $ = cheerio.load(response);
// check session is valid
if ($(".page-header").length === 0 || $(".loginbar .username").length === 0) {
reject(httpErrors(401, "Invalid token"));
return;
}
const result: StatusData[] = [];
$("#status-table > tbody > tr").each((idx, row) => {
const data: StatusData = {};
$("td", row).each((idx, col) => {
switch (idx) {
case 0:
data.id = $(col).text();
break;
case 1:
data.user_id = $(col).text();
break;
case 2:
data.problem = {
num: $("a", col).text(),
name: $("a", col).attr("title") || "",
};
break;
case 3:
data.result = $(".result-text > span", col).text();
if (!data.result) {
data.result = $(".result-text > a > span", col).text();
}
break;
case 8:
data.timestamp = $(col).children().data("timestamp") * 1000;
break;
}
});
if (this.validate(data)) {
reject(httpErrors(500, "Status data validation failed"));
return;
}
result.push(data);
});
if (isLocalhost()) {
log.verbose("parse result:", JSON.stringify(result, null, 2));
}
if (this.hasProcessing(result)) {
reject(httpErrors(403, "Processing submit exists. Try next time."));
return;
}
resolve(result);
}).catch((err) => reject(err));
});
}
validate(data: Object) {
return !Object.values(data).some((val) => {
// log.verbose("val: ", val, !!val);
if (typeof val == "object") {
return this.validate(val);
}
return !val;
});
}
hasProcessing(data: StatusData[]) {
return data.some((row) => PROCESSING_STATE.includes(row.result));
}
}