1pub mod error;
2
3use crate::utils::error::Error;
4
5use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
6use reqwest::{Client, Method, Proxy, Response, StatusCode, multipart};
7use serde_json::Value;
8use std::collections::HashMap;
9use std::sync::RwLock;
10use std::time::Duration;
11use tokio::time::sleep;
12use url::form_urlencoded::Serializer;
13
14#[derive(Clone, Debug, PartialEq, Eq)]
15pub enum HttpProxyMode {
16 NoProxy,
17 System,
18 Custom,
19}
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct HttpProxyConfig {
23 pub mode: HttpProxyMode,
24 pub proxy_url: Option<String>,
25}
26
27impl HttpProxyConfig {
28 pub fn no_proxy() -> Self {
29 Self {
30 mode: HttpProxyMode::NoProxy,
31 proxy_url: None,
32 }
33 }
34}
35
36lazy_static::lazy_static! {
37 static ref CLIENT: RwLock<Client> = RwLock::new(build_client(&HttpProxyConfig::no_proxy()).expect("default http client init failed"));
38 static ref HTTP_PROXY_CONFIG: RwLock<HttpProxyConfig> = RwLock::new(HttpProxyConfig::no_proxy());
39}
40
41const DOMAIN: &str = "fishpi.cn";
42const MAX_UPLOAD_FILE_BYTES: u64 = 20 * 1024 * 1024;
43const VISITOR_VERIFY_MESSAGE: &str = "当前网络触发摸鱼派访客验证,请完成验证后再重试";
44
45fn build_client(config: &HttpProxyConfig) -> Result<Client, Error> {
46 let builder = Client::builder();
47 let builder = match config.mode {
48 HttpProxyMode::NoProxy => builder.no_proxy(),
49 HttpProxyMode::System => builder,
50 HttpProxyMode::Custom => {
51 let proxy_url = config
52 .proxy_url
53 .as_deref()
54 .map(str::trim)
55 .filter(|v| !v.is_empty())
56 .ok_or_else(|| Error::Api("proxy url is empty".to_string()))?;
57 builder
58 .no_proxy()
59 .proxy(Proxy::all(proxy_url).map_err(|e| Error::Request(Box::new(e)))?)
60 }
61 };
62
63 builder
64 .connect_timeout(Duration::from_secs(8))
65 .timeout(Duration::from_secs(15))
66 .build()
67 .map_err(|e| Error::Request(Box::new(e)))
68}
69
70fn http_client() -> Client {
71 CLIENT
72 .read()
73 .map(|client| client.clone())
74 .unwrap_or_else(|_| Client::new())
75}
76
77pub fn configure_http_proxy(config: HttpProxyConfig) -> Result<(), Error> {
78 let client = build_client(&config)?;
79 if let Ok(mut guard) = HTTP_PROXY_CONFIG.write() {
80 *guard = config;
81 }
82 if let Ok(mut guard) = CLIENT.write() {
83 *guard = client;
84 }
85 Ok(())
86}
87
88pub fn current_http_proxy_config() -> HttpProxyConfig {
89 HTTP_PROXY_CONFIG
90 .read()
91 .map(|guard| guard.clone())
92 .unwrap_or_else(|_| HttpProxyConfig::no_proxy())
93}
94
95pub async fn get(url: &str) -> Result<Value, Error> {
96 request("GET", url, None, None).await
97}
98
99pub async fn get_with_body(url: &str, data: Option<Value>) -> Result<Value, Error> {
100 request("GET", url, None, data).await
101}
102
103pub async fn put(url: &str, data: Option<Value>) -> Result<Value, Error> {
104 request("PUT", url, None, data).await
105}
106
107pub async fn get_text(url: &str) -> Result<String, Error> {
108 let full_url = format!("https://{}/{}", DOMAIN, url.trim_start_matches('/'));
109
110 let resp = http_client()
111 .get(&full_url)
112 .header(
113 "User-Agent",
114 "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36",
115 )
116 .header("Referer", &format!("https://{}/", DOMAIN))
117 .send()
118 .await
119 .map_err(|e| Error::Request(Box::new(e)))?;
120
121 if !resp.status().is_success() {
122 return Err(Error::Request(
123 format!("HTTP error: {}", resp.status()).into(),
124 ));
125 }
126
127 resp.text().await.map_err(|e| Error::Request(Box::new(e)))
128}
129
130pub async fn get_with_key(url: &str, api_key: &str) -> Result<Value, Error> {
131 let url_with_key = build_http_path(url, &[("apiKey", api_key.to_string())]);
132 request("GET", &url_with_key, None, None).await
133}
134
135pub async fn post(url: &str, data: Option<Value>) -> Result<Value, Error> {
136 request("POST", url, None, data).await
137}
138
139pub async fn delete(url: &str, data: Option<Value>) -> Result<Value, Error> {
140 request("DELETE", url, None, data).await
141}
142
143pub struct UploadTicket {
144 pub ticket: String,
146 pub upload_url: String,
148}
149
150pub async fn request_upload_ticket(api_key: &str) -> Result<UploadTicket, Error> {
152 let url = build_http_path(
153 "api/rhypic/upload-ticket",
154 &[("apiKey", api_key.to_string())],
155 );
156 let rsp = post(&url, None).await?;
157 if rsp.get("code").and_then(Value::as_i64).unwrap_or(-1) != 0 {
158 return Err(Error::Api(
159 rsp["msg"].as_str().unwrap_or("获取上传票据失败").to_string(),
160 ));
161 }
162 let ticket = rsp["data"]["ticket"]
163 .as_str()
164 .filter(|s| !s.is_empty())
165 .ok_or_else(|| Error::Api("上传票据响应缺少 ticket".to_string()))?
166 .to_string();
167 let upload_url = rsp["data"]["uploadURL"]
168 .as_str()
169 .filter(|s| !s.is_empty())
170 .ok_or_else(|| Error::Api("上传票据响应缺少 uploadURL".to_string()))?
171 .to_string();
172 Ok(UploadTicket { ticket, upload_url })
173}
174
175pub async fn upload_files(
177 upload_url: &str,
178 files: Vec<String>,
179 ticket: &str,
180) -> Result<Value, Error> {
181 let full_url = format!("{}/api/v1/files", upload_url.trim_end_matches('/'));
182 let mut form = multipart::Form::new();
183
184 for file_path in files {
185 let path = std::path::Path::new(&file_path);
186 if !path.exists() {
187 return Err(Error::Api(format!("File not exist: {}", file_path)));
188 }
189 let metadata = tokio::fs::metadata(path).await.map_err(|e| {
190 Error::Api(format!("Failed to read file metadata {}: {}", file_path, e))
191 })?;
192 if metadata.len() > MAX_UPLOAD_FILE_BYTES {
193 return Err(Error::Api(format!(
194 "File too large: {} ({} bytes), max {} bytes",
195 file_path,
196 metadata.len(),
197 MAX_UPLOAD_FILE_BYTES
198 )));
199 }
200 let file_content = tokio::fs::read(&file_path)
201 .await
202 .map_err(|e| Error::Api(format!("Failed to read file {}: {}", file_path, e)))?;
203 let file_name = path
204 .file_name()
205 .and_then(|n| n.to_str())
206 .unwrap_or("file")
207 .to_string();
208 form = form.part(
209 "file",
210 multipart::Part::stream(file_content)
211 .file_name(file_name)
212 .mime_str(upload_mime_from_path(path))
213 .map_err(|e| Error::Api(format!("Invalid upload mime type: {}", e)))?,
214 );
215 }
216
217 let response = http_client()
218 .post(&full_url)
219 .header(
220 "User-Agent",
221 "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36",
222 )
223 .header("Authorization", format!("Bearer {}", ticket))
224 .multipart(form)
225 .send()
226 .await
227 .map_err(|e| Error::Api(format!("Request failed: {}", e)))?;
228
229 let rsp: Value = response
230 .json()
231 .await
232 .map_err(|e| Error::Api(format!("Failed to parse response: {}", e)))?;
233
234 Ok(rsp)
235}
236
237fn upload_mime_from_path(path: &std::path::Path) -> &'static str {
238 match path
239 .extension()
240 .and_then(|ext| ext.to_str())
241 .unwrap_or_default()
242 .to_ascii_lowercase()
243 .as_str()
244 {
245 "mp4" => "video/mp4",
246 "webm" => "video/webm",
247 "mov" => "video/quicktime",
248 "m4v" => "video/x-m4v",
249 "m3u8" => "application/vnd.apple.mpegurl",
250 "png" => "image/png",
251 "gif" => "image/gif",
252 "webp" => "image/webp",
253 "jpg" | "jpeg" => "image/jpeg",
254 _ => "application/octet-stream",
255 }
256}
257
258async fn request(
259 method: &str,
260 url: &str,
261 headers: Option<HashMap<String, String>>,
262 data: Option<Value>,
263) -> Result<Value, Error> {
264 let full_url = format!("https://{}/{}", DOMAIN, url.trim_start_matches('/'));
265
266 let method = method
267 .parse::<Method>()
268 .map_err(|e| Error::Request(Box::new(e)))?;
269 let extra_headers = if let Some(headers) = headers {
270 Some(
271 headers
272 .into_iter()
273 .map(|(k, v)| {
274 let name = HeaderName::from_bytes(k.as_bytes())
275 .map_err(|e| Error::Request(Box::new(e)))?;
276 let value =
277 HeaderValue::from_str(&v).map_err(|e| Error::Request(Box::new(e)))?;
278 Ok((name, value))
279 })
280 .collect::<Result<HeaderMap, Error>>()?,
281 )
282 } else {
283 None
284 };
285
286 let max_retries = 2;
287 let mut attempt = 0;
288
289 loop {
290 let mut req = http_client()
291 .request(method.clone(), &full_url)
292 .header(
293 "User-Agent",
294 "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36",
295 )
296 .header("Referer", &format!("https://{}/", DOMAIN));
297
298 if let Some(map) = extra_headers.clone() {
299 req = req.headers(map);
300 }
301
302 if let Some(body) = data.clone() {
303 req = req.json(&body);
304 }
305
306 let resp = match req.send().await {
307 Ok(resp) => resp,
308 Err(err) => {
309 if attempt < max_retries {
310 let wait_ms = 300 * (attempt + 1);
311 sleep(Duration::from_millis(wait_ms as u64)).await;
312 attempt += 1;
313 continue;
314 }
315 return Err(Error::Request(Box::new(err)));
316 }
317 };
318
319 if resp.status().is_success() {
320 return parse_json_response(resp).await;
321 }
322
323 if resp.status() == StatusCode::SERVICE_UNAVAILABLE && attempt < max_retries {
324 let wait_ms = 300 * (attempt + 1);
325 sleep(Duration::from_millis(wait_ms as u64)).await;
326 attempt += 1;
327 continue;
328 }
329
330 return Err(Error::Request(
331 format!("HTTP error: {}", resp.status()).into(),
332 ));
333 }
334}
335
336async fn parse_json_response(resp: Response) -> Result<Value, Error> {
337 let final_path = resp.url().path().to_string();
338 let content_type = resp
339 .headers()
340 .get("content-type")
341 .and_then(|v| v.to_str().ok())
342 .unwrap_or("")
343 .to_ascii_lowercase();
344 let text = resp.text().await.map_err(|e| Error::Request(Box::new(e)))?;
345 if is_visitor_verify_response(&final_path, &content_type, &text) {
346 return Err(Error::Api(VISITOR_VERIFY_MESSAGE.to_string()));
347 }
348
349 serde_json::from_str::<Value>(&text).map_err(|err| {
350 if is_html_response(&content_type, &text) {
351 Error::Api("服务返回了网页内容,无法作为 API 响应解析".to_string())
352 } else {
353 Error::Parse(format!("Failed to parse response body: {err}"))
354 }
355 })
356}
357
358fn is_visitor_verify_response(path: &str, content_type: &str, body: &str) -> bool {
359 let lower = body.to_ascii_lowercase();
360 path == "/test"
361 || (is_html_response(content_type, body)
362 && (body.contains("访客验证")
363 || body.contains("在继续浏览摸鱼派社区前请验证")
364 || body.contains("/validateCaptcha")
365 || lower.contains("initgeetest4")))
366}
367
368fn is_html_response(content_type: &str, body: &str) -> bool {
369 content_type.contains("text/html")
370 || body
371 .trim_start()
372 .to_ascii_lowercase()
373 .starts_with("<!doctype html")
374}
375
376pub fn build_http_path(path: &str, params: &[(&str, String)]) -> String {
378 if params.is_empty() {
379 return path.to_string();
380 }
381
382 let mut serializer = Serializer::new(String::new());
383 for (k, v) in params {
384 serializer.append_pair(k, v);
385 }
386 let query = serializer.finish();
387
388 format!("{}?{}", path, query)
389}
390
391#[derive(Clone, Debug)]
392#[allow(non_snake_case)]
393pub struct ResponseResult {
394 pub success: bool,
396 pub msg: String,
398}
399
400impl ResponseResult {
401 pub fn from_value(data: &Value) -> Result<Self, Error> {
402 Ok(ResponseResult {
403 success: data.get("code").and_then(|c| c.as_i64()).unwrap_or(0) == 0,
404 msg: data["msg"].as_str().unwrap_or("").to_string(),
405 })
406 }
407}
408
409#[cfg(test)]
410mod tests {
411 use super::build_http_path;
412
413 #[test]
414 fn build_http_path_encodes_query() {
415 let p = build_http_path(
416 "chat/get-message",
417 &[
418 ("apiKey", "token a+b".to_string()),
419 ("toUser", "alice/bob".to_string()),
420 ],
421 );
422
423 assert_eq!(p, "chat/get-message?apiKey=token+a%2Bb&toUser=alice%2Fbob");
424 }
425}