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
//! HTTP client for interacting with the UVA Online Judge at onlinejudge.org.
//!
//! [`UvaClient`] manages session cookies via [`reqwest::Client`] and provides
//! methods for authentication, solution submission, verdict polling, and
//! querying the uHunt auxiliary API.
//!
//! # Usage
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use crate::client::UvaClient;
//! use crate::config::Credentials;
//!
//! let creds = Credentials::load()?;
//! let mut client = UvaClient::new(false)?;
//! client.login(&creds).await?;
//! let result = client.submit("100", 5, "#include <iostream>...").await?;
//! println!("Run ID: {}", result.run_id);
//! # Ok(())
//! # }
//! ```

use reqwest::Client;
use serde::Deserialize;

use crate::config::Credentials;
use crate::parser::{self, Verdict};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const BASE_URL: &str = "https://onlinejudge.org";
const LOGIN_URL: &str = "https://onlinejudge.org/index.php?option=com_comprofiler&task=login";
const SUBMIT_URL: &str =
    "https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=25&page=save_submission";
const STATUS_URL: &str = "https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=9";
const UHUNT_BASE: &str = "https://uhunt.onlinejudge.org/api";

const USER_AGENT: &str = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 \
     (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
const ACCEPT_LANGUAGE: &str = "en-US,en;q=0.9";

/// Default maximum time (in seconds) to poll for a verdict.
const DEFAULT_POLL_TIMEOUT: u64 = 120;

/// Interval in seconds between verdict polls.
const POLL_INTERVAL_SECS: u64 = 1;

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

/// An HTTP client for the UVA Online Judge.
///
/// Wraps [`reqwest::Client`] with automatic cookie management and provides
/// high-level methods for the complete submission workflow.
pub struct UvaClient {
    client: Client,
    verbose: bool,
}

/// The result of a successful submission POST.
#[derive(Debug, Clone)]
pub struct SubmissionResult {
    /// The run (submission) ID assigned by the judge.
    pub run_id: String,
    /// The initial verdict text (typically `"In judge queue"`).
    pub initial_verdict: String,
}

/// A submission record returned by the uHunt API.
#[derive(Debug, Clone, Deserialize)]
pub struct UhuntSubmission {
    #[serde(rename = "run")]
    pub run_id: u32,
    #[serde(rename = "probid")]
    pub problem_id: u32,
    #[serde(rename = "ver")]
    pub verdict_code: u32,
    #[serde(rename = "pte")]
    pub runtime: u32,
    #[serde(rename = "lang")]
    pub language: String,
    #[serde(rename = "out")]
    pub date: String,
}

/// Errors that can occur when interacting with the UVA Online Judge.
#[derive(Debug, thiserror::Error)]
pub enum ClientError {
    #[error("Login failed: {0}")]
    LoginFailed(String),

    #[error("Network error: {0}")]
    NetworkError(#[from] reqwest::Error),

    #[error("Parse error: {0}")]
    ParseError(String),

    #[error("Polling timed out after {0} seconds")]
    PollingTimeout(u64),
}

// ---------------------------------------------------------------------------
// UvaClient implementation
// ---------------------------------------------------------------------------

impl UvaClient {
    /// Create a new client with cookie support enabled.
    ///
    /// The underlying [`reqwest::Client`] is configured with:
    /// - A cookie store for session persistence
    /// - A browser-like `User-Agent` header
    /// - English `Accept-Language` header
    ///
    /// # Errors
    ///
    /// Returns a [`reqwest::Error`] if the HTTP client cannot be built.
    pub fn new(verbose: bool) -> Result<Self, reqwest::Error> {
        let client = Client::builder()
            .cookie_store(true)
            .user_agent(USER_AGENT)
            .build()?;

        Ok(UvaClient { client, verbose })
    }

    /// Authenticate with onlinejudge.org using the given credentials.
    ///
    /// This method:
    /// 1. GETs the index page to establish a session cookie (`phpSESSID`).
    /// 2. Parses the login form to extract all hidden fields (CSRF tokens, etc.).
    /// 3. POSTs the login form with username, password, and all hidden fields.
    /// 4. Verifies login by checking the status page for the absence of
    ///    `"You need to login"`.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::LoginFailed`] if authentication fails (wrong
    /// credentials, missing CSRF token, etc.).
    pub async fn login(&mut self, credentials: &Credentials) -> Result<(), ClientError> {
        if self.verbose {
            eprintln!("[verbose] GET {}", BASE_URL);
        }

        // Step 1: GET the index page to obtain a session cookie.
        let index_resp = self
            .client
            .get(BASE_URL)
            .header("Accept-Language", ACCEPT_LANGUAGE)
            .send()
            .await?;

        if !index_resp.status().is_success() {
            return Err(ClientError::LoginFailed(format!(
                "Failed to load index page: HTTP {}",
                index_resp.status()
            )));
        }

        let index_html = index_resp.text().await?;

        if self.verbose {
            eprintln!(
                "[verbose] Index page loaded ({} bytes), parsing login form...",
                index_html.len()
            );
        }

        // Step 2: Parse the login form to extract hidden fields.
        let login_form = parser::parse_login_form(&index_html)
            .map_err(|e| ClientError::ParseError(format!("Failed to parse login form: {e}")))?;

        if self.verbose {
            eprintln!(
                "[verbose] Found {} fields in login form",
                login_form.hidden_fields.len()
            );
            for (k, v) in &login_form.hidden_fields {
                eprintln!("  {k} = {v}");
            }
        }

        // Step 3: Build POST data — hidden fields + credentials.
        // `hidden_fields` is a Vec<(String, String)> containing all inputs
        // including username/password/Submit — we filter those out and add
        // our own controlled values.
        let mut post_data: Vec<(&str, &str)> = login_form
            .hidden_fields
            .iter()
            .filter(|(name, _)| name != "username" && name != "passwd" && name != "Submit")
            .map(|(k, v)| (k.as_str(), v.as_str()))
            .collect();
        post_data.push(("username", &credentials.username));
        post_data.push(("passwd", &credentials.password));
        post_data.push(("remember", "yes"));

        if self.verbose {
            eprintln!("[verbose] POST {}", LOGIN_URL);
        }

        let login_resp = self
            .client
            .post(LOGIN_URL)
            .header("Accept-Language", ACCEPT_LANGUAGE)
            .form(&post_data)
            .send()
            .await?;

        if self.verbose {
            eprintln!(
                "[verbose] Login response: HTTP {} (redirected to {})",
                login_resp.status(),
                login_resp.url()
            );
        }

        // Step 4: Verify login by checking the status page.
        if self.verbose {
            eprintln!("[verbose] GET {} (login verification)", STATUS_URL);
        }

        let status_resp = self
            .client
            .get(STATUS_URL)
            .header("Accept-Language", ACCEPT_LANGUAGE)
            .send()
            .await?;

        let status_html = status_resp.text().await?;

        if !parser::is_logged_in(&status_html) {
            return Err(ClientError::LoginFailed(
                "Incorrect username or password, or session setup failed".to_string(),
            ));
        }

        if self.verbose {
            eprintln!("[verbose] Login verified successfully");
        }

        Ok(())
    }

    /// Submit a solution to the UVA Online Judge.
    ///
    /// Posts the source code to the submission endpoint and parses the
    /// redirected status page to extract the initial verdict and run ID.
    ///
    /// # Arguments
    ///
    /// * `problem_id` — The UVA problem number as a string (e.g. `"100"`).
    /// * `language_code` — The language code (1=C, 2=Java, 3=C++, 4=Pascal,
    ///   5=C++11, 6=Python3).
    /// * `source_code` — The full source code as a string.
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::SubmissionFailed`] if the POST fails or the
    /// response cannot be parsed.
    pub async fn submit(
        &mut self,
        problem_id: &str,
        language_code: u8,
        source_code: &str,
    ) -> Result<SubmissionResult, ClientError> {
        // Build multipart form data.
        let form = reqwest::multipart::Form::new()
            .text("problemid".to_string(), String::new())
            .text("category".to_string(), String::new())
            .text("localid".to_string(), problem_id.to_string())
            .text("language".to_string(), language_code.to_string())
            .text("code".to_string(), source_code.to_string());

        if self.verbose {
            eprintln!(
                "[verbose] POST {} (problem={}, lang={})",
                SUBMIT_URL, problem_id, language_code
            );
        }

        let submit_resp = self
            .client
            .post(SUBMIT_URL)
            .header("Accept-Language", ACCEPT_LANGUAGE)
            .multipart(form)
            .send()
            .await?;

        let submit_url = submit_resp.url().to_string();
        let submit_status = submit_resp.status();

        if self.verbose {
            eprintln!(
                "[verbose] Submit response: HTTP {} (url: {})",
                submit_status, submit_url
            );
        }

        // The server typically responds with a redirect to the status page.
        // Regardless, we discard the submission response body and explicitly
        // GET the status page to find our submission.
        if self.verbose {
            eprintln!(
                "[verbose] GET {} (fetching status after submission)",
                STATUS_URL
            );
        }

        // Small delay to let the server process the submission.
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;

        let status_resp = self
            .client
            .get(STATUS_URL)
            .header("Accept-Language", ACCEPT_LANGUAGE)
            .send()
            .await?;

        let status_html = status_resp.text().await?;

        if self.verbose {
            eprintln!("[verbose] Status page loaded ({} bytes)", status_html.len());
            // Print a snippet to help debug parsing issues
            if status_html.len() > 500 {
                eprintln!("[verbose] First 500 chars: {}", &status_html[..500]);
            }
        }

        // Parse the status page to extract the run ID and initial verdict.
        let verdict = parser::parse_latest_verdict(&status_html).map_err(|e| {
            ClientError::ParseError(format!("Failed to parse submission response: {e}"))
        })?;

        if self.verbose {
            eprintln!(
                "[verbose] Parsed submission result: run_id={}, verdict={}",
                verdict.run_id, verdict.verdict
            );
        }

        Ok(SubmissionResult {
            run_id: verdict.run_id,
            initial_verdict: verdict.verdict,
        })
    }

    /// Poll the status page for a final verdict.
    ///
    /// Repeatedly GETs the status page every [`POLL_INTERVAL_SECS`] second(s)
    /// and checks the most recent submission's verdict. Stops when the verdict
    /// is no longer `"In judge queue"` or when `max_duration_secs` elapses.
    ///
    /// # Arguments
    ///
    /// * `max_duration_secs` — Maximum number of seconds to poll before
    ///   timing out. Pass `0` to use the default (120 seconds).
    ///
    /// # Errors
    ///
    /// Returns [`ClientError::PollingTimeout`] if the verdict does not resolve
    /// within the time limit.
    pub async fn poll_verdict(&self, max_duration_secs: u64) -> Result<Verdict, ClientError> {
        let timeout = if max_duration_secs == 0 {
            DEFAULT_POLL_TIMEOUT
        } else {
            max_duration_secs
        };

        if self.verbose {
            eprintln!(
                "[verbose] Polling status page (timeout={}s, interval={}s)",
                timeout, POLL_INTERVAL_SECS
            );
        }

        let start = std::time::Instant::now();

        loop {
            let elapsed_secs = start.elapsed().as_secs();
            if elapsed_secs >= timeout {
                return Err(ClientError::PollingTimeout(timeout));
            }

            // Sleep between polls. On the first iteration we sleep immediately
            // because the judge typically needs at least a second to enqueue.
            tokio::time::sleep(std::time::Duration::from_secs(POLL_INTERVAL_SECS)).await;

            if self.verbose {
                eprintln!(
                    "[verbose] Polling attempt (elapsed={}s)",
                    start.elapsed().as_secs()
                );
            }

            let status_resp = self
                .client
                .get(STATUS_URL)
                .header("Accept-Language", ACCEPT_LANGUAGE)
                .send()
                .await?;

            let status_html = status_resp.text().await?;

            let verdict = parser::parse_latest_verdict(&status_html).map_err(|e| {
                ClientError::ParseError(format!("Failed to parse status page during polling: {e}"))
            })?;

            if self.verbose {
                eprintln!(
                    "[verbose] Verdict: \"{}\" (run_id: {})",
                    verdict.verdict, verdict.run_id
                );
            }

            // Stop when the verdict is no longer "In judge queue".
            if !verdict.verdict.eq_ignore_ascii_case("In judge queue") {
                return Ok(verdict);
            }
        }
    }

    /// Look up a UVA username and return the numeric user ID via the uHunt API.
    ///
    /// # Endpoint
    ///
    /// `GET https://uhunt.onlinejudge.org/api/uname2uid/{username}`
    ///
    /// Returns a plain-text integer (0 if the user is not found).
    ///
    /// # Errors
    ///
    /// Returns an error on network failure or if the response cannot be parsed
    /// as a `u32`.
    pub async fn get_uhunt_user_id(username: &str) -> Result<u32, ClientError> {
        let url = format!("{UHUNT_BASE}/uname2uid/{username}");

        let resp = Client::new()
            .get(&url)
            .header("User-Agent", USER_AGENT)
            .send()
            .await?;

        let text = resp.text().await?.trim().to_string();

        text.parse::<u32>().map_err(|e| {
            ClientError::ParseError(format!(
                "Failed to parse user ID from uHunt response \"{text}\": {e}"
            ))
        })
    }

    /// Fetch the most recent submissions for a user via the uHunt API.
    ///
    /// # Endpoint
    ///
    /// `GET https://uhunt.onlinejudge.org/api/subs-user-last/{user_id}/{count}`
    ///
    /// Returns a JSON array of submission records.
    ///
    /// # Arguments
    ///
    /// * `user_id` — Numeric user ID (obtain via [`get_uhunt_user_id`]).
    /// * `count` — Number of recent submissions to retrieve.
    ///
    /// # Errors
    ///
    /// Returns an error on network failure or JSON deserialization failure.
    pub async fn get_uhunt_recent_submissions(
        user_id: u32,
        count: u32,
    ) -> Result<Vec<UhuntSubmission>, ClientError> {
        let url = format!("{UHUNT_BASE}/subs-user-last/{user_id}/{count}");

        let resp = Client::new()
            .get(&url)
            .header("User-Agent", USER_AGENT)
            .send()
            .await?;

        let submissions: Vec<UhuntSubmission> = resp.json().await?;

        Ok(submissions)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn submission_result_fields() {
        let result = SubmissionResult {
            run_id: "29964933".to_string(),
            initial_verdict: "In judge queue".to_string(),
        };
        assert_eq!(result.run_id, "29964933");
        assert_eq!(result.initial_verdict, "In judge queue");
    }

    #[test]
    fn client_error_display() {
        let err = ClientError::LoginFailed("bad creds".into());
        assert!(err.to_string().contains("bad creds"));

        let err = ClientError::PollingTimeout(120);
        assert!(err.to_string().contains("120"));

        let err = ClientError::ParseError("malformed HTML".into());
        assert!(err.to_string().contains("malformed HTML"));
    }

    #[test]
    fn uhunt_submission_deserialization() {
        let json = r#"{
            "run": 12345678,
            "probid": 100,
            "ver": 90,
            "pte": 140,
            "lang": "C++11",
            "out": "2024-11-15 07:56:25"
        }"#;

        let sub: UhuntSubmission = serde_json::from_str(json).unwrap();
        assert_eq!(sub.run_id, 12345678);
        assert_eq!(sub.problem_id, 100);
        assert_eq!(sub.verdict_code, 90);
        assert_eq!(sub.runtime, 140);
        assert_eq!(sub.language, "C++11");
        assert_eq!(sub.date, "2024-11-15 07:56:25");
    }

    #[test]
    fn client_error_from_reqwest() {
        // Verify the From<reqwest::Error> conversion works by triggering a
        // real network error (connection refused on loopback).
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let result = rt.block_on(async {
            let client = reqwest::Client::builder()
                .timeout(std::time::Duration::from_millis(100))
                .build()
                .unwrap();
            // Port 1 on localhost is almost certainly not listening
            client.get("http://127.0.0.1:1/does-not-exist").send().await
        });
        let reqwest_err = result.unwrap_err();
        let client_err: ClientError = reqwest_err.into();
        assert!(matches!(client_err, ClientError::NetworkError(_)));
    }
}