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
use std::time::Duration;

use lcode_config::global::G_USER_CONFIG;
use miette::Result;
use regex::Regex;
use tokio::{join, time::sleep};
use tracing::{debug, trace};

use crate::{
    dao::{query::Query, save_info::FileInfo},
    leetcode::{
        graphqls::init_subit_list_grql,
        leetcode_send::fetch,
        resps::{
            run_res::*,
            submit_list::{SubmissionData, SubmissionList},
        },
        IdSlug, LeetCode,
    },
    Json,
};

impl LeetCode {
    /// submit code by id or slug, once submit one question
    ///
    /// * `idslug`: id or slug
    pub async fn submit_code(&self, idslug: IdSlug) -> Result<(SubmitInfo, RunResult)> {
        let (code, pb) = join!(
            self.get_user_code(idslug.clone()),
            Query::get_question_index(&idslug)
        );
        let ((code, _), pb) = (code?, pb?);

        let mut json: Json = Json::new();
        json.insert("lang", G_USER_CONFIG.config.lang.clone());
        json.insert("question_id", pb.question_id.to_string());
        json.insert("typed_code", code);

        trace!("submit insert json: {:#?}", json);

        let sub_info: SubmitInfo = match fetch(
            &self.client,
            &G_USER_CONFIG
                .urls
                .mod_submit(&pb.question_title_slug),
            Some(&json),
            self.headers.clone(),
        )
        .await
        {
            Ok(it) => it,
            Err(err) => {
                return Ok((
                    SubmitInfo::default(),
                    RunResultBuild::default()
                        .set_status_msg(err.to_string())
                        .build(),
                ));
            },
        };

        let last_sub_result = self
            .get_one_submit_res(&sub_info)
            .await?;
        debug!("last submit result: {:#?}", last_sub_result);

        Ok((sub_info, last_sub_result))
    }

    /// Get one submit info
    ///
    /// * `sub_id`: be fetch `submission_id`
    pub async fn get_one_submit_res(&self, sub_id: &SubmitInfo) -> Result<RunResult> {
        let test_res_url = G_USER_CONFIG
            .urls
            .mod_submissions(&sub_id.submission_id().to_string());
        trace!("start get last submit detail");

        for _ in 0..9 {
            sleep(Duration::from_millis(700)).await;

            let resp_json: RunResult =
                fetch(&self.client, &test_res_url, None, self.headers.clone()).await?;
            if resp_json.success() {
                return Ok(resp_json);
            }
        }
        Ok(RunResultBuild::default()
            .set_status_msg(
                "Get the submit result error, please check your code, it may fail to execute, or \
                 check your network"
                    .to_owned(),
            )
            .build())
    }

    /// Get all submission results for a question
    pub async fn all_submit_res(&self, idslug: IdSlug) -> Result<SubmissionList> {
        let pb = Query::get_question_index(&idslug).await?;

        let json: Json = init_subit_list_grql(&pb.question_title_slug);

        let pat: SubmissionData = fetch(
            &self.client,
            &G_USER_CONFIG.urls.graphql,
            Some(&json),
            self.headers.clone(),
        )
        .await?;

        Ok(pat.submission_list())
    }

    pub async fn test_code(&self, idslug: IdSlug) -> Result<(TestInfo, RunResult)> {
        let (code, pb) = join!(
            self.get_user_code(idslug.clone()),
            Query::get_question_index(&idslug)
        );
        let ((code, test_case), pb) = (code?, pb?);
        debug!("code:\n{}", code);

        let mut json: Json = Json::new();
        json.insert("lang", G_USER_CONFIG.config.lang.clone());
        json.insert("question_id", pb.question_id.to_string());
        json.insert("typed_code", code);
        json.insert("data_input", test_case);

        let test_info: TestInfo = match fetch(
            &self.client,
            &G_USER_CONFIG
                .urls
                .mod_test(&pb.question_title_slug),
            Some(&json),
            self.headers.clone(),
        )
        .await
        {
            Ok(it) => it,
            Err(err) => {
                return Ok((
                    TestInfo::default(),
                    RunResultBuild::default()
                        .set_status_msg(err.to_string())
                        .build(),
                ));
            },
        };

        let test_result = self.get_test_res(&test_info).await?;

        Ok((test_info, test_result))
    }

    /// Get the last submission results for a question
    async fn get_test_res(&self, test_info: &TestInfo) -> Result<RunResult> {
        for _ in 0..9 {
            sleep(Duration::from_millis(700)).await;

            let resp_json: RunResult = fetch(
                &self.client.clone(),
                &G_USER_CONFIG
                    .urls
                    .mod_submissions(test_info.interpret_id()),
                None,
                self.headers.clone(),
            )
            .await?;
            if resp_json.success() {
                return Ok(resp_json);
            }
        }
        Ok(RunResultBuild::default()
            .set_status_msg(
                "Get the test result error, please check your network,or check test case it may \
                 not correct"
                    .to_owned(),
            )
            .build())
    }

    /// Get user code as string(`code`, `test case`)
    pub async fn get_user_code(&self, idslug: IdSlug) -> Result<(String, String)> {
        let pb = Query::get_question_index(&idslug).await?;
        let chf = FileInfo::build(&pb).await?;
        let (code, mut test_case) = chf.get_user_code(&idslug).await?;

        if test_case.is_empty() {
            test_case = self
                .get_qs_detail(idslug, false)
                .await?
                .example_testcases;
        }
        let (start, end, ..) = G_USER_CONFIG.get_lang_info();
        let code_re = Regex::new(&format!(r"(?s){}\n(?P<code>.*){}", start, end))
            .expect("get_user_code regex new failed");

        // sep code just get needed
        #[allow(clippy::option_if_let_else)]
        let res = match code_re.captures(&code) {
            Some(val) => val["code"].to_owned(),
            None => code,
        };

        Ok((res, test_case))
    }
}