1use std::sync::Arc;
2use std::time::Duration;
3
4use reqwest::{Client, Method, Proxy, Response, StatusCode, redirect::Policy};
5use serde::Serialize;
6use serde::de::DeserializeOwned;
7use serde_json::Value;
8use tokio::time::sleep;
9
10use super::{Config, USER_AGENT};
11use crate::ids::ApiKey;
12use crate::model::misc::LoginData;
13use crate::utils::error::Error;
14use crate::utils::{HttpProxyConfig, build_http_path};
15
16const VISITOR_VERIFY_MESSAGE: &str = "当前网络触发摸鱼派访客验证,请完成验证后再重试";
17
18struct Inner {
19 http: Client,
20 config: Config,
21 api_key: ApiKey,
22 page_auth: tokio::sync::OnceCell<PageAuth>,
23}
24
25#[derive(Clone)]
27pub struct FishPi {
28 inner: Arc<Inner>,
29}
30
31impl FishPi {
32 pub fn builder() -> FishPiBuilder {
34 FishPiBuilder::default()
35 }
36
37 pub fn api_key(&self) -> &ApiKey {
39 &self.inner.api_key
40 }
41
42 pub(crate) fn domain(&self) -> &str {
44 &self.inner.config.domain
45 }
46
47 pub(crate) fn client_tag(&self) -> &str {
49 &self.inner.config.client_tag
50 }
51
52 pub fn is_authenticated(&self) -> bool {
54 !self.inner.api_key.is_empty()
55 }
56
57 pub fn with_api_key(&self, api_key: impl Into<ApiKey>) -> Self {
59 Self {
60 inner: Arc::new(Inner {
61 http: self.inner.http.clone(),
62 config: self.inner.config.clone(),
63 api_key: api_key.into(),
64 page_auth: tokio::sync::OnceCell::new(),
65 }),
66 }
67 }
68
69 pub fn with_client_tag(&self, client_tag: impl Into<String>) -> Self {
71 let mut config = self.inner.config.clone();
72 config.client_tag = client_tag.into();
73 Self {
74 inner: Arc::new(Inner {
75 http: self.inner.http.clone(),
76 config,
77 api_key: self.inner.api_key.clone(),
78 page_auth: tokio::sync::OnceCell::new(),
79 }),
80 }
81 }
82}
83
84#[derive(Default)]
86pub struct FishPiBuilder {
87 api_key: Option<ApiKey>,
88 domain: Option<String>,
89 connect_timeout: Option<Duration>,
90 timeout: Option<Duration>,
91 proxy: Option<HttpProxyConfig>,
92 max_retries: Option<u32>,
93 client_tag: Option<String>,
94}
95
96impl FishPiBuilder {
97 pub fn api_key(mut self, api_key: impl Into<ApiKey>) -> Self {
99 self.api_key = Some(api_key.into());
100 self
101 }
102
103 pub fn domain(mut self, domain: impl Into<String>) -> Self {
105 self.domain = Some(domain.into());
106 self
107 }
108
109 pub fn connect_timeout(mut self, d: Duration) -> Self {
111 self.connect_timeout = Some(d);
112 self
113 }
114
115 pub fn timeout(mut self, d: Duration) -> Self {
117 self.timeout = Some(d);
118 self
119 }
120
121 pub fn proxy(mut self, proxy: HttpProxyConfig) -> Self {
123 self.proxy = Some(proxy);
124 self
125 }
126
127 pub fn max_retries(mut self, n: u32) -> Self {
129 self.max_retries = Some(n);
130 self
131 }
132
133 pub fn client_tag(mut self, tag: impl Into<String>) -> Self {
135 self.client_tag = Some(tag.into());
136 self
137 }
138
139 pub fn build(self) -> Result<FishPi, Error> {
141 let mut config = Config::default();
142 if let Some(d) = self.domain {
143 config.domain = d;
144 }
145 if let Some(t) = self.client_tag {
146 config.client_tag = t;
147 }
148 if let Some(t) = self.connect_timeout {
149 config.connect_timeout = t;
150 }
151 if let Some(t) = self.timeout {
152 config.timeout = t;
153 }
154 if let Some(p) = self.proxy {
155 config.proxy = p;
156 }
157 if let Some(n) = self.max_retries {
158 config.max_retries = n;
159 }
160
161 let http = build_http_client(&config)?;
162 Ok(FishPi {
163 inner: Arc::new(Inner {
164 http,
165 config,
166 api_key: self.api_key.unwrap_or_else(|| ApiKey::new("")),
167 page_auth: tokio::sync::OnceCell::new(),
168 }),
169 })
170 }
171
172 pub async fn login(self, data: &LoginData) -> Result<FishPi, Error> {
174 self.build()?.login(data).await
175 }
176}
177
178fn build_http_client(config: &Config) -> Result<Client, Error> {
179 let builder = Client::builder();
180 build_http_client_from_builder(config, builder)
181}
182
183fn build_http_client_without_redirects(config: &Config) -> Result<Client, Error> {
184 let builder = Client::builder().redirect(Policy::none());
185 build_http_client_from_builder(config, builder)
186}
187
188fn build_http_client_from_builder(
189 config: &Config,
190 builder: reqwest::ClientBuilder,
191) -> Result<Client, Error> {
192 let builder = match config.proxy.mode {
193 crate::utils::HttpProxyMode::NoProxy => builder.no_proxy(),
194 crate::utils::HttpProxyMode::System => builder,
195 crate::utils::HttpProxyMode::Custom => {
196 let proxy_url = config
197 .proxy
198 .proxy_url
199 .as_deref()
200 .map(str::trim)
201 .filter(|v| !v.is_empty())
202 .ok_or_else(|| Error::decode("proxy url is empty"))?;
203 builder.no_proxy().proxy(Proxy::all(proxy_url)?)
204 }
205 };
206
207 builder
208 .connect_timeout(config.connect_timeout)
209 .timeout(config.timeout)
210 .build()
211 .map_err(Error::from)
212}
213
214impl FishPi {
215 fn full_url(&self, path: &str) -> String {
216 format!(
217 "https://{}/{}",
218 self.inner.config.domain,
219 path.trim_start_matches('/')
220 )
221 }
222
223 pub(crate) fn with_key(&self, path: &str) -> String {
225 build_http_path(path, &[("apiKey", self.inner.api_key.to_string())])
226 }
227
228 pub(crate) async fn send_raw(
230 &self,
231 method: Method,
232 path: &str,
233 body: Option<&Value>,
234 ) -> Result<Value, Error> {
235 let url = self.full_url(path);
236 let max_retries = self.inner.config.max_retries;
237 let mut attempt = 0;
238
239 loop {
240 let mut req = self
241 .inner
242 .http
243 .request(method.clone(), &url)
244 .header("User-Agent", USER_AGENT)
245 .header("Referer", format!("https://{}/", self.inner.config.domain));
246 if let Some(b) = body {
247 req = req.json(b);
248 }
249
250 let resp = match req.send().await {
251 Ok(resp) => resp,
252 Err(err) => {
253 if attempt < max_retries {
254 sleep(backoff(attempt)).await;
255 attempt += 1;
256 continue;
257 }
258 return Err(Error::from(err));
259 }
260 };
261
262 let status = resp.status();
263 if status.is_success() {
264 return parse_json_response(resp).await;
265 }
266
267 match status {
268 StatusCode::UNAUTHORIZED => return Err(Error::Unauthorized),
269 StatusCode::NOT_FOUND => {
270 return Err(Error::NotFound {
271 resource: path.to_string(),
272 });
273 }
274 StatusCode::TOO_MANY_REQUESTS => {
275 return Err(Error::RateLimited {
276 retry_after: retry_after(&resp),
277 });
278 }
279 StatusCode::SERVICE_UNAVAILABLE if attempt < max_retries => {
280 sleep(backoff(attempt)).await;
281 attempt += 1;
282 continue;
283 }
284 _ => {
285 return Err(Error::decode(format!("HTTP error: {}", status)));
286 }
287 }
288 }
289 }
290}
291
292fn backoff(attempt: u32) -> Duration {
293 Duration::from_millis(300 * (attempt as u64 + 1))
294}
295
296fn retry_after(resp: &Response) -> Option<Duration> {
297 resp.headers()
298 .get(reqwest::header::RETRY_AFTER)
299 .and_then(|v| v.to_str().ok())
300 .and_then(|s| s.trim().parse::<u64>().ok())
301 .map(Duration::from_secs)
302}
303
304fn check_envelope(value: Value) -> Result<Value, Error> {
306 let code = value.get("code").and_then(Value::as_i64);
307 match code {
308 None | Some(0) => Ok(value),
309 Some(c) => {
310 let msg = value
311 .get("msg")
312 .and_then(Value::as_str)
313 .unwrap_or("API error")
314 .to_string();
315 Err(map_business(c, msg))
316 }
317 }
318}
319
320fn map_business(code: i64, msg: String) -> Error {
321 match code {
322 -1 if msg.contains("Auth") || msg.contains("登录") || msg.contains("认证") => {
323 Error::Unauthorized
324 }
325 _ => Error::business(code, msg),
326 }
327}
328
329impl FishPi {
330 pub(crate) async fn get_data<T: DeserializeOwned>(&self, path: &str) -> Result<T, Error> {
332 let value = self.send_raw(Method::GET, path, None).await?;
333 let value = check_envelope(value)?;
334 take_data(value)
335 }
336
337 pub(crate) async fn get_data_with_key<T: DeserializeOwned>(
339 &self,
340 path: &str,
341 ) -> Result<T, Error> {
342 let mut body = Value::Object(Default::default());
343 self.inject_api_key(&mut body);
344 let value = self.send_raw(Method::GET, path, Some(&body)).await?;
345 let value = check_envelope(value)?;
346 take_data(value)
347 }
348
349 pub(crate) async fn post_data<T: DeserializeOwned, B: Serialize>(
351 &self,
352 path: &str,
353 body: &B,
354 ) -> Result<T, Error> {
355 let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
356 self.inject_api_key(&mut body);
357 let value = self.send_raw(Method::POST, path, Some(&body)).await?;
358 let value = check_envelope(value)?;
359 take_data(value)
360 }
361 pub(crate) async fn post_page_data<T: DeserializeOwned, B: Serialize>(
363 &self,
364 path: &str,
365 body: &B,
366 ) -> Result<T, Error> {
367 let body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
368 let url = self.full_url(path);
369 let page_auth = self.page_auth().await?;
370 let resp = self
371 .inner
372 .http
373 .post(&url)
374 .header("User-Agent", USER_AGENT)
375 .header(
376 "Referer",
377 format!("https://{}/settings/profession", self.inner.config.domain),
378 )
379 .header("Cookie", page_auth.cookie_header())
380 .header("csrfToken", page_auth.csrf_token)
381 .json(&body)
382 .send()
383 .await?;
384 let value = parse_json_response(resp).await?;
385 let value = check_envelope(value)?;
386 take_data(value)
387 }
388 pub(crate) async fn get_raw(&self, path: &str) -> Result<Value, Error> {
390 let value = self.send_raw(Method::GET, path, None).await?;
391 check_envelope(value)
392 }
393
394 pub(crate) async fn post_raw<B: Serialize>(
396 &self,
397 path: &str,
398 body: &B,
399 ) -> Result<Value, Error> {
400 let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
401 self.inject_api_key(&mut body);
402 let value = self.send_raw(Method::POST, path, Some(&body)).await?;
403 check_envelope(value)
404 }
405
406 pub(crate) async fn put_raw<B: Serialize>(&self, path: &str, body: &B) -> Result<Value, Error> {
408 let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
409 self.inject_api_key(&mut body);
410 let value = self.send_raw(Method::PUT, path, Some(&body)).await?;
411 check_envelope(value)
412 }
413
414 pub(crate) async fn delete_raw<B: Serialize>(
416 &self,
417 path: &str,
418 body: &B,
419 ) -> Result<Value, Error> {
420 let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
421 self.inject_api_key(&mut body);
422 let value = self.send_raw(Method::DELETE, path, Some(&body)).await?;
423 check_envelope(value)
424 }
425
426 pub(crate) async fn get_text(&self, path: &str) -> Result<String, Error> {
428 self.get_text_with_cookie(path, None).await
429 }
430
431 async fn get_text_with_cookie(
432 &self,
433 path: &str,
434 cookie: Option<String>,
435 ) -> Result<String, Error> {
436 let url = self.full_url(path);
437 let mut req = self
438 .inner
439 .http
440 .get(&url)
441 .header("User-Agent", USER_AGENT)
442 .header("Referer", format!("https://{}/", self.inner.config.domain));
443 if let Some(cookie) = cookie {
444 req = req.header("Cookie", cookie);
445 }
446 let resp = req.send().await?;
447 let status = resp.status();
448 if !status.is_success() {
449 return Err(Error::decode(format!("HTTP error: {}", status)));
450 }
451 resp.text().await.map_err(Error::from)
452 }
453
454 fn inject_api_key(&self, body: &mut Value) {
456 if self.inner.api_key.is_empty() {
457 return;
458 }
459 if let Value::Object(map) = body
460 && !map.contains_key("apiKey")
461 {
462 map.insert(
463 "apiKey".to_string(),
464 Value::String(self.inner.api_key.to_string()),
465 );
466 }
467 }
468
469 async fn page_auth(&self) -> Result<PageAuth, Error> {
470 let page_auth = self
471 .inner
472 .page_auth
473 .get_or_try_init(|| async {
474 let sym_ce = self.exchange_page_token().await?;
475 if sym_ce.is_empty() {
476 return Err(Error::Unauthorized);
477 }
478 let html = self
479 .get_text_with_cookie("settings/profession", Some(format!("sym-ce={sym_ce}")))
480 .await?;
481 let csrf_token = extract_csrf_token(&html)
482 .filter(|token| !token.trim().is_empty())
483 .ok_or_else(|| Error::decode("cannot parse csrfToken from settings page"))?;
484 Ok(PageAuth { sym_ce, csrf_token })
485 })
486 .await?;
487 Ok(page_auth.clone())
488 }
489
490 async fn exchange_page_token(&self) -> Result<String, Error> {
491 if self.inner.api_key.is_empty() {
492 return Err(Error::Unauthorized);
493 }
494 let path = build_http_path(
495 "loginWebInApiKey",
496 &[("apiKey", self.inner.api_key.to_string())],
497 );
498 let url = self.full_url(&path);
499 let http = build_http_client_without_redirects(&self.inner.config)?;
500 let resp = http
501 .get(&url)
502 .header("User-Agent", USER_AGENT)
503 .header(
504 "Referer",
505 format!("https://{}/login", self.inner.config.domain),
506 )
507 .send()
508 .await?;
509 response_cookie_value(&resp, "sym-ce")
510 .ok_or_else(|| Error::decode("cannot exchange apiKey for page sym-ce cookie"))
511 }
512}
513
514fn take_data<T: DeserializeOwned>(mut value: Value) -> Result<T, Error> {
516 let data = match value.get_mut("data") {
517 Some(d) => d.take(),
518 None => value,
519 };
520 let data = if let Value::String(s) = &data {
521 serde_json::from_str(s).map_err(|e| Error::decode(e.to_string()))?
522 } else {
523 data
524 };
525 serde_json::from_value(data).map_err(|e| Error::decode(e.to_string()))
526}
527
528async fn parse_json_response(resp: Response) -> Result<Value, Error> {
529 let final_path = resp.url().path().to_string();
530 let content_type = resp
531 .headers()
532 .get("content-type")
533 .and_then(|v| v.to_str().ok())
534 .unwrap_or("")
535 .to_ascii_lowercase();
536 let text = resp.text().await?;
537
538 if is_visitor_verify_response(&final_path, &content_type, &text) {
539 return Err(Error::decode(VISITOR_VERIFY_MESSAGE));
540 }
541
542 serde_json::from_str::<Value>(&text).map_err(|err| {
543 if is_html_response(&content_type, &text) {
544 Error::decode("服务返回了网页内容,无法作为 API 响应解析")
545 } else {
546 Error::decode(format!("Failed to parse response body: {err}"))
547 }
548 })
549}
550
551fn is_visitor_verify_response(path: &str, content_type: &str, body: &str) -> bool {
552 let lower = body.to_ascii_lowercase();
553 path == "/test"
554 || (is_html_response(content_type, body)
555 && (body.contains("访客验证")
556 || body.contains("在继续浏览摸鱼派社区前请验证")
557 || body.contains("/validateCaptcha")
558 || lower.contains("initgeetest4")))
559}
560
561fn is_html_response(content_type: &str, body: &str) -> bool {
562 content_type.contains("text/html")
563 || body
564 .trim_start()
565 .to_ascii_lowercase()
566 .starts_with("<!doctype html")
567}
568
569#[derive(Clone)]
570struct PageAuth {
571 sym_ce: String,
572 csrf_token: String,
573}
574
575impl PageAuth {
576 fn cookie_header(&self) -> String {
577 format!("sym-ce={}", self.sym_ce)
578 }
579}
580
581fn extract_csrf_token(html: &str) -> Option<String> {
582 let key = html.find("csrfToken")?;
583 let rest = &html[key..];
584 let colon = rest.find(':')?;
585 let mut value = rest[colon + 1..].trim_start();
586 let first = value.chars().next()?;
587 if first == '\'' || first == '"' {
588 value = &value[first.len_utf8()..];
589 let end = value.find(first)?;
590 Some(value[..end].to_string())
591 } else {
592 let end = value
593 .find(|c: char| c.is_whitespace() || c == ',' || c == ';' || c == '}')
594 .unwrap_or(value.len());
595 Some(
596 value[..end]
597 .trim_matches('"')
598 .trim_matches('\'')
599 .to_string(),
600 )
601 }
602}
603
604fn response_cookie_value(resp: &Response, name: &str) -> Option<String> {
605 let prefix = format!("{name}=");
606 resp.headers()
607 .get_all(reqwest::header::SET_COOKIE)
608 .iter()
609 .filter_map(|value| value.to_str().ok())
610 .find_map(|cookie| {
611 cookie
612 .split(';')
613 .map(str::trim)
614 .find_map(|part| part.strip_prefix(&prefix).map(str::to_string))
615 })
616}
617
618impl FishPi {
619 pub async fn login(&self, data: &LoginData) -> Result<FishPi, Error> {
621 let body = data.to_value()?;
622 let rsp = self
623 .send_raw(Method::POST, "api/getKey", Some(&body))
624 .await?;
625 let rsp = check_envelope(rsp)?;
626 let api_key = rsp
627 .get("Key")
628 .and_then(Value::as_str)
629 .unwrap_or("")
630 .trim()
631 .to_string();
632 Ok(self.with_api_key(api_key))
633 }
634}