novel_api/sfacg/
utils.rs

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
use std::time::{SystemTime, UNIX_EPOCH};

use hex_simd::AsciiCase;
use reqwest::Response;
use serde::Serialize;
use tokio::sync::OnceCell;
use url::Url;
use uuid::Uuid;

use crate::{Error, HTTPClient, NovelDB, SfacgClient};

#[cfg(target_os = "windows")]
macro_rules! PATH_SEPARATOR {
    () => {
        r"\"
    };
}

#[cfg(not(target_os = "windows"))]
macro_rules! PATH_SEPARATOR {
    () => {
        r"/"
    };
}

include!(concat!(env!("OUT_DIR"), PATH_SEPARATOR!(), "codegen.rs"));

impl SfacgClient {
    const APP_NAME: &'static str = "sfacg";

    const HOST: &'static str = "https://api.sfacg.com";
    const USER_AGENT: &'static str = "boluobao/5.1.34(iOS;18.2)/appStore/{}/appStore";
    const USER_AGENT_RSS: &'static str = "SFReader/5.1.34 (iPhone; iOS 18.2; Scale/3.00)";

    const USERNAME: &'static str = "apiuser";
    const PASSWORD: &'static str = "3s#1-yt6e*Acv@qer";

    const SALT: &'static str = "a@Lk7Tf4gh8TUPoX";

    /// Create a sfacg client
    pub async fn new() -> Result<Self, Error> {
        Ok(Self {
            proxy: None,
            no_proxy: false,
            cert_path: None,
            client: OnceCell::new(),
            client_rss: OnceCell::new(),
            db: OnceCell::new(),
        })
    }

    pub(crate) async fn db(&self) -> Result<&NovelDB, Error> {
        self.db
            .get_or_try_init(|| async { NovelDB::new(SfacgClient::APP_NAME).await })
            .await
    }

    pub(crate) async fn client(&self) -> Result<&HTTPClient, Error> {
        self.client
            .get_or_try_init(|| async {
                let device_token = crate::uid();
                let user_agent = SfacgClient::USER_AGENT.replace("{}", device_token);

                HTTPClient::builder(SfacgClient::APP_NAME)
                    .accept("application/vnd.sfacg.api+json;version=1")
                    .accept_language("zh-Hans-CN;q=1")
                    .cookie(true)
                    .user_agent(user_agent)
                    .proxy(self.proxy.clone())
                    .no_proxy(self.no_proxy)
                    .cert(self.cert_path.clone())
                    .build()
                    .await
            })
            .await
    }

    pub(crate) async fn client_rss(&self) -> Result<&HTTPClient, Error> {
        self.client_rss
            .get_or_try_init(|| async {
                HTTPClient::builder(SfacgClient::APP_NAME)
                    .accept("image/*,*/*;q=0.8")
                    .accept_language("zh-CN,zh-Hans;q=0.9")
                    .user_agent(SfacgClient::USER_AGENT_RSS)
                    .proxy(self.proxy.clone())
                    .no_proxy(self.no_proxy)
                    .cert(self.cert_path.clone())
                    .build()
                    .await
            })
            .await
    }

    pub(crate) async fn get<T>(&self, url: T) -> Result<Response, Error>
    where
        T: AsRef<str>,
    {
        Ok(self
            .client()
            .await?
            .get(SfacgClient::HOST.to_string() + url.as_ref())
            .basic_auth(SfacgClient::USERNAME, Some(SfacgClient::PASSWORD))
            .header("sfsecurity", self.sf_security()?)
            .send()
            .await?)
    }

    pub(crate) async fn get_query<T, E>(&self, url: T, query: E) -> Result<Response, Error>
    where
        T: AsRef<str>,
        E: Serialize,
    {
        let mut count = 0;

        let response = loop {
            let response = self
                .client()
                .await?
                .get(SfacgClient::HOST.to_string() + url.as_ref())
                .query(&query)
                .basic_auth(SfacgClient::USERNAME, Some(SfacgClient::PASSWORD))
                .header("sfsecurity", self.sf_security()?)
                .send()
                .await;

            if let Ok(response) = response {
                break response;
            } else {
                tracing::info!(
                    "HTTP request failed: `{}`, retry, number of times: `{}`",
                    response.as_ref().unwrap_err(),
                    count + 1
                );

                count += 1;
                if count > 3 {
                    response?;
                }
            }
        };

        Ok(response)
    }

    pub(crate) async fn post<T, E>(&self, url: T, json: E) -> Result<Response, Error>
    where
        T: AsRef<str>,
        E: Serialize,
    {
        Ok(self
            .client()
            .await?
            .post(SfacgClient::HOST.to_string() + url.as_ref())
            .basic_auth(SfacgClient::USERNAME, Some(SfacgClient::PASSWORD))
            .header("sfsecurity", self.sf_security()?)
            .json(&json)
            .send()
            .await?)
    }

    pub(crate) async fn put<T, E>(&self, url: T, json: E) -> Result<Response, Error>
    where
        T: AsRef<str>,
        E: Serialize,
    {
        Ok(self
            .client()
            .await?
            .put(SfacgClient::HOST.to_string() + url.as_ref())
            .basic_auth(SfacgClient::USERNAME, Some(SfacgClient::PASSWORD))
            .header("sfsecurity", self.sf_security()?)
            .json(&json)
            .send()
            .await?)
    }

    pub(crate) async fn get_rss(&self, url: &Url) -> Result<Response, Error> {
        let response = self.client_rss().await?.get(url.clone()).send().await?;
        crate::check_status(response.status(), format!("HTTP request failed: `{url}`"))?;

        Ok(response)
    }

    fn sf_security(&self) -> Result<String, Error> {
        let uuid = Uuid::new_v4();
        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();
        let device_token = crate::uid();

        let sign = crate::md5_hex(
            format!("{uuid}{timestamp}{device_token}{}", SfacgClient::SALT),
            AsciiCase::Upper,
        );

        Ok(format!(
            "nonce={uuid}&timestamp={timestamp}&devicetoken={device_token}&sign={sign}"
        ))
    }

    pub(crate) fn convert(content: String) -> String {
        let mut result = String::with_capacity(content.len());

        for c in content.chars() {
            result.push(*CHARACTER_MAPPER.get(&c).unwrap_or(&c));
        }

        result
    }
}