leetctl 0.3.0

LeetCode command-line interface in Rust, with curated problem sets and filtered random picking.
Documentation
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Save bad network\'s ass.
pub mod models;
pub mod parser;
pub mod reviews;
pub mod schemas;
mod sql;
use self::models::*;
use self::schemas::{problems::dsl::*, tags::dsl::*};
use self::sql::*;
use crate::helper::test_cases_path;
use crate::{config::Config, err::Error, plugins::LeetCode};
use anyhow::anyhow;
use diesel::prelude::*;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashMap;
use std::time::{Duration, Instant};
use wreq::Response;

/// How long to wait between two polls of the judge, and how long to keep polling before
/// giving up. LeetCode budgets requests per machine and answers anything over the budget
/// with a 429 or a Cloudflare challenge page instead of JSON, so the gap has to stay in
/// human territory: the previous 3ms gap fired hundreds of `check` requests per run and
/// left the next `leetctl test` throttled.
const VERIFY_POLL_INTERVAL: Duration = Duration::from_millis(500);
const VERIFY_POLL_TIMEOUT: Duration = Duration::from_secs(120);

/// Why LeetCode answered with something other than an API result.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Block {
    /// HTTP 429 — too many requests from this machine.
    RateLimit,
    /// Cloudflare's bot interstitial. It arrives with perfectly valid cookies, so telling it
    /// apart keeps the "your cookies expired" message for actual auth failures, and telling
    /// it apart from a 429 keeps the advice honest: the two have different remedies.
    Challenge,
}

impl From<Block> for Error {
    fn from(block: Block) -> Self {
        match block {
            Block::RateLimit => Error::Throttled,
            Block::Challenge => Error::CloudflareChallenge,
        }
    }
}

/// Classify a response that may be a block page rather than an API answer.
fn detect_block(http_status: wreq::StatusCode, body: &str) -> Option<Block> {
    if http_status == wreq::StatusCode::TOO_MANY_REQUESTS {
        return Some(Block::RateLimit);
    }
    if body.contains("cf_chl_opt") || body.contains("<title>Just a moment...</title>") {
        return Some(Block::Challenge);
    }
    None
}

/// sqlite connection
pub fn conn(p: String) -> Result<SqliteConnection, Error> {
    SqliteConnection::establish(&p).map_err(|source| Error::CacheOpen { path: p, source })
}

/// Condition submit or test
#[derive(Clone, Debug, Default)]
pub enum Run {
    Test,
    #[default]
    Submit,
}

/// Requests if data not download
#[derive(Clone)]
pub struct Cache(pub LeetCode);

impl Cache {
    /// Ref to sqlite connection
    fn conn(&self) -> Result<SqliteConnection, Error> {
        conn(self.0.conf.storage.cache()?)
    }

    /// Clean cache
    pub fn clean(&self) -> Result<(), Error> {
        Ok(std::fs::remove_file(self.0.conf.storage.cache()?)?)
    }

    /// ref to download problems
    pub async fn update(self) -> Result<(), Error> {
        self.download_problems().await?;
        Ok(())
    }

    pub fn update_after_ac(self, rid: i32) -> Result<(), Error> {
        let mut c = conn(self.0.conf.storage.cache()?)?;
        let target = problems.filter(id.eq(rid));
        diesel::update(target)
            .set(status.eq("ac"))
            .execute(&mut c)?;
        Ok(())
    }

    async fn get_user_info(&self) -> Result<(String, bool), Error> {
        let user = parser::user(self.clone().0.get_user_info().await?.json().await?);
        match user {
            None => Err(Error::NoneError),
            Some(None) => Err(Error::CookieError),
            Some(Some((s, b))) => Ok((s, b)),
        }
    }

    async fn is_session_bad(&self) -> bool {
        // i.e. self.get_user_info().contains_err(Error::CookieError)
        matches!(self.get_user_info().await, Err(Error::CookieError))
    }

    async fn resp_to_json<T: DeserializeOwned>(&self, resp: Response) -> Result<T, Error> {
        let http_status = resp.status();
        let text = resp.text().await?;
        if let Some(block) = detect_block(http_status, &text) {
            return Err(block.into());
        }

        match serde_json::from_str(&text) {
            Ok(json) => Ok(json),
            Err(e) => {
                if self.is_session_bad().await {
                    Err(Error::CookieError)
                } else {
                    Err(e.into())
                }
            }
        }
    }

    /// Download leetcode problems to db
    pub async fn download_problems(self) -> Result<Vec<Problem>, Error> {
        info!("Fetching leetcode problems...");
        let mut ps: Vec<Problem> = vec![];

        for i in &self.0.conf.sys.categories.to_owned() {
            let json = self
                .0
                .clone()
                .get_category_problems(i)
                .await?
                .json() // does not require LEETCODE_SESSION
                .await?;
            parser::problem(&mut ps, json).ok_or(Error::NoneError)?;
        }

        diesel::replace_into(problems)
            .values(&ps)
            .execute(&mut self.conn()?)?;

        Ok(ps)
    }

    /// Get problem
    pub fn get_problem(&self, rfid: i32) -> Result<Problem, Error> {
        let p: Problem = problems.filter(fid.eq(rfid)).first(&mut self.conn()?)?;
        if p.category != "algorithms" {
            return Err(anyhow!("No support for database and shell questions yet").into());
        }

        Ok(p)
    }

    /// Get problem from name
    pub fn get_problem_id_from_name(&self, problem_name: &String) -> Result<i32, Error> {
        let p: Problem = problems
            .filter(name.eq(problem_name))
            .first(&mut self.conn()?)?;
        if p.category != "algorithms" {
            return Err(anyhow!("No support for database and shell questions yet").into());
        }
        Ok(p.fid)
    }

    /// Get daily problem
    pub async fn get_daily_problem_id(&self) -> Result<i32, Error> {
        parser::daily(
            self.clone()
                .0
                .get_question_daily()
                .await?
                .json() // does not require LEETCODE_SESSION
                .await?,
        )
        .ok_or(Error::NoneError)
    }

    /// The frontend id of the problem LeetCode calls `internal_id`.
    ///
    /// The judge answers in internal ids, and everything the user types — `leetctl pick 1`, the
    /// review deck's key — is a frontend id. This is the only place the two are joined.
    fn problem_fid(&self, internal_id: i32) -> Result<i32, Error> {
        Ok(problems
            .filter(id.eq(internal_id))
            .select(fid)
            .first(&mut self.conn()?)?)
    }

    /// Feed a finished submission into the review deck.
    ///
    /// An accepted submission enrols the problem and grades it `good`. A rejected one grades an
    /// already-enrolled problem `again` and does nothing else: failing a problem you have never
    /// solved is not a lapse, and enrolling it would fill the deck with problems you have not
    /// learned yet. Test runs never reach here — see `VerifyResult::submitted_problem_id`.
    fn record_submission(&self, res: &VerifyResult) -> Result<(), Error> {
        let Some(internal_id) = res.submitted_problem_id()? else {
            return Ok(());
        };

        let rfid = self.problem_fid(internal_id)?;
        let today = crate::srs::today();

        if res.is_accepted() {
            self.grade_review(rfid, crate::srs::Grade::Good, today)?;
        } else {
            self.grade_enrolled_review(rfid, crate::srs::Grade::Again, today)?;
        }

        Ok(())
    }

    /// Get problems from cache
    pub fn get_problems(&self) -> Result<Vec<Problem>, Error> {
        Ok(problems.load::<Problem>(&mut self.conn()?)?)
    }

    /// Get question
    #[allow(clippy::useless_let_if_seq)]
    pub async fn get_question(&self, rfid: i32) -> Result<Question, Error> {
        let target: Problem = problems.filter(fid.eq(rfid)).first(&mut self.conn()?)?;

        if target.category != "algorithms" {
            return Err(anyhow!("No support for database and shell questions yet").into());
        }

        let mut rdesc = Question::default();
        if !target.desc.is_empty() {
            rdesc = serde_json::from_str(&target.desc)?;
        } else {
            let json: Value = self
                .0
                .clone()
                .get_question_detail(&target.slug)
                .await?
                .json()
                .await?;
            debug!("{:#?}", json);
            match parser::desc(&mut rdesc, json) {
                None => return Err(Error::NoneError),
                Some(false) => {
                    return if self.is_session_bad().await {
                        Err(Error::CookieError)
                    } else {
                        Err(Error::PremiumError)
                    };
                }
                Some(true) => (),
            }

            // update the question
            let sdesc = serde_json::to_string(&rdesc)?;
            diesel::update(&target)
                .set(desc.eq(sdesc))
                .execute(&mut self.conn()?)?;
        }

        Ok(rdesc)
    }

    pub async fn get_tagged_questions(self, rslug: &str) -> Result<Vec<String>, Error> {
        trace!("Geting {} questions...", rslug);
        let ids: Vec<String>;
        let rtag = tags
            .filter(tag.eq(rslug.to_string()))
            .first::<Tag>(&mut self.conn()?);
        if let Ok(t) = rtag {
            trace!("Got {} questions from local cache...", rslug);
            ids = serde_json::from_str(&t.refs)?;
        } else {
            ids = parser::tags(
                self.clone()
                    .0
                    .get_question_ids_by_tag(rslug)
                    .await?
                    .json()
                    .await?,
            )
            .ok_or(Error::NoneError)?;
            let t = Tag {
                r#tag: rslug.to_string(),
                r#refs: serde_json::to_string(&ids)?,
            };

            diesel::insert_into(tags)
                .values(&t)
                .execute(&mut self.conn()?)?;
        }

        Ok(ids)
    }

    pub fn get_tags(&self) -> Result<Vec<Tag>, Error> {
        Ok(tags.load::<Tag>(&mut self.conn()?)?)
    }

    /// run_code data
    async fn pre_run_code(
        &self,
        run: Run,
        rfid: i32,
        test_case: Option<String>,
    ) -> Result<(HashMap<&'static str, String>, [String; 2]), Error> {
        trace!("pre-run code...");
        use crate::helper::code_path;
        use std::fs::File;
        use std::io::Read;

        let mut p = self.get_problem(rfid)?;
        if p.desc.is_empty() {
            trace!("Problem description does not exist, pull desc and exec again...");
            self.get_question(rfid).await?;
            p = self.get_problem(rfid)?;
        }

        let d: Question = serde_json::from_str(&p.desc)?;
        let conf = &self.0.conf;
        let mut json: HashMap<&'static str, String> = HashMap::new();
        let mut code: String = "".to_string();

        let maybe_file_testcases: Option<String> = test_cases_path(&p)
            .map(|file_name| {
                let mut tests = "".to_string();
                File::open(file_name)
                    .and_then(|mut file_descriptor| file_descriptor.read_to_string(&mut tests))
                    .map(|_| Some(tests))
                    .unwrap_or(None)
            })
            .unwrap_or(None);

        let maybe_all_testcases: Option<String> = if d.all_cases.is_empty() {
            None
        } else {
            Some(d.all_cases.to_string())
        };

        // Takes test cases using following priority
        // 1. cli parameter
        // 2. if test cases file exist, use the file test cases(user can edit it)
        // 3. test cases from problem desc all test cases
        // 4. sample test case from the task
        let test_case = test_case
            .or(maybe_file_testcases)
            .or(maybe_all_testcases)
            .unwrap_or(d.case);

        File::open(code_path(&p, None)?)?.read_to_string(&mut code)?;

        let code = if conf.code.edit_code_marker {
            let begin = code.find(&conf.code.start_marker);
            let end = code.find(&conf.code.end_marker);
            if let (Some(l), Some(r)) = (begin, end) {
                code.get((l + conf.code.start_marker.len())..r)
                    .map(|s| s.to_string())
                    .unwrap_or_else(|| code)
            } else {
                code
            }
        } else {
            code
        };

        json.insert("lang", conf.code.lang.to_string());
        json.insert("question_id", p.id.to_string());
        json.insert("typed_code", code);

        // pass manually data
        json.insert("name", p.name.to_string());
        json.insert("data_input", test_case);

        let url = match run {
            Run::Test => conf.sys.urls.test(&p.slug),
            Run::Submit => {
                json.insert("judge_type", "large".to_string());
                conf.sys.urls.submit(&p.slug)
            }
        };

        Ok((json, [url, conf.sys.urls.problem(&p.slug)]))
    }

    /// Poll the judge until it reports the run finished.
    async fn poll_verify(&self, rid: String) -> Result<VerifyResult, Error> {
        trace!("Polling judge for {rid}...");
        let deadline = Instant::now() + VERIFY_POLL_TIMEOUT;

        loop {
            tokio::time::sleep(VERIFY_POLL_INTERVAL).await;

            let res: VerifyResult = self
                .resp_to_json(self.clone().0.verify_result(rid.clone()).await?)
                .await?;
            if res.state == "SUCCESS" {
                return Ok(res);
            }
            if Instant::now() >= deadline {
                return Err(Error::VerifyTimeout { rid });
            }
        }
    }

    /// Exec problem filter —— Test or Submit
    pub async fn exec_problem(
        &self,
        rfid: i32,
        run: Run,
        test_case: Option<String>,
    ) -> Result<VerifyResult, Error> {
        trace!("Exec problem filter —— Test or Submit");
        let (json, [url, refer]) = self.pre_run_code(run.clone(), rfid, test_case).await?;
        trace!("Pre-run code result {:#?}, {}, {}", json, url, refer);

        let resp = self
            .0
            .clone()
            .run_code(json.clone(), url.clone(), refer.clone())
            .await?;
        let http_status = resp.status();
        let text = resp.text().await?;
        if let Some(block) = detect_block(http_status, &text) {
            return Err(block.into());
        }

        let run_res: RunCode = serde_json::from_str(&text).map_err(|e| {
            anyhow!(
                "Failed to decode run code result, could be caused by cookie expiration, \
                 csrf token mismatch, or network issue:\n {e}, raw response:\n {text}\n, \
                 please report this issue at https://github.com/siansiansu/leetctl/issues/new"
            )
        })?;

        trace!("Run code result {:#?}", run_res);

        // Check if leetcode accepted the Run request
        if match run {
            Run::Test => run_res.interpret_id.is_empty(),
            Run::Submit => run_res.submission_id == 0,
        } {
            return Err(Error::CookieError);
        }

        let mut res = match run {
            Run::Test => self.poll_verify(run_res.interpret_id.clone()).await?,
            Run::Submit => self.poll_verify(run_res.submission_id.to_string()).await?,
        };
        trace!("Recur verify result {:#?}", res);

        res.name = json.get("name").ok_or(Error::NoneError)?.to_string();
        res.data_input = json.get("data_input").ok_or(Error::NoneError)?.to_string();
        res.result_type = run;

        // Marking the row solved belongs to the submission, not to rendering its result. It used
        // to happen inside `VerifyResult`'s `Display` impl, which meant formatting a result wrote
        // to sqlite — the TUI formats results while drawing. The review deck is written here for
        // the same reason.
        if let Some(pid) = res.accepted_problem_id()? {
            self.clone().update_after_ac(pid)?;
        }
        self.record_submission(&res)?;

        Ok(res)
    }

    /// New cache
    pub fn new() -> Result<Self, Error> {
        let conf = Config::locate()?;
        let mut c = conn(conf.storage.cache()?)?;
        diesel::sql_query(CREATE_PROBLEMS_IF_NOT_EXISTS).execute(&mut c)?;
        diesel::sql_query(CREATE_TAGS_IF_NOT_EXISTS).execute(&mut c)?;
        diesel::sql_query(CREATE_REVIEWS_IF_NOT_EXISTS).execute(&mut c)?;

        Ok(Cache(LeetCode::new()?))
    }
}

#[cfg(test)]
mod tests {
    use super::{Block, detect_block};
    use wreq::StatusCode;

    const CHALLENGE_PAGE: &str = "<!DOCTYPE html><html lang=\"en-US\"><head>\
        <title>Just a moment...</title></head><body><script>\
        (function(){window._cf_chl_opt = {cRay: 'a2d10820ce8588ff'};}());</script></body></html>";

    #[test]
    fn detect_block_reads_a_cloudflare_challenge_page_as_a_challenge() {
        assert_eq!(
            detect_block(StatusCode::OK, CHALLENGE_PAGE),
            Some(Block::Challenge)
        );
    }

    #[test]
    fn detect_block_reads_429_as_a_rate_limit() {
        assert_eq!(
            detect_block(StatusCode::TOO_MANY_REQUESTS, "<html>slow down</html>"),
            Some(Block::RateLimit)
        );
    }

    #[test]
    fn detect_block_passes_judge_json() {
        assert_eq!(
            detect_block(StatusCode::OK, r#"{"state":"SUCCESS","status_code":10}"#),
            None
        );
    }

    #[test]
    fn detect_block_passes_non_cloudflare_html() {
        // A logged-out request gets LeetCode's own login page; that is a cookie problem,
        // not a block, and must keep reaching the `CookieError` branch.
        assert_eq!(
            detect_block(
                StatusCode::FORBIDDEN,
                "<!DOCTYPE html><html><head><title>Sign In</title></head></html>"
            ),
            None
        );
    }
}