oj-submit 0.1.0

A fast, simple CLI for submitting solutions to the UVA Online Judge (onlinejudge.org)
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! HTML parsing utilities for onlinejudge.org (UVA OJ).
//!
//! The UVA OJ runs on Joomla CMS (circa 2005) and serves everything as HTML.
//! This module provides functions to parse login forms, verdict tables, and
//! authentication state from raw HTML strings.

use scraper::{Html, Selector};

/// Parsed login form with all hidden fields.
///
/// The UVA OJ login form (`#mod_loginform`) contains multiple hidden fields
/// generated by Joomla, including CSRF tokens with random names. All fields
/// are scraped dynamically — no field names are hardcoded.
#[derive(Debug, Clone, PartialEq)]
pub struct LoginForm {
    /// The form's `action` attribute (URL to POST to).
    pub action: String,
    /// All non-text/non-password input fields as (name, value) pairs.
    /// Includes hidden fields like `op2`, `lang`, CSRF tokens, etc.
    pub hidden_fields: Vec<(String, String)>,
}

/// A single verdict entry parsed from the status page submission table.
#[derive(Debug, Clone, PartialEq)]
pub struct Verdict {
    /// The run/submission ID (e.g., `"29964933"`).
    pub run_id: String,
    /// The problem number (e.g., `"100"`).
    pub problem_id: String,
    /// The problem name (e.g., `"The Starflyer Agents"`).
    pub problem_name: String,
    /// The verdict string (e.g., `"Accepted"`, `"In judge queue"`).
    pub verdict: String,
    /// The language used (e.g., `"C++11"`).
    pub language: String,
    /// The runtime in seconds (e.g., `"0.140"`).
    pub runtime: String,
    /// The submission date/time (e.g., `"2024-11-15 07:56:25"`).
    pub date: String,
}

/// Errors that can occur when parsing HTML from onlinejudge.org.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    /// The `<form id="mod_loginform">` element was not found in the HTML.
    #[error("Login form not found in HTML")]
    LoginFormNotFound,

    /// No table with `#` and `Verdict` headers was found in the HTML.
    #[error("Verdict table not found in HTML")]
    VerdictTableNotFound,

    /// The verdict table was found but contained no data rows.
    #[error("No submissions found")]
    NoSubmissions,
}

/// Parse the login form from the onlinejudge.org homepage HTML.
///
/// Finds `<form id="mod_loginform">` and extracts all `<input>` fields
/// (hidden, text, password, checkbox — everything). This ensures all
/// dynamically-generated Joomla CSRF tokens are captured.
///
/// # Errors
///
/// Returns `ParseError::LoginFormNotFound` if the form element is missing.
///
/// # Examples
///
/// ```ignore
/// let html = fetch_homepage().await?;
/// let form = parse_login_form(&html)?;
/// println!("Action URL: {}", form.action);
/// for (name, value) in &form.hidden_fields {
///     println!("  {name} = {value}");
/// }
/// ```
pub fn parse_login_form(html: &str) -> Result<LoginForm, ParseError> {
    let document = Html::parse_document(html);

    let form_selector =
        Selector::parse("form#mod_loginform").expect("valid CSS selector for form#mod_loginform");

    let form = document
        .select(&form_selector)
        .next()
        .ok_or(ParseError::LoginFormNotFound)?;

    let action = form.value().attr("action").unwrap_or("").to_string();

    let input_selector = Selector::parse("input").expect("valid CSS selector for input");

    let mut hidden_fields = Vec::new();

    for input in form.select(&input_selector) {
        let name = match input.value().attr("name") {
            Some(n) => n.to_string(),
            None => continue,
        };

        let value = input.value().attr("value").unwrap_or("").to_string();

        hidden_fields.push((name, value));
    }

    Ok(LoginForm {
        action,
        hidden_fields,
    })
}

/// Parse the verdict/status table from the onlinejudge.org status page HTML.
///
/// Finds the table whose header row contains both `#` and `Verdict`, then
/// parses all data rows into [`Verdict`] entries. The header row (row 0)
/// is skipped.
///
/// Each data row is expected to have 7 cells:
///
/// | Index | Field        |
/// |-------|-------------|
/// | 0     | Run ID      |
/// | 1     | Problem ID  |
/// | 2     | Problem Name|
/// | 3     | Verdict     |
/// | 4     | Language    |
/// | 5     | Runtime     |
/// | 6     | Date        |
///
/// # Errors
///
/// Returns `ParseError::VerdictTableNotFound` if no matching table exists,
/// or `ParseError::NoSubmissions` if the table has no data rows.
pub fn parse_verdict_table(html: &str) -> Result<Vec<Verdict>, ParseError> {
    let document = Html::parse_document(html);
    let table_selector = Selector::parse("table").expect("valid CSS selector for table");
    let tr_selector = Selector::parse("tr").expect("valid CSS selector for tr");
    let td_selector = Selector::parse("td, th").expect("valid CSS selector for td/th");

    // Find the table whose first row has both "#" and "Verdict" in header text
    let target_table = document
        .select(&table_selector)
        .find(|table| {
            table
                .select(&tr_selector)
                .next()
                .map(|first_row| {
                    let header_text = first_row.text().collect::<String>();
                    header_text.contains('#') && header_text.contains("Verdict")
                })
                .unwrap_or(false)
        })
        .ok_or(ParseError::VerdictTableNotFound)?;

    let rows: Vec<_> = target_table.select(&tr_selector).collect();

    // Skip header row (index 0)
    if rows.len() < 2 {
        return Err(ParseError::NoSubmissions);
    }

    let mut verdicts = Vec::new();

    for row in &rows[1..] {
        let cells: Vec<_> = row.select(&td_selector).collect();

        if cells.len() < 7 {
            continue; // skip malformed rows
        }

        let run_id = cells[0].text().collect::<String>().trim().to_string();

        // Problem ID may be inside a link — extract text content
        let problem_id = cells[1].text().collect::<String>().trim().to_string();

        let problem_name = cells[2].text().collect::<String>().trim().to_string();
        let verdict = cells[3].text().collect::<String>().trim().to_string();
        let language = cells[4].text().collect::<String>().trim().to_string();
        let runtime = cells[5].text().collect::<String>().trim().to_string();
        let date = cells[6].text().collect::<String>().trim().to_string();

        verdicts.push(Verdict {
            run_id,
            problem_id,
            problem_name,
            verdict,
            language,
            runtime,
            date,
        });
    }

    if verdicts.is_empty() {
        return Err(ParseError::NoSubmissions);
    }

    Ok(verdicts)
}

/// Parse and return only the most recent (first) verdict from the status page.
///
/// This is a convenience wrapper around [`parse_verdict_table`] that returns
/// just the first entry — typically the most recent submission.
///
/// # Errors
///
/// Forwards errors from [`parse_verdict_table`].
pub fn parse_latest_verdict(html: &str) -> Result<Verdict, ParseError> {
    parse_verdict_table(html)?
        .into_iter()
        .next()
        .ok_or(ParseError::NoSubmissions)
}

/// Check whether the HTML indicates the user is logged in.
///
/// Returns `false` if the HTML contains `"You need to login"` (the UVA OJ's
/// standard not-logged-in indicator), and `true` otherwise.
pub fn is_logged_in(html: &str) -> bool {
    !html.contains("You need to login")
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── Mock HTML generators ────────────────────────────────────────────────

    /// Simulates the login form from onlinejudge.org's homepage.
    /// Includes the 8 hidden fields confirmed via browser DOM inspection.
    fn mock_login_form_html() -> String {
        r#"
        <html>
        <body>
            <div id="module_login">
                <form id="mod_loginform" action="/index.php?option=com_comprofiler&task=login" method="post">
                    <input type="text" name="username" value="" class="inputbox" size="15" />
                    <input type="password" name="passwd" class="inputbox" size="15" />
                    <input type="checkbox" name="remember" value="yes" />
                    <input type="hidden" name="op2" value="login" />
                    <input type="hidden" name="lang" value="english" />
                    <input type="hidden" name="force_session" value="1" />
                    <input type="hidden" name="return" value="L2luZGV4LnBocD8%3D" />
                    <input type="hidden" name="message" value="0" />
                    <input type="hidden" name="loginfrom" value="loginmodule" />
                    <input type="hidden" name="cbsecuritym3" value="cbm_a1b2c3d4e5f6_token" />
                    <input type="hidden" name="j2cf4c0ff90f87bc0e1fb21187a441cc1" value="1" />
                    <input type="submit" name="Submit" value="Login" />
                </form>
            </div>
        </body>
        </html>
        "#
        .to_string()
    }

    /// Simulates the status page HTML with a verdict table.
    fn mock_verdict_table_html() -> String {
        r#"
        <html>
        <body>
            <table>
                <tr>
                    <th>#</th>
                    <th></th>
                    <th>Problem</th>
                    <th>Verdict</th>
                    <th>Language</th>
                    <th>Run Time</th>
                    <th>Submission Date</th>
                </tr>
                <tr>
                    <td>29964933</td>
                    <td><a href="/index.php?option=com_onlinejudge&page=problem&id=100">100</a></td>
                    <td><a href="/index.php?option=com_onlinejudge&page=problem&id=100">The 3n + 1 Problem</a></td>
                    <td>Accepted</td>
                    <td>C++11</td>
                    <td>0.140</td>
                    <td>2024-11-15 07:56:25</td>
                </tr>
                <tr>
                    <td>29964900</td>
                    <td><a href="/index.php?option=com_onlinejudge&page=problem&id=12315">12315</a></td>
                    <td><a href="/index.php?option=com_onlinejudge&page=problem&id=12315">The Starflyer Agents</a></td>
                    <td>Wrong Answer</td>
                    <td>Java</td>
                    <td>0.000</td>
                    <td>2024-11-14 12:30:00</td>
                </tr>
                <tr>
                    <td>29964800</td>
                    <td><a href="/index.php?option=com_onlinejudge&page=problem&id=50">50</a></td>
                    <td><a href="/index.php?option=com_onlinejudge&page=problem&id=50">Primary Arithmetic</a></td>
                    <td>In judge queue</td>
                    <td>PASCAL</td>
                    <td>-</td>
                    <td>2024-11-13 09:00:00</td>
                </tr>
            </table>
        </body>
        </html>
        "#
        .to_string()
    }

    /// Simulates the status page with only a header row (no submissions).
    fn mock_verdict_table_empty_html() -> String {
        r#"
        <html>
        <body>
            <table>
                <tr>
                    <th>#</th>
                    <th></th>
                    <th>Problem</th>
                    <th>Verdict</th>
                    <th>Language</th>
                    <th>Run Time</th>
                    <th>Submission Date</th>
                </tr>
            </table>
        </body>
        </html>
        "#
        .to_string()
    }

    /// Simulates a page with "You need to login" message.
    fn mock_not_logged_in_html() -> String {
        r#"
        <html>
        <body>
            <div>You need to login</div>
        </body>
        </html>
        "#
        .to_string()
    }

    /// Simulates a page for a logged-in user.
    fn mock_logged_in_html() -> String {
        r#"
        <html>
        <body>
            <div>Welcome, user123!</div>
        </body>
        </html>
        "#
        .to_string()
    }

    // ── LoginForm tests ─────────────────────────────────────────────────────

    #[test]
    fn test_parse_login_form_extracts_action() {
        let html = mock_login_form_html();
        let form = parse_login_form(&html).unwrap();
        assert_eq!(form.action, "/index.php?option=com_comprofiler&task=login");
    }

    #[test]
    fn test_parse_login_form_extracts_all_inputs() {
        let html = mock_login_form_html();
        let form = parse_login_form(&html).unwrap();

        // Should include: username, passwd, remember, op2, lang, force_session,
        // return, message, loginfrom, cbsecuritym3, j2cf..., Submit
        assert!(form.hidden_fields.len() >= 10);
    }

    #[test]
    fn test_parse_login_form_extracts_hidden_fields() {
        let html = mock_login_form_html();
        let form = parse_login_form(&html).unwrap();

        let field_map: std::collections::HashMap<&str, &str> = form
            .hidden_fields
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        assert_eq!(field_map.get("op2").copied(), Some("login"));
        assert_eq!(field_map.get("lang").copied(), Some("english"));
        assert_eq!(field_map.get("force_session").copied(), Some("1"));
        assert_eq!(field_map.get("return").copied(), Some("L2luZGV4LnBocD8%3D"));
        assert_eq!(field_map.get("message").copied(), Some("0"));
        assert_eq!(field_map.get("loginfrom").copied(), Some("loginmodule"));
        assert_eq!(
            field_map.get("cbsecuritym3").copied(),
            Some("cbm_a1b2c3d4e5f6_token")
        );
    }

    #[test]
    fn test_parse_login_form_extracts_csrf_token() {
        let html = mock_login_form_html();
        let form = parse_login_form(&html).unwrap();

        // The random-name Joomla CSRF field should be present
        let csrf = form
            .hidden_fields
            .iter()
            .find(|(name, _)| name.starts_with('j'))
            .expect("random-name CSRF field should be present");

        assert_eq!(csrf.1, "1");
    }

    #[test]
    fn test_parse_login_form_not_found() {
        let html = r#"<html><body><p>No form here</p></body></html>"#;
        let result = parse_login_form(html);
        assert!(matches!(result, Err(ParseError::LoginFormNotFound)));
    }

    #[test]
    fn test_parse_login_form_includes_visible_inputs() {
        let html = mock_login_form_html();
        let form = parse_login_form(&html).unwrap();

        let names: Vec<&str> = form.hidden_fields.iter().map(|(k, _)| k.as_str()).collect();
        assert!(names.contains(&"username"));
        assert!(names.contains(&"passwd"));
        assert!(names.contains(&"remember"));
        assert!(names.contains(&"Submit"));
    }

    // ── Verdict table tests ─────────────────────────────────────────────────

    #[test]
    fn test_parse_verdict_table_extracts_all_rows() {
        let html = mock_verdict_table_html();
        let verdicts = parse_verdict_table(&html).unwrap();
        assert_eq!(verdicts.len(), 3);
    }

    #[test]
    fn test_parse_verdict_table_first_row() {
        let html = mock_verdict_table_html();
        let verdicts = parse_verdict_table(&html).unwrap();
        let v = &verdicts[0];

        assert_eq!(v.run_id, "29964933");
        assert_eq!(v.problem_id, "100");
        assert_eq!(v.problem_name, "The 3n + 1 Problem");
        assert_eq!(v.verdict, "Accepted");
        assert_eq!(v.language, "C++11");
        assert_eq!(v.runtime, "0.140");
        assert_eq!(v.date, "2024-11-15 07:56:25");
    }

    #[test]
    fn test_parse_verdict_table_second_row() {
        let html = mock_verdict_table_html();
        let verdicts = parse_verdict_table(&html).unwrap();
        let v = &verdicts[1];

        assert_eq!(v.run_id, "29964900");
        assert_eq!(v.problem_id, "12315");
        assert_eq!(v.problem_name, "The Starflyer Agents");
        assert_eq!(v.verdict, "Wrong Answer");
        assert_eq!(v.language, "Java");
        assert_eq!(v.runtime, "0.000");
        assert_eq!(v.date, "2024-11-14 12:30:00");
    }

    #[test]
    fn test_parse_verdict_table_in_judge_queue() {
        let html = mock_verdict_table_html();
        let verdicts = parse_verdict_table(&html).unwrap();
        let v = &verdicts[2];

        assert_eq!(v.verdict, "In judge queue");
        assert_eq!(v.runtime, "-");
    }

    #[test]
    fn test_parse_verdict_table_not_found() {
        let html = r#"<html><body><p>No table here</p></body></html>"#;
        let result = parse_verdict_table(html);
        assert!(matches!(result, Err(ParseError::VerdictTableNotFound)));
    }

    #[test]
    fn test_parse_verdict_table_no_submissions() {
        let html = mock_verdict_table_empty_html();
        let result = parse_verdict_table(&html);
        assert!(matches!(result, Err(ParseError::NoSubmissions)));
    }

    #[test]
    fn test_parse_verdict_table_ignores_wrong_table() {
        // A page with an unrelated table should not match
        let html = r#"
        <html>
        <body>
            <table>
                <tr><td>Navigation</td></tr>
                <tr><td>Home</td></tr>
            </table>
        </body>
        </html>
        "#;
        let result = parse_verdict_table(html);
        assert!(matches!(result, Err(ParseError::VerdictTableNotFound)));
    }

    #[test]
    fn test_parse_verdict_table_problem_id_from_link() {
        let html = mock_verdict_table_html();
        let verdicts = parse_verdict_table(&html).unwrap();

        // Problem ID should be extracted as text content, not the href
        assert_eq!(verdicts[0].problem_id, "100");
        assert_eq!(verdicts[1].problem_id, "12315");
    }

    // ── parse_latest_verdict tests ──────────────────────────────────────────

    #[test]
    fn test_parse_latest_verdict_returns_first() {
        let html = mock_verdict_table_html();
        let v = parse_latest_verdict(&html).unwrap();

        assert_eq!(v.run_id, "29964933");
        assert_eq!(v.verdict, "Accepted");
    }

    #[test]
    fn test_parse_latest_verdict_empty_table() {
        let html = mock_verdict_table_empty_html();
        let result = parse_latest_verdict(&html);
        assert!(matches!(result, Err(ParseError::NoSubmissions)));
    }

    #[test]
    fn test_parse_latest_verdict_no_table() {
        let html = r#"<html><body></body></html>"#;
        let result = parse_latest_verdict(html);
        assert!(matches!(result, Err(ParseError::VerdictTableNotFound)));
    }

    // ── is_logged_in tests ──────────────────────────────────────────────────

    #[test]
    fn test_is_logged_in_false_when_not_logged_in() {
        let html = mock_not_logged_in_html();
        assert!(!is_logged_in(&html));
    }

    #[test]
    fn test_is_logged_in_true_when_logged_in() {
        let html = mock_logged_in_html();
        assert!(is_logged_in(&html));
    }

    #[test]
    fn test_is_logged_in_true_for_empty_html() {
        assert!(is_logged_in(""));
    }

    #[test]
    fn test_is_logged_in_case_sensitive() {
        // "You need to login" is case-sensitive on the real site
        let html = r#"<div>you need to login</div>"#;
        assert!(is_logged_in(html));
    }

    // ── Integration-style tests with more realistic HTML ────────────────────

    #[test]
    fn test_parse_login_form_with_multiple_hidden_fields() {
        // Simulate a page with extra Joomla hidden fields
        let html = r#"
        <html>
        <body>
            <form id="mod_loginform" action="/index.php?option=com_comprofiler&task=login" method="post">
                <input type="hidden" name="op2" value="login" />
                <input type="hidden" name="lang" value="english" />
                <input type="hidden" name="force_session" value="1" />
                <input type="hidden" name="return" value="L2luZGV4LnBocD8%3D" />
                <input type="hidden" name="message" value="0" />
                <input type="hidden" name="loginfrom" value="loginmodule" />
                <input type="hidden" name="cbsecuritym3" value="cbm_xyz123token" />
                <input type="hidden" name="j1a2b3c4d5e6f7g8" value="1" />
                <input type="hidden" name="extra_joomla_field" value="something" />
                <input type="text" name="username" value="" />
                <input type="password" name="passwd" value="" />
                <input type="submit" name="Submit" value="Login" />
            </form>
        </body>
        </html>
        "#;

        let form = parse_login_form(html).unwrap();
        assert_eq!(form.action, "/index.php?option=com_comprofiler&task=login");

        // 12 total inputs: 8 hidden + username + passwd + remember isn't here
        // Let's just check the count is reasonable
        assert!(form.hidden_fields.len() >= 10);

        // Verify the dynamic CSRF token is captured
        let field_map: std::collections::HashMap<&str, &str> = form
            .hidden_fields
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();

        assert_eq!(
            field_map.get("cbsecuritym3").copied(),
            Some("cbm_xyz123token")
        );
        assert_eq!(
            field_map.get("extra_joomla_field").copied(),
            Some("something")
        );
    }

    #[test]
    fn test_parse_verdict_table_with_extra_columns() {
        // Some pages might have extra navigation cells — verify we handle it
        let html = r#"
        <html>
        <body>
            <table>
                <tr>
                    <th>#</th>
                    <th></th>
                    <th>Problem</th>
                    <th>Verdict</th>
                    <th>Language</th>
                    <th>Run Time</th>
                    <th>Submission Date</th>
                </tr>
                <tr>
                    <td>12345</td>
                    <td><a href="/problem/100">100</a></td>
                    <td><a href="/problem/100">Test Problem</a></td>
                    <td>Compile Error</td>
                    <td>ANSI C</td>
                    <td>-</td>
                    <td>2025-01-01 00:00:00</td>
                </tr>
            </table>
        </body>
        </html>
        "#;

        let verdicts = parse_verdict_table(html).unwrap();
        assert_eq!(verdicts.len(), 1);
        assert_eq!(verdicts[0].verdict, "Compile Error");
        assert_eq!(verdicts[0].language, "ANSI C");
    }
}