fishpi-sdk 1.1.1

A Rust SDK for interacting with the FishPi community API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
pub mod error;

use crate::utils::error::Error;

use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, Method, Proxy, Response, StatusCode, multipart};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::RwLock;
use std::time::Duration;
use tokio::time::sleep;
use url::form_urlencoded::Serializer;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HttpProxyMode {
    NoProxy,
    System,
    Custom,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HttpProxyConfig {
    pub mode: HttpProxyMode,
    pub proxy_url: Option<String>,
}

impl HttpProxyConfig {
    pub fn no_proxy() -> Self {
        Self {
            mode: HttpProxyMode::NoProxy,
            proxy_url: None,
        }
    }
}

lazy_static::lazy_static! {
    static ref CLIENT: RwLock<Client> = RwLock::new(build_client(&HttpProxyConfig::no_proxy()).expect("default http client init failed"));
    static ref HTTP_PROXY_CONFIG: RwLock<HttpProxyConfig> = RwLock::new(HttpProxyConfig::no_proxy());
}

const DOMAIN: &str = "fishpi.cn";
const MAX_UPLOAD_FILE_BYTES: u64 = 20 * 1024 * 1024;
const VISITOR_VERIFY_MESSAGE: &str = "当前网络触发摸鱼派访客验证,请完成验证后再重试";

fn build_client(config: &HttpProxyConfig) -> Result<Client, Error> {
    let builder = Client::builder();
    let builder = match config.mode {
        HttpProxyMode::NoProxy => builder.no_proxy(),
        HttpProxyMode::System => builder,
        HttpProxyMode::Custom => {
            let proxy_url = config
                .proxy_url
                .as_deref()
                .map(str::trim)
                .filter(|v| !v.is_empty())
                .ok_or_else(|| Error::Api("proxy url is empty".to_string()))?;
            builder
                .no_proxy()
                .proxy(Proxy::all(proxy_url).map_err(|e| Error::Request(Box::new(e)))?)
        }
    };

    builder
        .connect_timeout(Duration::from_secs(8))
        .timeout(Duration::from_secs(15))
        .build()
        .map_err(|e| Error::Request(Box::new(e)))
}

fn http_client() -> Client {
    CLIENT
        .read()
        .map(|client| client.clone())
        .unwrap_or_else(|_| Client::new())
}

pub fn configure_http_proxy(config: HttpProxyConfig) -> Result<(), Error> {
    let client = build_client(&config)?;
    if let Ok(mut guard) = HTTP_PROXY_CONFIG.write() {
        *guard = config;
    }
    if let Ok(mut guard) = CLIENT.write() {
        *guard = client;
    }
    Ok(())
}

pub fn current_http_proxy_config() -> HttpProxyConfig {
    HTTP_PROXY_CONFIG
        .read()
        .map(|guard| guard.clone())
        .unwrap_or_else(|_| HttpProxyConfig::no_proxy())
}

pub async fn get(url: &str) -> Result<Value, Error> {
    request("GET", url, None, None).await
}

pub async fn get_with_body(url: &str, data: Option<Value>) -> Result<Value, Error> {
    request("GET", url, None, data).await
}

pub async fn put(url: &str, data: Option<Value>) -> Result<Value, Error> {
    request("PUT", url, None, data).await
}

pub async fn get_text(url: &str) -> Result<String, Error> {
    let full_url = format!("https://{}/{}", DOMAIN, url.trim_start_matches('/'));

    let resp = http_client()
        .get(&full_url)
        .header(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36",
        )
        .header("Referer", &format!("https://{}/", DOMAIN))
        .send()
        .await
        .map_err(|e| Error::Request(Box::new(e)))?;

    if !resp.status().is_success() {
        return Err(Error::Request(
            format!("HTTP error: {}", resp.status()).into(),
        ));
    }

    resp.text().await.map_err(|e| Error::Request(Box::new(e)))
}

pub async fn get_with_key(url: &str, api_key: &str) -> Result<Value, Error> {
    let url_with_key = build_http_path(url, &[("apiKey", api_key.to_string())]);
    request("GET", &url_with_key, None, None).await
}

pub async fn post(url: &str, data: Option<Value>) -> Result<Value, Error> {
    request("POST", url, None, data).await
}

pub async fn delete(url: &str, data: Option<Value>) -> Result<Value, Error> {
    request("DELETE", url, None, data).await
}

pub struct UploadTicket {
    /// 一次性上传票据(JWT)。
    pub ticket: String,
    /// 上传地址。
    pub upload_url: String,
}

/// 一次性上传票据。
pub async fn request_upload_ticket(api_key: &str) -> Result<UploadTicket, Error> {
    let url = build_http_path(
        "api/rhypic/upload-ticket",
        &[("apiKey", api_key.to_string())],
    );
    let rsp = post(&url, None).await?;
    if rsp.get("code").and_then(Value::as_i64).unwrap_or(-1) != 0 {
        return Err(Error::Api(
            rsp["msg"].as_str().unwrap_or("获取上传票据失败").to_string(),
        ));
    }
    let ticket = rsp["data"]["ticket"]
        .as_str()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| Error::Api("上传票据响应缺少 ticket".to_string()))?
        .to_string();
    let upload_url = rsp["data"]["uploadURL"]
        .as_str()
        .filter(|s| !s.is_empty())
        .ok_or_else(|| Error::Api("上传票据响应缺少 uploadURL".to_string()))?
        .to_string();
    Ok(UploadTicket { ticket, upload_url })
}

/// 携带票据直传图床, `{code, msg, data}` 响应。
pub async fn upload_files(
    upload_url: &str,
    files: Vec<String>,
    ticket: &str,
) -> Result<Value, Error> {
    let full_url = format!("{}/api/v1/files", upload_url.trim_end_matches('/'));
    let mut form = multipart::Form::new();

    for file_path in files {
        let path = std::path::Path::new(&file_path);
        if !path.exists() {
            return Err(Error::Api(format!("File not exist: {}", file_path)));
        }
        let metadata = tokio::fs::metadata(path).await.map_err(|e| {
            Error::Api(format!("Failed to read file metadata {}: {}", file_path, e))
        })?;
        if metadata.len() > MAX_UPLOAD_FILE_BYTES {
            return Err(Error::Api(format!(
                "File too large: {} ({} bytes), max {} bytes",
                file_path,
                metadata.len(),
                MAX_UPLOAD_FILE_BYTES
            )));
        }
        let file_content = tokio::fs::read(&file_path)
            .await
            .map_err(|e| Error::Api(format!("Failed to read file {}: {}", file_path, e)))?;
        let file_name = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("file")
            .to_string();
        form = form.part(
            "file",
            multipart::Part::stream(file_content)
                .file_name(file_name)
                .mime_str(upload_mime_from_path(path))
                .map_err(|e| Error::Api(format!("Invalid upload mime type: {}", e)))?,
        );
    }

    let response = http_client()
        .post(&full_url)
        .header(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36",
        )
        .header("Authorization", format!("Bearer {}", ticket))
        .multipart(form)
        .send()
        .await
        .map_err(|e| Error::Api(format!("Request failed: {}", e)))?;

    let rsp: Value = response
        .json()
        .await
        .map_err(|e| Error::Api(format!("Failed to parse response: {}", e)))?;

    Ok(rsp)
}

fn upload_mime_from_path(path: &std::path::Path) -> &'static str {
    match path
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or_default()
        .to_ascii_lowercase()
        .as_str()
    {
        "mp4" => "video/mp4",
        "webm" => "video/webm",
        "mov" => "video/quicktime",
        "m4v" => "video/x-m4v",
        "m3u8" => "application/vnd.apple.mpegurl",
        "png" => "image/png",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "jpg" | "jpeg" => "image/jpeg",
        _ => "application/octet-stream",
    }
}

async fn request(
    method: &str,
    url: &str,
    headers: Option<HashMap<String, String>>,
    data: Option<Value>,
) -> Result<Value, Error> {
    let full_url = format!("https://{}/{}", DOMAIN, url.trim_start_matches('/'));

    let method = method
        .parse::<Method>()
        .map_err(|e| Error::Request(Box::new(e)))?;
    let extra_headers = if let Some(headers) = headers {
        Some(
            headers
                .into_iter()
                .map(|(k, v)| {
                    let name = HeaderName::from_bytes(k.as_bytes())
                        .map_err(|e| Error::Request(Box::new(e)))?;
                    let value =
                        HeaderValue::from_str(&v).map_err(|e| Error::Request(Box::new(e)))?;
                    Ok((name, value))
                })
                .collect::<Result<HeaderMap, Error>>()?,
        )
    } else {
        None
    };

    let max_retries = 2;
    let mut attempt = 0;

    loop {
        let mut req = http_client()
            .request(method.clone(), &full_url)
            .header(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36",
            )
            .header("Referer", &format!("https://{}/", DOMAIN));

        if let Some(map) = extra_headers.clone() {
            req = req.headers(map);
        }

        if let Some(body) = data.clone() {
            req = req.json(&body);
        }

        let resp = match req.send().await {
            Ok(resp) => resp,
            Err(err) => {
                if attempt < max_retries {
                    let wait_ms = 300 * (attempt + 1);
                    sleep(Duration::from_millis(wait_ms as u64)).await;
                    attempt += 1;
                    continue;
                }
                return Err(Error::Request(Box::new(err)));
            }
        };

        if resp.status().is_success() {
            return parse_json_response(resp).await;
        }

        if resp.status() == StatusCode::SERVICE_UNAVAILABLE && attempt < max_retries {
            let wait_ms = 300 * (attempt + 1);
            sleep(Duration::from_millis(wait_ms as u64)).await;
            attempt += 1;
            continue;
        }

        return Err(Error::Request(
            format!("HTTP error: {}", resp.status()).into(),
        ));
    }
}

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.map_err(|e| Error::Request(Box::new(e)))?;
    if is_visitor_verify_response(&final_path, &content_type, &text) {
        return Err(Error::Api(VISITOR_VERIFY_MESSAGE.to_string()));
    }

    serde_json::from_str::<Value>(&text).map_err(|err| {
        if is_html_response(&content_type, &text) {
            Error::Api("服务返回了网页内容,无法作为 API 响应解析".to_string())
        } else {
            Error::Parse(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")
}

/// 构造带查询参数的相对 HTTP 路径,自动进行 query 编码
pub fn build_http_path(path: &str, params: &[(&str, String)]) -> String {
    if params.is_empty() {
        return path.to_string();
    }

    let mut serializer = Serializer::new(String::new());
    for (k, v) in params {
        serializer.append_pair(k, v);
    }
    let query = serializer.finish();

    format!("{}?{}", path, query)
}

#[derive(Clone, Debug)]
#[allow(non_snake_case)]
pub struct ResponseResult {
    /// 是否成功
    pub success: bool,
    /// 执行结果或错误信息
    pub msg: String,
}

impl ResponseResult {
    pub fn from_value(data: &Value) -> Result<Self, Error> {
        Ok(ResponseResult {
            success: data.get("code").and_then(|c| c.as_i64()).unwrap_or(0) == 0,
            msg: data["msg"].as_str().unwrap_or("").to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::build_http_path;

    #[test]
    fn build_http_path_encodes_query() {
        let p = build_http_path(
            "chat/get-message",
            &[
                ("apiKey", "token a+b".to_string()),
                ("toUser", "alice/bob".to_string()),
            ],
        );

        assert_eq!(p, "chat/get-message?apiKey=token+a%2Bb&toUser=alice%2Fbob");
    }
}