zai_rs/file/
content.rs

1use crate::client::http::HttpClient;
2
3/// File content request (GET /paas/v4/files/{file_id}/content)
4pub struct FileContentRequest {
5    pub key: String,
6    url: String,
7    _body: (),
8}
9
10impl FileContentRequest {
11    pub fn new(key: String, file_id: impl Into<String>) -> Self {
12        let url = format!(
13            "https://open.bigmodel.cn/api/paas/v4/files/{}/content",
14            file_id.into()
15        );
16        Self {
17            key,
18            url,
19            _body: (),
20        }
21    }
22
23    /// Send the request and return raw bytes of the file content.
24    pub async fn send(&self) -> anyhow::Result<Vec<u8>> {
25        let resp: reqwest::Response = self.get().await?;
26        let status = resp.status();
27        if !status.is_success() {
28            let text = resp.text().await.unwrap_or_default();
29            return Err(anyhow::anyhow!(
30                "HTTP {} {} | body={}",
31                status.as_u16(),
32                status.canonical_reason().unwrap_or(""),
33                text
34            ));
35        }
36        let bytes = resp.bytes().await?;
37        Ok(bytes.to_vec())
38    }
39
40    /// Send the request and save content to the given path.
41    /// It will create parent directories if missing.
42    /// Returns the number of bytes written.
43    pub async fn send_to<P: AsRef<std::path::Path>>(&self, path: P) -> anyhow::Result<usize> {
44        let bytes = self.send().await?;
45        let p = path.as_ref();
46        if let Some(parent) = p.parent() {
47            if !parent.as_os_str().is_empty() {
48                std::fs::create_dir_all(parent)?;
49            }
50        }
51        use std::io::Write;
52        let mut f = std::fs::File::create(p)?;
53        f.write_all(&bytes)?;
54        Ok(bytes.len())
55    }
56}
57
58impl HttpClient for FileContentRequest {
59    type Body = ();
60    type ApiUrl = String;
61    type ApiKey = String;
62
63    fn api_url(&self) -> &Self::ApiUrl {
64        &self.url
65    }
66    fn api_key(&self) -> &Self::ApiKey {
67        &self.key
68    }
69    fn body(&self) -> &Self::Body {
70        &self._body
71    }
72}