forked from skygragon/leetcode-cli
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathleetcode_client.js
330 lines (265 loc) · 9 KB
/
leetcode_client.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
var _ = require('underscore');
var cheerio = require('cheerio');
var he = require('he');
var log = require('loglevel');
var request = require('request');
var config = require('./config');
var h = require('./helper');
// update options with user credentials
function signOpts(opts, user) {
opts.headers.Cookie = 'LEETCODE_SESSION=' + user.sessionId +
';csrftoken=' + user.sessionCSRF + ';';
opts.headers['X-CSRFToken'] = user.sessionCSRF;
opts.headers['X-Requested-With'] = 'XMLHttpRequest';
}
function makeOpts(url) {
var opts = {url: url, headers: {}, _expectedStatus: 200};
var core = require('./core');
if (core.isLogin()) signOpts(opts, core.getUser());
return opts;
}
function checkError(e, resp, expectedStatus, msg) {
if (e) return e;
if (resp && resp.statusCode !== expectedStatus) {
if (resp.statusCode === 403) {
msg = msg || 'session expired, please login again';
var core = require('./core');
core.logout();
}
return {
msg: msg || 'http error',
statusCode: resp.statusCode
};
}
}
// leetcode.com is limiting one session alive in the same time,
// which means once you login on web, your cli session will get
// expired immediately. In that case we will try to re-login in
// the backend to give a seamless user experience.
function requestWithReLogin(opts, cb) {
if (!config.AUTO_LOGIN)
return request(opts, cb);
var core = require('./core');
var user = core.getUser();
request(opts, function(e, resp, body) {
e = checkError(e, resp, opts._expectedStatus);
// not 403: transparently pass down
if (!e || e.statusCode !== 403)
return cb(e, resp, body);
// if 403: try re-login
log.debug('session expired, auto re-login...');
core.login(user, function(e2, user) {
if (e2) return cb(e, resp, body);
log.debug('login successfully, cont\'d...');
signOpts(opts, user);
request(opts, cb);
});
});
}
var leetcodeClient = {};
leetcodeClient.getProblems = function(cb) {
var opts = makeOpts(config.URL_PROBLEMS);
requestWithReLogin(opts, function(e, resp, body) {
e = checkError(e, resp, 200);
if (e) return cb(e);
var json = JSON.parse(body);
// leetcode permits anonymous access to the problem list
// while we require login first to make a better experience.
if (json.user_name.length === 0)
return cb('session expired, please login again');
var problems = json.stat_status_pairs
.filter(function(p) {
return !p.stat.question__hide;
})
.map(function(p) {
return {
state: p.status || 'None',
id: p.stat.question_id,
name: p.stat.question__title,
key: p.stat.question__title_slug,
link: config.URL_PROBLEM.replace('$id', p.stat.question__title_slug),
locked: p.paid_only,
percent: p.stat.total_acs * 100 / p.stat.total_submitted,
level: h.levelToName(p.difficulty.level),
starred: p.is_favor
};
});
return cb(null, problems);
});
};
// hacking ;P
var aceCtrl = {
init: function() {
return Array.prototype.slice.call(arguments);
}
};
leetcodeClient.getProblem = function(problem, cb) {
var opts = makeOpts();
opts.url = problem.link;
request(opts, function(e, resp, body) {
e = checkError(e, resp, 200);
// FIXME: if session expired, this will still return 200
if (e) return cb(e);
var $ = cheerio.load(body);
var info = $('div[class="question-info text-info"] ul li strong');
problem.totalAC = $(info[0]).text();
problem.totalSubmit = $(info[1]).text();
problem.desc = $('meta[property="og:description"]').attr('content');
problem.desc = he.decode(problem.desc);
var pageData;
var r = /(var pageData[^;]+;)/m;
var result = body.match(r);
if (!result)
return cb('failed to load' + (problem.locked ? ' locked ' : ' ') +
'problem!');
eval(result[1]);
problem.templates = pageData.codeDefinition;
problem.testcase = pageData.sampleTestCase;
problem.testable = pageData.enableRunCode;
return cb(null, problem);
});
};
leetcodeClient.getSubmissions = function(problem, cb) {
var opts = makeOpts();
opts.url = config.URL_SUBMISSIONS.replace('$key', problem.key);
opts.headers.Referer = config.URL_PROBLEM.replace('$id', problem.key);
request(opts, function(e, resp, body) {
e = checkError(e, resp, 200);
// FIXME: if session expired, this will still return 200
if (e) return cb(e);
// FIXME: this only return the 1st 20 submissions, we should get next if necessary.
var submissions = JSON.parse(body).submissions_dump;
_.each(submissions, function(submission) {
submission.id = _.last(_.compact(submission.url.split('/')));
});
return cb(null, submissions);
});
};
leetcodeClient.getSubmission = function(submission, cb) {
var opts = makeOpts();
opts.url = config.URL_SUBMISSION.replace('$id', submission.id);
request(opts, function(e, resp, body) {
e = checkError(e, resp, 200);
if (e) return cb(e);
var re = body.match(/submissionCode:\s('[^']*')/);
if (re) {
submission.code = eval(re[1]);
}
return cb(null, submission);
});
};
leetcodeClient.login = function(user, cb) {
request(config.URL_LOGIN, function(e, resp, body) {
e = checkError(e, resp, 200);
if (e) return cb(e);
user.loginCSRF = h.getSetCookieValue(resp, 'csrftoken');
var opts = {
url: config.URL_LOGIN,
headers: {
Origin: config.URL_BASE,
Referer: config.URL_LOGIN,
Cookie: 'csrftoken=' + user.loginCSRF + ';'
},
form: {
csrfmiddlewaretoken: user.loginCSRF,
login: user.login,
password: user.pass
}
};
request.post(opts, function(e, resp, body) {
e = checkError(e, resp, 302, 'invalid password?');
if (e) return cb(e);
user.sessionCSRF = h.getSetCookieValue(resp, 'csrftoken');
user.sessionId = h.getSetCookieValue(resp, 'LEETCODE_SESSION');
user.name = h.getSetCookieValue(resp, 'messages')
.match('Successfully signed in as ([^.]*)')[1];
return cb(null, user);
});
});
};
function verifyResult(opts, jobs, results, cb) {
if (jobs.length === 0)
return cb(null, results);
opts.method = 'GET';
opts.url = config.URL_VERIFY.replace('$id', jobs[0].id);
requestWithReLogin(opts, function(e, resp, body) {
e = checkError(e, resp, 200);
if (e) return cb(e);
var result = JSON.parse(body);
if (result.state === 'SUCCESS') {
result.name = jobs[0].name;
results.push(result);
jobs.shift();
}
setImmediate(verifyResult, opts, jobs, results, cb);
});
}
function runCode(opts, problem, cb) {
opts.method = 'POST';
opts.headers.Origin = config.URL_BASE;
opts.headers.Referer = problem.link;
opts.json = true;
opts._delay = opts._delay || 1; // in seconds
opts.body = opts.body || {};
_.extendOwn(opts.body, {
'lang': h.extToLang(problem.file),
'question_id': parseInt(problem.id, 10),
'test_mode': false,
'typed_code': h.getFileData(problem.file)
});
requestWithReLogin(opts, function(e, resp, body) {
e = checkError(e, resp, 200);
if (e) return cb(e);
if (body.error) {
if (body.error.indexOf('run code too soon') < 0)
return cb(body.error);
// hit 'run code too soon' error, have to wait a bit
log.debug(body.error);
// linear wait
++opts._delay;
log.debug('Will retry after %d seconds...', opts._delay);
var reRun = _.partial(runCode, opts, problem, cb);
return setTimeout(reRun, opts._delay * 1000);
}
opts.json = false;
opts.body = null;
return cb(null, body);
});
}
leetcodeClient.testProblem = function(problem, cb) {
var opts = makeOpts();
opts.url = config.URL_TEST.replace('$key', problem.key);
opts.body = {'data_input': problem.testcase};
runCode(opts, problem, function(e, task) {
if (e) return cb(e);
var jobs = [
{name: 'Your', id: task.interpret_id},
{name: 'Expected', id: task.interpret_expected_id}
];
verifyResult(opts, jobs, [], cb);
});
};
leetcodeClient.submitProblem = function(problem, cb) {
var opts = makeOpts();
opts.url = config.URL_SUBMIT.replace('$key', problem.key);
opts.body = {'judge_type': 'large'};
runCode(opts, problem, function(e, task) {
if (e) return cb(e);
var jobs = [{name: 'Your', id: task.submission_id}];
verifyResult(opts, jobs, [], cb);
});
};
leetcodeClient.starProblem = function(problem, starred, cb) {
var opts = makeOpts(config.URL_STAR);
opts.method = (starred ? 'POST' : 'DELETE');
opts.headers.Origin = config.URL_BASE;
opts.headers.Referer = problem.link;
opts.json = true;
opts.body = {'qid': problem.id};
requestWithReLogin(opts, function(e, resp, body) {
e = checkError(e, resp, 200);
if (e) return cb(e);
cb(null, body.is_favor);
});
};
module.exports = leetcodeClient;