use std::sync::Arc;
use std::time::Duration;
use reqwest::{Client, Method, Proxy, Response, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio::time::sleep;
use super::{Config, USER_AGENT};
use crate::ids::ApiKey;
use crate::model::misc::LoginData;
use crate::utils::error::Error;
use crate::utils::{HttpProxyConfig, build_http_path};
const VISITOR_VERIFY_MESSAGE: &str = "当前网络触发摸鱼派访客验证,请完成验证后再重试";
struct Inner {
http: Client,
config: Config,
api_key: ApiKey,
}
#[derive(Clone)]
pub struct FishPi {
inner: Arc<Inner>,
}
impl FishPi {
pub fn builder() -> FishPiBuilder {
FishPiBuilder::default()
}
pub fn api_key(&self) -> &ApiKey {
&self.inner.api_key
}
pub(crate) fn domain(&self) -> &str {
&self.inner.config.domain
}
pub(crate) fn client_tag(&self) -> &str {
&self.inner.config.client_tag
}
pub fn is_authenticated(&self) -> bool {
!self.inner.api_key.is_empty()
}
pub fn with_api_key(&self, api_key: impl Into<ApiKey>) -> Self {
Self {
inner: Arc::new(Inner {
http: self.inner.http.clone(),
config: self.inner.config.clone(),
api_key: api_key.into(),
}),
}
}
pub fn with_client_tag(&self, client_tag: impl Into<String>) -> Self {
let mut config = self.inner.config.clone();
config.client_tag = client_tag.into();
Self {
inner: Arc::new(Inner {
http: self.inner.http.clone(),
config,
api_key: self.inner.api_key.clone(),
}),
}
}
}
#[derive(Default)]
pub struct FishPiBuilder {
api_key: Option<ApiKey>,
domain: Option<String>,
connect_timeout: Option<Duration>,
timeout: Option<Duration>,
proxy: Option<HttpProxyConfig>,
max_retries: Option<u32>,
client_tag: Option<String>,
}
impl FishPiBuilder {
pub fn api_key(mut self, api_key: impl Into<ApiKey>) -> Self {
self.api_key = Some(api_key.into());
self
}
pub fn domain(mut self, domain: impl Into<String>) -> Self {
self.domain = Some(domain.into());
self
}
pub fn connect_timeout(mut self, d: Duration) -> Self {
self.connect_timeout = Some(d);
self
}
pub fn timeout(mut self, d: Duration) -> Self {
self.timeout = Some(d);
self
}
pub fn proxy(mut self, proxy: HttpProxyConfig) -> Self {
self.proxy = Some(proxy);
self
}
pub fn max_retries(mut self, n: u32) -> Self {
self.max_retries = Some(n);
self
}
pub fn client_tag(mut self, tag: impl Into<String>) -> Self {
self.client_tag = Some(tag.into());
self
}
pub fn build(self) -> Result<FishPi, Error> {
let mut config = Config::default();
if let Some(d) = self.domain {
config.domain = d;
}
if let Some(t) = self.client_tag {
config.client_tag = t;
}
if let Some(t) = self.connect_timeout {
config.connect_timeout = t;
}
if let Some(t) = self.timeout {
config.timeout = t;
}
if let Some(p) = self.proxy {
config.proxy = p;
}
if let Some(n) = self.max_retries {
config.max_retries = n;
}
let http = build_http_client(&config)?;
Ok(FishPi {
inner: Arc::new(Inner {
http,
config,
api_key: self.api_key.unwrap_or_else(|| ApiKey::new("")),
}),
})
}
pub async fn login(self, data: &LoginData) -> Result<FishPi, Error> {
self.build()?.login(data).await
}
}
fn build_http_client(config: &Config) -> Result<Client, Error> {
let builder = Client::builder();
let builder = match config.proxy.mode {
crate::utils::HttpProxyMode::NoProxy => builder.no_proxy(),
crate::utils::HttpProxyMode::System => builder,
crate::utils::HttpProxyMode::Custom => {
let proxy_url = config
.proxy
.proxy_url
.as_deref()
.map(str::trim)
.filter(|v| !v.is_empty())
.ok_or_else(|| Error::decode("proxy url is empty"))?;
builder.no_proxy().proxy(Proxy::all(proxy_url)?)
}
};
builder
.connect_timeout(config.connect_timeout)
.timeout(config.timeout)
.build()
.map_err(Error::from)
}
impl FishPi {
fn full_url(&self, path: &str) -> String {
format!(
"https://{}/{}",
self.inner.config.domain,
path.trim_start_matches('/')
)
}
pub(crate) fn with_key(&self, path: &str) -> String {
build_http_path(path, &[("apiKey", self.inner.api_key.to_string())])
}
pub(crate) async fn send_raw(
&self,
method: Method,
path: &str,
body: Option<&Value>,
) -> Result<Value, Error> {
let url = self.full_url(path);
let max_retries = self.inner.config.max_retries;
let mut attempt = 0;
loop {
let mut req = self
.inner
.http
.request(method.clone(), &url)
.header("User-Agent", USER_AGENT)
.header("Referer", format!("https://{}/", self.inner.config.domain));
if let Some(b) = body {
req = req.json(b);
}
let resp = match req.send().await {
Ok(resp) => resp,
Err(err) => {
if attempt < max_retries {
sleep(backoff(attempt)).await;
attempt += 1;
continue;
}
return Err(Error::from(err));
}
};
let status = resp.status();
if status.is_success() {
return parse_json_response(resp).await;
}
match status {
StatusCode::UNAUTHORIZED => return Err(Error::Unauthorized),
StatusCode::NOT_FOUND => {
return Err(Error::NotFound {
resource: path.to_string(),
});
}
StatusCode::TOO_MANY_REQUESTS => {
return Err(Error::RateLimited {
retry_after: retry_after(&resp),
});
}
StatusCode::SERVICE_UNAVAILABLE if attempt < max_retries => {
sleep(backoff(attempt)).await;
attempt += 1;
continue;
}
_ => {
return Err(Error::decode(format!("HTTP error: {}", status)));
}
}
}
}
}
fn backoff(attempt: u32) -> Duration {
Duration::from_millis(300 * (attempt as u64 + 1))
}
fn retry_after(resp: &Response) -> Option<Duration> {
resp.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok())
.map(Duration::from_secs)
}
fn check_envelope(value: Value) -> Result<Value, Error> {
let code = value.get("code").and_then(Value::as_i64);
match code {
None | Some(0) => Ok(value),
Some(c) => {
let msg = value
.get("msg")
.and_then(Value::as_str)
.unwrap_or("API error")
.to_string();
Err(map_business(c, msg))
}
}
}
fn map_business(code: i64, msg: String) -> Error {
match code {
-1 if msg.contains("Auth") || msg.contains("登录") || msg.contains("认证") => {
Error::Unauthorized
}
_ => Error::business(code, msg),
}
}
impl FishPi {
pub(crate) async fn get_data<T: DeserializeOwned>(&self, path: &str) -> Result<T, Error> {
let value = self.send_raw(Method::GET, path, None).await?;
let value = check_envelope(value)?;
take_data(value)
}
pub(crate) async fn get_data_with_key<T: DeserializeOwned>(
&self,
path: &str,
) -> Result<T, Error> {
let mut body = Value::Object(Default::default());
self.inject_api_key(&mut body);
let value = self.send_raw(Method::GET, path, Some(&body)).await?;
let value = check_envelope(value)?;
take_data(value)
}
pub(crate) async fn post_data<T: DeserializeOwned, B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<T, Error> {
let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
self.inject_api_key(&mut body);
let value = self.send_raw(Method::POST, path, Some(&body)).await?;
let value = check_envelope(value)?;
take_data(value)
}
pub(crate) async fn get_raw(&self, path: &str) -> Result<Value, Error> {
let value = self.send_raw(Method::GET, path, None).await?;
check_envelope(value)
}
pub(crate) async fn post_raw<B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<Value, Error> {
let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
self.inject_api_key(&mut body);
let value = self.send_raw(Method::POST, path, Some(&body)).await?;
check_envelope(value)
}
pub(crate) async fn put_raw<B: Serialize>(&self, path: &str, body: &B) -> Result<Value, Error> {
let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
self.inject_api_key(&mut body);
let value = self.send_raw(Method::PUT, path, Some(&body)).await?;
check_envelope(value)
}
pub(crate) async fn delete_raw<B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<Value, Error> {
let mut body = serde_json::to_value(body).map_err(|e| Error::decode(e.to_string()))?;
self.inject_api_key(&mut body);
let value = self.send_raw(Method::DELETE, path, Some(&body)).await?;
check_envelope(value)
}
pub(crate) async fn get_text(&self, path: &str) -> Result<String, Error> {
let url = self.full_url(path);
let resp = self
.inner
.http
.get(&url)
.header("User-Agent", USER_AGENT)
.header("Referer", format!("https://{}/", self.inner.config.domain))
.send()
.await?;
let status = resp.status();
if !status.is_success() {
return Err(Error::decode(format!("HTTP error: {}", status)));
}
resp.text().await.map_err(Error::from)
}
fn inject_api_key(&self, body: &mut Value) {
if self.inner.api_key.is_empty() {
return;
}
if let Value::Object(map) = body
&& !map.contains_key("apiKey")
{
map.insert(
"apiKey".to_string(),
Value::String(self.inner.api_key.to_string()),
);
}
}
}
fn take_data<T: DeserializeOwned>(mut value: Value) -> Result<T, Error> {
let data = match value.get_mut("data") {
Some(d) => d.take(),
None => value,
};
let data = if let Value::String(s) = &data {
serde_json::from_str(s).map_err(|e| Error::decode(e.to_string()))?
} else {
data
};
serde_json::from_value(data).map_err(|e| Error::decode(e.to_string()))
}
async fn parse_json_response(resp: Response) -> Result<Value, Error> {
let final_path = resp.url().path().to_string();
let content_type = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
let text = resp.text().await?;
if is_visitor_verify_response(&final_path, &content_type, &text) {
return Err(Error::decode(VISITOR_VERIFY_MESSAGE));
}
serde_json::from_str::<Value>(&text).map_err(|err| {
if is_html_response(&content_type, &text) {
Error::decode("服务返回了网页内容,无法作为 API 响应解析")
} else {
Error::decode(format!("Failed to parse response body: {err}"))
}
})
}
fn is_visitor_verify_response(path: &str, content_type: &str, body: &str) -> bool {
let lower = body.to_ascii_lowercase();
path == "/test"
|| (is_html_response(content_type, body)
&& (body.contains("访客验证")
|| body.contains("在继续浏览摸鱼派社区前请验证")
|| body.contains("/validateCaptcha")
|| lower.contains("initgeetest4")))
}
fn is_html_response(content_type: &str, body: &str) -> bool {
content_type.contains("text/html")
|| body
.trim_start()
.to_ascii_lowercase()
.starts_with("<!doctype html")
}
impl FishPi {
pub async fn login(&self, data: &LoginData) -> Result<FishPi, Error> {
let body = data.to_value()?;
let rsp = self
.send_raw(Method::POST, "api/getKey", Some(&body))
.await?;
let rsp = check_envelope(rsp)?;
let token = rsp
.get("Key")
.and_then(Value::as_str)
.unwrap_or("")
.trim()
.to_string();
Ok(self.with_api_key(token))
}
}