Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c155d2b

Browse files
committed
feat: Rename
1 parent 87e3cbb commit c155d2b

File tree

14 files changed

+116
-252
lines changed

14 files changed

+116
-252
lines changed

‎Cargo.toml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "leetcoderustapi"
3-
version = "0.1.2"
3+
version = "0.1.3"
44
authors = ["Kirill Melkozerov <k.melkozerov@gmail.com>"]
55
edition = "2021"
66
license = "MIT"
@@ -22,4 +22,4 @@ path = "src/lib.rs"
2222
reqwest = { version = "0.11.18", features = ["json"] }
2323
serde = { version = "1.0.164", features = ["derive"] }
2424
serde_json = "1.0.99"
25-
tokio = { version = "1.29.1", features = ["time"] }
25+
tokio = { version = "1.29.1", features = ["time"] }

‎README.md

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ This Rust library provides a convenient way to interact with the LeetCode API, a
1111
Add the following line to your `Cargo.toml` file:
1212
```toml
1313
[dependencies]
14-
leetcode-api = "0.1.2"
14+
leetcode-api = "0.1.3"
1515
```
1616
## Usage
1717
### Authentication
@@ -30,11 +30,11 @@ async fn main() {
3030
let api = UserApi::new(&token).await.unwrap();
3131

3232
// Show found problems by keyword and show 5 notes
33-
let show_problems = api.show_tasks_list("sum", 5).await.unwrap();
33+
let show_problems = api.show_problm_list("sum", 5).await.unwrap();
3434

35-
// Find problems by properties with creating builder
36-
let show_problems_builder = api
37-
.show_task_builder()
35+
// Find problems by properties with creating problem builder
36+
let problems_builder = api
37+
.problem_builder()
3838
.set_category(leetcoderustapi::Category::Algorithms)
3939
.set_difficulty(leetcoderustapi::Difficulty::Easy)
4040
.set_keyword("sum")
@@ -51,13 +51,14 @@ async fn main() {
5151
.unwrap();
5252

5353
// Fetch the full data for a specific problem
54-
let problem_info = api.set_task("two sum").await.unwrap();
55-
54+
let problem_info = api.set_problm("two sum").await.unwrap();
55+
// Retrieve previous submissions to this problem
56+
let my_submissions = problem_info.my_submissions().await.unwrap();
5657
// Retrieve code snippets
57-
let code_snippets = problem_info.code_snippets();
58+
let code_snippets = problem_info.code_snippets().unwrap();
5859

5960
// Retrieve solution info
60-
let solution_info = problem_info.solution_info();
61+
let solution_info = problem_info.solution_info().unwrap();
6162

6263
// Retrieve related topics
6364
let related_topics = problem_info.related_topics();

‎src/lib.rs

Lines changed: 23 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
use std::error::Error;
22

3+
use problem_actions::Problem;
4+
use problem_build::{Filters, TaskBuilder};
35
use reqwest::header::{HeaderMap, HeaderValue};
46
use serde_json::{json, Value};
5-
use source::{cookie::CookieData, descr::TaskData, taskfulldata::TaskFullData};
6-
use task_actions::Task;
7-
use task_build::{Filters, TaskBuilder};
7+
use resources::{cookie::CookieData, descr::ProblemData, problemfulldata::ProblemFullData};
88

9-
pub mod source;
10-
pub mod task_actions;
11-
pub mod task_build;
9+
pub mod problem_actions;
10+
pub mod problem_build;
11+
pub mod resources;
1212

1313
pub struct UserApi {
1414
client: reqwest::Client,
@@ -70,76 +70,11 @@ impl UserApi {
7070

7171
let query = r#"
7272
query globalData {
73-
feature {
74-
questionTranslation
75-
subscription
76-
signUp
77-
discuss
78-
mockInterview
79-
contest
80-
store
81-
chinaProblemDiscuss
82-
socialProviders
83-
studentFooter
84-
enableChannels
85-
dangerZone
86-
enableSharedWorker
87-
enableRecaptchaV3
88-
enableDebugger
89-
enableDebuggerPremium
90-
enableAutocomplete
91-
enableAutocompletePremium
92-
enableAllQuestionsRaw
93-
autocompleteLanguages
94-
enableIndiaPricing
95-
enableReferralDiscount
96-
maxTimeTravelTicketCount
97-
enableStoreShippingForm
98-
enableCodingChallengeV2
99-
__typename
100-
}
101-
streakCounter {
102-
streakCount
103-
daysSkipped
104-
currentDayCompleted
105-
__typename
106-
}
107-
currentTimestamp
10873
userStatus {
10974
isSignedIn
110-
isAdmin
111-
isStaff
112-
isSuperuser
113-
isMockUser
114-
isTranslator
115-
isPremium
116-
isVerified
117-
checkedInToday
118-
username
119-
realName
120-
avatar
121-
optedIn
122-
requestRegion
123-
region
124-
activeSessionId
125-
permissions
126-
notificationStatus {
127-
lastModified
128-
numUnread
129-
__typename
130-
}
131-
completedFeatureGuides
132-
__typename
13375
}
134-
siteRegion
135-
chinaHost
136-
websocketUrl
137-
recaptchaKey
138-
recaptchaKeyV2
139-
sitewideAnnouncement
140-
userCountryCode
14176
}
142-
"#;
77+
"#;
14378

14479
let json_data = json!({
14580
"operationName": operation_name,
@@ -161,10 +96,7 @@ impl UserApi {
16196
.text()
16297
.await
16398
{
164-
Ok(data) => {
165-
// println!("{}", data);
166-
data
167-
},
99+
Ok(data) => data,
168100
Err(_err) => return Err("Can't take cookie info".into()),
169101
};
170102

@@ -173,31 +105,30 @@ impl UserApi {
173105
.userStatus
174106
.isSignedIn
175107
{
176-
println!("work");
177108
return Ok((true, String::from(token)));
178109
}
179110

180111
Ok((false, String::from(token)))
181112
}
182113

183-
pub async fn set_task(&self, task: &str) -> Result<Task, Box<dyn Error>> {
184-
let info = Self::get_full_data(
114+
pub async fn set_problm(&self, task: &str) -> Result<Problem, Box<dyn Error>> {
115+
let info = Self::fetch_full_data(
185116
&self,
186117
Self::get_question_name(&self, String::from(task)).await?,
187118
)
188119
.await?;
189120

190-
Ok(Task {
121+
Ok(Problem {
191122
client: self.client.clone(),
192123
task_search_name: info.0,
193124
full_data: info.1,
194125
})
195126
}
196127

197-
async fn get_full_data(
128+
async fn fetch_full_data(
198129
&self,
199130
task_name: String,
200-
) -> Result<(String, TaskFullData), Box<dyn Error>> {
131+
) -> Result<(String, ProblemFullData), Box<dyn Error>> {
201132
let json_obj = json!({
202133
"operationName": "questionData",
203134
"variables": {
@@ -215,7 +146,7 @@ impl UserApi {
215146
.send()
216147
.await
217148
.unwrap()
218-
.json::<TaskFullData>()
149+
.json::<ProblemFullData>()
219150
.await
220151
{
221152
Ok(data) => data,
@@ -225,11 +156,11 @@ impl UserApi {
225156
Ok((full_data.data.question.titleSlug.clone(), full_data))
226157
}
227158

228-
pub async fn show_tasks_list(
159+
pub async fn show_problm_list(
229160
&self,
230161
key_word: &str,
231162
limit: u32,
232-
) -> Result<TaskData, Box<dyn Error>> {
163+
) -> Result<ProblemData, Box<dyn Error>> {
233164
let query = json!({
234165
"query": "query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) { problemsetQuestionList: questionList( categorySlug: $categorySlug limit: $limit skip: $skip filters: $filters ) { total: totalNum questions: data { acRate difficulty freqBar frontendQuestionId: questionFrontendId isFavor paidOnly: isPaidOnly status title titleSlug topicTags { name id slug } hasSolution hasVideoSolution } } }",
235166
"variables": {
@@ -259,10 +190,10 @@ impl UserApi {
259190
return Err("Problem does not found".into());
260191
}
261192

262-
Ok(serde_json::from_str::<TaskData>(&task_info.unwrap())?)
193+
Ok(serde_json::from_str::<ProblemData>(&task_info.unwrap())?)
263194
}
264195

265-
pub fn show_task_builder(&self) -> TaskBuilder {
196+
pub fn problem_builder(&self) -> TaskBuilder {
266197
TaskBuilder {
267198
client: self.client.clone(),
268199
key_word: String::new(),
@@ -274,7 +205,7 @@ impl UserApi {
274205

275206
async fn get_question_name(&self, name: String) -> Result<String, Box<dyn Error>> {
276207
let query = json!({
277-
"query": "query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) { problemsetQuestionList: questionList( categorySlug: $categorySlug limit: $limit skip: $skip filters: $filters ) { total: totalNum questions: data { acRate difficulty freqBar frontendQuestionId: questionFrontendId isFavor paidOnly: isPaidOnly status title titleSlug topicTags { name id slug } hasSolution hasVideoSolution } } }",
208+
"query": "query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) { problemsetQuestionList: questionList( categorySlug: $categorySlug limit: $limit skip: $skip filters: $filters ) { questions: data { titleSlug } } }",
278209
"variables": {
279210
"categorySlug": "",
280211
"skip": 0,
@@ -302,14 +233,15 @@ impl UserApi {
302233
return Err("Task does not found".into());
303234
}
304235

305-
let parsed_data: TaskData = serde_json::from_str(&task_info.unwrap())?;
236+
let parsed_data: ProblemData = serde_json::from_str(&task_info.unwrap())?;
306237

307238
Ok(parsed_data.data.problemsetQuestionList.questions[0]
308239
.titleSlug
309240
.clone())
310241
}
311242
}
312243

244+
#[derive(Debug)]
313245
#[allow(unused)]
314246
pub enum Category {
315247
AllTopics,
@@ -320,13 +252,15 @@ pub enum Category {
320252
Concurrency,
321253
}
322254

255+
#[derive(Debug)]
323256
#[allow(unused)]
324257
pub enum Difficulty {
325258
Easy,
326259
Medium,
327260
Hard,
328261
}
329262

263+
#[derive(Debug)]
330264
#[allow(unused)]
331265
pub enum Status {
332266
Todo,

‎src/task_actions.rs renamed to ‎src/problem_actions.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,23 @@ use std::{error::Error, time::Duration};
22

33
use serde_json::json;
44

5-
use crate::source::{
5+
use crate::resources::{
6+
problemfulldata::{CodeSnippetNode, ProblemFullData, Solution, TopicTagNode, Statistics, SimilarQuestions},
67
subm_send::{SubmExecutionResult, SubmissionCase, SubmissionCaseResp},
78
subm_show::SubmList,
8-
taskfulldata::{CodeSnippetNode, Solution, TaskFullData, TopicTagNode},
99
test_send::{TestCase, TestCaseResp, TestExecutionResult},
1010
Descryption, Rate,
1111
};
1212

1313
#[derive(Debug)]
14-
pub struct Task {
14+
pub struct Problem {
1515
pub client: reqwest::Client,
1616
pub task_search_name: String,
17-
pub full_data: TaskFullData,
17+
pub full_data: ProblemFullData,
1818
}
1919

2020
#[allow(unused)]
21-
impl Task {
21+
impl Problem {
2222
pub async fn send_test(
2323
&self,
2424
lang: &str,
@@ -128,11 +128,11 @@ impl Task {
128128
self.full_data.data.question.topicTags.clone()
129129
}
130130

131-
pub fn similar_questions(&self) -> String {
132-
self.full_data.data.question.similarQuestions.clone()
131+
pub fn similar_questions(&self) -> Vec<SimilarQuestions> {
132+
serde_json::from_str::<Vec<SimilarQuestions>>(self.full_data.data.question.similarQuestions.as_str()).unwrap()
133133
}
134-
pub fn stats(&self) -> String {
135-
self.full_data.data.question.stats.clone()
134+
pub fn stats(&self) -> Statistics {
135+
serde_json::from_str::<Statistics>(self.full_data.data.question.stats.as_str()).unwrap()
136136
}
137137

138138
pub fn hints(&self) -> Vec<String> {
@@ -164,7 +164,7 @@ impl Task {
164164
self.full_data.data.question.categoryTitle.clone()
165165
}
166166

167-
pub async fn submissions(&self) -> Result<SubmList, Box<dyn Error>> {
167+
pub async fn my_submissions(&self) -> Result<SubmList, Box<dyn Error>> {
168168
let query = json!({
169169
"operationName": "Submissions",
170170
"variables": {

‎src/task_build.rs renamed to ‎src/problem_build.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::error::Error;
33
use serde::Deserialize;
44
use serde_json::json;
55

6-
use crate::{source::descr::TaskData, Category, Difficulty, Status, Tags};
6+
use crate::{resources::descr::ProblemData, Category, Difficulty, Status, Tags};
77

88
#[derive(Debug)]
99
pub struct TaskBuilder {
@@ -164,7 +164,7 @@ impl TaskBuilder {
164164
self
165165
}
166166

167-
pub async fn build(self) -> Result<TaskData, Box<dyn Error>> {
167+
pub async fn build(self) -> Result<ProblemData, Box<dyn Error>> {
168168
let mut filters = json!({
169169
"orderBy": self.filters.orderBy,
170170
"sortOrder": self.filters.sortOrder,
@@ -242,6 +242,6 @@ impl TaskBuilder {
242242
return Err("Task does not found or Incorrect query".into());
243243
}
244244

245-
Ok(serde_json::from_str::<TaskData>(&task_info.unwrap())?)
245+
Ok(serde_json::from_str::<ProblemData>(&task_info.unwrap())?)
246246
}
247247
}

‎src/resources/cookie.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
use serde::Deserialize;
2+
3+
#[allow(non_snake_case)]
4+
#[derive(Debug, Deserialize)]
5+
pub struct QueryResponse {
6+
pub userStatus: UserStatus,
7+
}
8+
9+
#[allow(non_snake_case)]
10+
#[derive(Debug, Deserialize)]
11+
pub struct UserStatus {
12+
pub isSignedIn: bool,
13+
}
14+
15+
#[allow(non_snake_case)]
16+
#[derive(Debug, Deserialize)]
17+
pub struct GlobalData {
18+
pub userStatus: UserStatus,
19+
}
20+
21+
#[derive(Debug, Deserialize)]
22+
pub struct CookieData {
23+
pub data: GlobalData,
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /