Skip to content

Commit a209efa

Browse files
committed
feat: add site config at cookies section
1 parent 78b9737 commit a209efa

File tree

9 files changed

+140
-48
lines changed

9 files changed

+140
-48
lines changed

README.md

+2-4
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
[![telegram](https://img.shields.io/badge/telegram-blue?logo=telegram)](https://t.me/+U_5si6PhWykxZTI1)
88
[![LICENSE](https://img.shields.io/crates/l/leetcode-cli.svg)](https://choosealicense.com/licenses/mit/)
99

10-
Modify for **leetcode.cn**
11-
1210
## Installing
1311

1412
```sh
@@ -45,7 +43,7 @@ If no argument is provided, the shell is inferred from the `SHELL` environment v
4543

4644
## Usage
4745

48-
**Make sure you have logged in to `leetcode.cn` with `Firefox`**. See [Cookies](#cookies) for why you need to do this first.
46+
**Make sure you have logged in to `leetcode.com` with `Firefox`**. See [Cookies](#cookies) for why you need to do this first.
4947

5048
```sh
5149
leetcode 0.4.0
@@ -309,7 +307,7 @@ Open Firefox, press F12, and click `Storage` tab.
309307

310308
#### Step 2
311309

312-
Expand `Cookies` tab on the left and select https://leetcode.cn.
310+
Expand `Cookies` tab on the left and select https://leetcode.com.
313311

314312
#### Step 2
315313

src/cache/parser.rs

+23-19
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,17 @@ pub fn problem(problems: &mut Vec<Problem>, v: Value) -> Option<()> {
1010
let total_acs = stat.get("total_acs")?.as_f64()? as f32;
1111
let total_submitted = stat.get("total_submitted")?.as_f64()? as f32;
1212

13+
let fid_obj = stat.get("frontend_question_id")?;
14+
let fid = match fid_obj.as_i64() {
15+
// Handle on leetcode-com
16+
Some(s) => s as i32,
17+
// Handle on leetcode-cn
18+
None => fid_obj.as_str()?.split(" ").last()?.parse::<i32>().ok()?,
19+
};
20+
1321
problems.push(Problem {
1422
category: v.get("category_slug")?.as_str()?.to_string(),
15-
fid: stat
16-
.get("frontend_question_id")?
17-
.as_str()?
18-
.split(" ")
19-
.last()?
20-
.parse::<i32>()
21-
.ok()?,
23+
fid: fid,
2224
id: stat.get("question_id")?.as_i64()? as i32,
2325
level: p.get("difficulty")?.as_object()?.get("level")?.as_i64()? as i32,
2426
locked: p.get("paid_only")?.as_bool()?,
@@ -95,18 +97,20 @@ pub fn tags(v: Value) -> Option<Vec<String>> {
9597
/// daily parser
9698
pub fn daily(v: Value) -> Option<i32> {
9799
trace!("Parse daily...");
98-
v.as_object()?
99-
.get("data")?
100-
.as_object()?
101-
.get("todayRecord")?
102-
.as_array()?[0]
103-
.as_object()?
104-
.get("question")?
105-
.as_object()?
106-
.get("questionFrontendId")?
107-
.as_str()?
108-
.parse()
109-
.ok()
100+
let v_obj = v.as_object()?.get("data")?.as_object()?;
101+
match v_obj.get("dailyQuestionRecord") {
102+
// Handle on leetcode-com
103+
Some(v) => v,
104+
// Handle on leetcode-cn
105+
None => v_obj.get("todayRecord")?.as_array()?.get(0)?,
106+
}
107+
.as_object()?
108+
.get("question")?
109+
.as_object()?
110+
.get("questionFrontendId")?
111+
.as_str()?
112+
.parse()
113+
.ok()
110114
}
111115

112116
/// user parser

src/config/cookies.rs

+42-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,52 @@
11
//! Cookies in config
2+
use std::str::FromStr;
3+
24
use serde::{Deserialize, Serialize};
35

6+
#[derive(Clone, Debug, Deserialize, Serialize)]
7+
pub enum LeetcodeSite {
8+
#[serde(rename = "leetcode.com")]
9+
LeetcodeCom,
10+
#[serde(rename = "leetcode.cn")]
11+
LeetcodeCn,
12+
}
13+
14+
impl FromStr for LeetcodeSite {
15+
type Err = String;
16+
fn from_str(s: &str) -> Result<Self, Self::Err> {
17+
match s {
18+
"leetcode.com" => Ok(LeetcodeSite::LeetcodeCom),
19+
"leetcode.cn" => Ok(LeetcodeSite::LeetcodeCn),
20+
_ => Err("Invalid site key".to_string()),
21+
}
22+
}
23+
}
24+
25+
impl ToString for LeetcodeSite {
26+
fn to_string(&self) -> String {
27+
match self {
28+
LeetcodeSite::LeetcodeCom => "leetcode.com".to_string(),
29+
LeetcodeSite::LeetcodeCn => "leetcode.cn".to_string(),
30+
}
31+
}
32+
}
33+
434
/// Cookies settings
5-
#[derive(Default, Clone, Debug, Deserialize, Serialize)]
35+
#[derive(Clone, Debug, Deserialize, Serialize)]
636
pub struct Cookies {
737
pub csrf: String,
838
pub session: String,
39+
pub site: LeetcodeSite,
40+
}
41+
42+
impl Default for Cookies {
43+
fn default() -> Self {
44+
Self {
45+
csrf: "".to_string(),
46+
session: "".to_string(),
47+
site: LeetcodeSite::LeetcodeCom,
48+
}
49+
}
950
}
1051

1152
impl std::string::ToString for Cookies {

src/config/mod.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ mod cookies;
1717
mod storage;
1818
mod sys;
1919

20+
pub use cookies::LeetcodeSite;
21+
2022
/// Sync with `~/.leetcode/leetcode.toml`
2123
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
2224
pub struct Config {
@@ -44,7 +46,14 @@ impl Config {
4446

4547
let s = fs::read_to_string(&conf)?;
4648
match toml::from_str::<Config>(&s) {
47-
Ok(config) => Ok(config),
49+
Ok(config) => match config.cookies.site {
50+
cookies::LeetcodeSite::LeetcodeCom => Ok(config),
51+
cookies::LeetcodeSite::LeetcodeCn => {
52+
let mut config = config;
53+
config.sys.urls = sys::Urls::new_with_leetcode_cn();
54+
Ok(config)
55+
}
56+
},
4857
Err(e) => {
4958
let tmp = Self::root()?.join("leetcode.tmp.toml");
5059
Self::write_default(tmp)?;

src/config/sys.rs

+21-2
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,27 @@ pub struct Urls {
3232

3333
impl Default for Urls {
3434
fn default() -> Self {
35+
Self {
36+
base: "https://leetcode.com".into(),
37+
graphql: "https://leetcode.com/graphql".into(),
38+
login: "https://leetcode.com/accounts/login/".into(),
39+
problems: "https://leetcode.com/api/problems/$category/".into(),
40+
problem: "https://leetcode.com/problems/$slug/description/".into(),
41+
tag: "https://leetcode.com/tag/$slug/".into(),
42+
test: "https://leetcode.com/problems/$slug/interpret_solution/".into(),
43+
session: "https://leetcode.com/session/".into(),
44+
submit: "https://leetcode.com/problems/$slug/submit/".into(),
45+
submissions: "https://leetcode.com/submissions/detail/$id/".into(),
46+
submission: "https://leetcode.com/submissions/detail/$id/".into(),
47+
verify: "https://leetcode.com/submissions/detail/$id/check/".into(),
48+
favorites: "https://leetcode.com/list/api/questions".into(),
49+
favorite_delete: "https://leetcode.com/list/api/questions/$hash/$id".into(),
50+
}
51+
}
52+
}
53+
54+
impl Urls {
55+
pub fn new_with_leetcode_cn() -> Self {
3556
Self {
3657
base: "https://leetcode.cn".into(),
3758
graphql: "https://leetcode.cn/graphql".into(),
@@ -49,9 +70,7 @@ impl Default for Urls {
4970
favorite_delete: "https://leetcode.cn/list/api/questions/$hash/$id".into(),
5071
}
5172
}
52-
}
5373

54-
impl Urls {
5574
/// problem url with specific `$slug`
5675
pub fn problem(&self, slug: &str) -> String {
5776
self.problem.replace("$slug", slug)

src/lib.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
//!
1313
//! ## Usage
1414
//!
15-
//! **Please make sure you have logined in `leetcode.cn` with `chrome`**, more info plz checkout [this](#cookies)
15+
//! **Please make sure you have logined in `leetcode.com` with `chrome`**, more info plz checkout [this](#cookies)
1616
//!
1717
//! ```sh
1818
//! leetcode 0.3.10
@@ -142,15 +142,15 @@
142142
//! session = "..."
143143
//! ```
144144
//!
145-
//! For Example, if you're using chrome to login to leetcode.cn.
145+
//! For Example, if you're using chrome to login to leetcode.com.
146146
//!
147147
//!
148148
//! #### Step 1
149149
//!
150150
//! Open chrome and paste the link below to the `chrome linkbar`.
151151
//!
152152
//! ```sh
153-
//! chrome://settings/cookies/detail?site=leetcode.cn
153+
//! chrome://settings/cookies/detail?site=leetcode.com
154154
//! ```
155155
//!
156156
//! #### Step 2

src/plugins/chrome.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ pub fn cookies() -> Result<Ident> {
6464
debug!("Chrome Cookies path is {:?}", &p);
6565
let mut conn = cache::conn(p.to_string_lossy().to_string());
6666
let res = cookies
67-
.filter(host_key.like("%leetcode.cn"))
67+
.filter(host_key.like(format!("#{}", ccfg.site.to_string())))
6868
.load::<Cookies>(&mut conn)
6969
.expect("Loading cookies from google chrome failed.");
7070

src/plugins/leetcode.rs

+36-15
Original file line numberDiff line numberDiff line change
@@ -145,21 +145,42 @@ impl LeetCode {
145145
trace!("Requesting daily problem...");
146146
let url = &self.conf.sys.urls.graphql;
147147
let mut json: Json = HashMap::new();
148-
json.insert("operationName", "questionOfToday".to_string());
149-
json.insert(
150-
"query",
151-
vec![
152-
"query questionOfToday {",
153-
" todayRecord {",
154-
" question {",
155-
" questionFrontendId",
156-
" }",
157-
" }",
158-
"}",
159-
]
160-
.join("\n"),
161-
);
162-
148+
149+
match self.conf.cookies.site {
150+
config::LeetcodeSite::LeetcodeCom => {
151+
json.insert("operationName", "daily".to_string());
152+
json.insert(
153+
"query",
154+
vec![
155+
"query daily {",
156+
" activeDailyCodingChallengeQuestion {",
157+
" question {",
158+
" questionFrontendId",
159+
" }",
160+
" }",
161+
"}",
162+
]
163+
.join("\n"),
164+
);
165+
}
166+
config::LeetcodeSite::LeetcodeCn => {
167+
json.insert("operationName", "questionOfToday".to_string());
168+
json.insert(
169+
"query",
170+
vec![
171+
"query questionOfToday {",
172+
" todayRecord {",
173+
" question {",
174+
" questionFrontendId",
175+
" }",
176+
" }",
177+
"}",
178+
]
179+
.join("\n"),
180+
);
181+
}
182+
}
183+
163184
Req {
164185
default_headers: self.default_headers,
165186
refer: None,

src/plugins/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
//! + chrome cookie parser
44
//! + leetcode API
55
//!
6-
//! ## login to `leetcode.cn`
7-
//! Leetcode-cli use chrome cookie directly, do not need to login, please make sure you have loggined in `leetcode.cn` before usnig `leetcode-cli`
6+
//! ## login to `leetcode.com`
7+
//! Leetcode-cli use chrome cookie directly, do not need to login, please make sure you have loggined in `leetcode.com` before usnig `leetcode-cli`
88
//!
99
1010
// FIXME: Read cookies from local storage. (issue #122)

0 commit comments

Comments
 (0)