forked from SuprDewd/uva-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adapterUVA.js
401 lines (352 loc) · 12.4 KB
/
adapterUVA.js
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
const fs = require('fs');
const path = require('path');
const async = require('async');
const util = require('./util');
const RequestClient = require('./requestClient');
const Adapter = require('./adapter');
const UVA_HOST = "uva.onlinejudge.org";
const SUBMIT_PAGE_PATH = "/index.php?option=com_onlinejudge&Itemid=25";
const SUBMIT_PATH = "/index.php?option=com_onlinejudge&Itemid=25&page=save_submission";
const PROBLEM_PATH = "/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=";
const UHUNT_HOST = 'uhunt.felix-halim.net';
const LOGIN_FORM_PATTERN =
// group 1: form attribs
// group 2: form HTML contents
/<form([^>]+?id\s*=\s*["']?\w*mod_loginform[^>]*)>((?:.|\n)*?)<\/form>/i;
const INPUT_PATTERN =
// group 1: attribs
/<input([^>]+?)\/?>/gi;
module.exports = (function(parentCls){
// constructor
function cls(app, acct)
{
// super constructor call
parentCls.call(this, app, acct);
// private instance fields
var acctData = acct.getAdapterData();
var adapData = app.getAdapterData('uva');
var uvaClient = new RequestClient('https', UVA_HOST);
var uhuntClient = new RequestClient('http', UHUNT_HOST);
// private instance method
function fetchUserId(callback)
{
if (acctData.userId > 0)
return callback(null, acctData.userId);
uhuntClient.get('/api/uname2uid/' + acct.user(), function(err, res, data){
if (err)
return callback(err);
acctData.userId = parseInt(data);
callback(null, acctData.userId);
});
};
function fetchProbs(callback)
{
if (adapData.probs && adapData.mapNum){
return callback(null, adapData.probs);
}
uhuntClient.get('/api/p', function(err, res, data){
if (err)
return callback(err);
var p;
try
{
p = JSON.parse(data);
}
catch (e)
{
return callback(e);
}
var map = {}; // maps prob ID to array index
var mapNum = {}; // maps prob # to array index
for (var i=0;i < p.length; i++)
{
var cur = p[i];
map [cur[0].toString()] = i; // prob ID
mapNum[cur[1].toString()] = i; // prob #
}
adapData.map = map;
adapData.mapNum = mapNum;
callback(null, adapData.probs = p);
});
}
// public instance method
this.login = function(callback){
async.waterfall([
function(subCallback){
uvaClient.get('/', subCallback);
},
function(res, html, subCallback){
var f = cls.parseForm(LOGIN_FORM_PATTERN, html);
var err = null;
if (!f)
err = ("cannot find HTML form");
else if (!f.userField)
err = ("cannot find user field");
else if (!f.passField)
err = ("cannot find pass field");
else if (!f.action)
err = ("cannot find action");
if (err)
return subCallback(new Error(err));
f.data[f.userField] = acct.user();
f.data[f.passField] = acct.pass();
var opts = {
// Must not follow otherwise will miss the session cookie.
followAllRedirects: false,
headers: {
Referer: 'https://' + UVA_HOST,
},
};
uvaClient.post(f.action, f.data, opts, subCallback);
},
],
function(err, res, html){
if (err)
return callback(err);
callback();
});
};
/**
* Finds existing source code files which names contain the
* problem number.
* @return array of file names which fit the criteria; empty if not found.
*/
this.findFileNames = function(probNum){
var found = [];
var all = fs.readdirSync('.');
var probNumStr = probNum+'';
for (var i=0;i < all.length; i++)
{
var cur = all[i];
var ext = util.getFileExt(cur).toLowerCase();
var lang = util.getLang(ext);
if (lang >= 0)
{
var m = cur.match(/0*(\d+)/);
if (m && m[1] == probNumStr)
found.push(cur);
}
}
return found;
};
/**
* Infers the prob num from a file path
* @return undefined if not found; else the problem num as a string.
*/
this.inferProbNum = function(filePath){
var fileName = path.basename(filePath);
var m = fileName.match(/0*(\d+)/);
if (m) return m[1];
};
this._send = function(probNum, filePath, fileExt, callback){
var langVal = cls.getLangVal(util.getLang(fileExt.toLowerCase()));
if (langVal < 0)
return callback(new Error('unacceptable programming lang'));
var data = {
localid: probNum,
code: '',
language: langVal,
codeupl: fs.createReadStream(filePath),
problemid: '',
category: '',
};
var opts = {
headers: {
Referer: 'https://' + UVA_HOST + SUBMIT_PATH,
},
};
uvaClient.postMultipart(SUBMIT_PATH, data, opts, function(err, res, html){
if (err)
return callback(err);
if (html.match(/not\s+authori[zs]ed/i))
return callback(new Error('cannot login. password correct?'));
callback(null);
});
};
this.fetchStatus = function(num, callback){
var tries = 0;
function process(buf)
{
var obj;
try
{
obj = JSON.parse(buf);
}
catch(e)
{
return callback(e);
}
var subs = obj.subs;
// latest at 0th elem.
subs.sort(function(a,b){return b[0] - a[0];});
// must sort first then slice
if (subs.length > num)
subs = subs.slice(0, num);
/*
subs[i] is an array with fields in this order:
0: Submission ID
1: Problem ID
2: Verdict ID
3: Runtime
4: Submission Time (unix timestamp)
5: Language ID (1=ANSI C, 2=Java, 3=C++, 4=Pascal)
6: Submission Rank
*/
var p = adapData.probs;
var map = adapData.map;
var outdated = false;
for (var i=0;i < subs.length; i++)
{
var cur = subs[i];
var idx = map[cur[1].toString()];
if (p[idx])
cur[1] = p[idx][1];
else
{
cur[1] = -1;
outdated = true;
// don't break
}
cur[2] = cls.getVerdict(cur[2]);
cur[4] *= 1000; // convert to millisec
cur[5] = cls.getLang(cur[5]);
}
if (outdated && tries++ < 1)
{
// retry
adapData.probs = null;
return fetchProbs(function(e){
if (e) return callback(e);
process(buf);
});
}
callback(null, subs);
}
async.waterfall([
fetchProbs,
function(probs, subCallback){
fetchUserId(subCallback);
},
function(userId, subCallback){
uhuntClient.get('/api/subs-user/' + userId, subCallback);
},
],
function(err, res, data){
if (err)
return callback(err);
process(data);
});
};
this.getProblemURL = function(probNum, callback){
fetchProbs(function(e, probs){
var theProb = probs[adapData.mapNum[probNum+'']];
if (theProb)
{
var probId = theProb[0];
callback(null, 'http://'+UVA_HOST+PROBLEM_PATH + probId);
return;
}
callback(null,null);
});
};
}
cls.parseForm = function(formPat, html){
var match = formPat.exec(html);
if (! match) return null;
var attribs = match[1];
var contents = match[2];
var atts = util.parseAttribs(attribs);
var r = {contents: contents, data: {}};
for (var key in atts)
{
if (key.toLowerCase() === 'action')
{
r.action = util.htmlDecodeSimple(atts[key]);
break;
}
}
while(match = INPUT_PATTERN.exec(contents))
{
atts = util.parseAttribs(match[1]);
var value = null, name = null, isText = false;
for (var key in atts)
{
var val = util.htmlDecodeSimple(atts[key]);
var keyLower = key.toLowerCase();
var valLower = val.toLowerCase();
switch(keyLower)
{
case 'type':
isText = (valLower === 'password' || valLower === 'text');
break;
case 'name':
name = val;
break;
case 'value':
value = val;
break;
}
}
if (name !== null && isText)
{
var nameLower = name.toLowerCase();
if (nameLower.indexOf("user") >= 0)
r.userField = name;
else if (nameLower.indexOf("pass")>=0)
r.passField = name;
}
else if (value !== null && name !== null)
{
r.data[name] = value;
}
}
return r;
};
/**
* @param lang One of LANG_* constants
* @return UVA lang value or -1 if unacceptable.
*/
cls.getLangVal = function(lang){
switch (lang)
{
case util.LANG_C: return 1;
case util.LANG_JAVA: return 2;
case util.LANG_CPP: return 3;
case util.LANG_PASCAL: return 4;
case util.LANG_CPP11: return 5;
}
return -1;
};
cls.getVerdict = function(ver)
{
switch(ver)
{
case 10: return Adapter.STATUS_ERROR;
case 15: return Adapter.STATUS_QUEUE_ERROR;
case 20: return Adapter.STATUS_IN_QUEUE;
case 30: return Adapter.STATUS_COMPILE_ERROR;
case 35: return Adapter.STATUS_RESTRICTED_FN;
case 40: return Adapter.STATUS_RUNTIME_ERROR;
case 45: return Adapter.STATUS_OUTPUT_LIMIT;
case 50: return Adapter.STATUS_TIME_LIMIT;
case 60: return Adapter.STATUS_MEM_LIMIT;
case 70: return Adapter.STATUS_WRONG_ANS;
case 80: return Adapter.STATUS_PRESENTATION;
case 90: return Adapter.STATUS_ACCEPTED;
}
return Adapter.STATUS_UNKNOWN;
};
cls.getLang = function(id)
{
switch(id)
{
case 1: return "C";
case 2: return "Java";
case 3: return "C++";
case 4: return "Pascal";
case 5: return "C++11";
}
return "?";
};
return cls;
})(Adapter);