Skip to main content

babelforce_manager_sdk/resources/
files.rs

1use std::sync::Arc;
2
3use crate::error::{map_manager_err, ManagerError};
4use crate::gen::manager::apis::configuration::Configuration;
5use crate::gen::manager::apis::file_api;
6use crate::gen::manager::models;
7use crate::http::{collect_all, fetch_page, Page};
8use crate::retry::{with_retry, RetryPolicy};
9
10/// Stored files — `/api/v2/files` (recordings, prompts and backups).
11pub struct FilesResource {
12    pub(crate) cfg: Arc<Configuration>,
13    pub(crate) retry: RetryPolicy,
14}
15
16impl FilesResource {
17    /// List all files (auto-paginated).
18    pub async fn list_all(&self) -> Result<Vec<models::StoredFile>, ManagerError> {
19        collect_all(&self.retry, map_manager_err, |page| async move {
20            let r = file_api::list_files(
21                self.cfg.as_ref(),
22                Some(page),
23                None,
24                None,
25                None,
26                None,
27                None,
28                None,
29                None,
30            )
31            .await?;
32            Ok((r.items, r.pagination.pages, r.pagination.current))
33        })
34        .await
35    }
36
37    /// List one page of files, optionally narrowed to one storage type.
38    pub async fn list_page(
39        &self,
40        page: i32,
41        per_page: Option<i32>,
42        file_type: Option<models::StorageType>,
43    ) -> Result<Page<models::StoredFile>, ManagerError> {
44        fetch_page(&self.retry, map_manager_err, || async move {
45            let r = file_api::list_files(
46                self.cfg.as_ref(),
47                Some(page),
48                per_page,
49                None,
50                None,
51                file_type,
52                None,
53                None,
54                None,
55            )
56            .await?;
57            Ok((
58                r.items,
59                r.pagination.pages,
60                r.pagination.current,
61                Some(r.pagination.total),
62            ))
63        })
64        .await
65    }
66
67    /// List files of a given storage type (single, non-paginated response).
68    pub async fn list_by_type(
69        &self,
70        file_type: models::StorageType,
71    ) -> Result<Vec<models::StoredFile>, ManagerError> {
72        let r = with_retry(&self.retry, true, || {
73            file_api::list_files_by_type(self.cfg.as_ref(), file_type)
74        })
75        .await
76        .map_err(map_manager_err)?;
77        Ok(r.items)
78    }
79
80    /// List all backup files.
81    pub async fn backups(&self) -> Result<Vec<models::StoredFile>, ManagerError> {
82        let r = with_retry(&self.retry, true, || {
83            file_api::list_backup_files(self.cfg.as_ref())
84        })
85        .await
86        .map_err(map_manager_err)?;
87        Ok(r.items)
88    }
89
90    /// List all recording files.
91    pub async fn recordings(&self) -> Result<Vec<models::StoredFile>, ManagerError> {
92        let r = with_retry(&self.retry, true, || {
93            file_api::list_recording_files(self.cfg.as_ref())
94        })
95        .await
96        .map_err(map_manager_err)?;
97        Ok(r.items)
98    }
99
100    /// List all prompt files.
101    pub async fn prompts(&self) -> Result<Vec<models::StoredFile>, ManagerError> {
102        let r = with_retry(&self.retry, true, || {
103            file_api::list_prompt_files(self.cfg.as_ref())
104        })
105        .await
106        .map_err(map_manager_err)?;
107        Ok(r.items)
108    }
109
110    /// Get a file by id.
111    pub async fn get(&self, id: &str) -> Result<models::StoredFileItemResponse, ManagerError> {
112        with_retry(&self.retry, true, || {
113            file_api::get_file(self.cfg.as_ref(), id)
114        })
115        .await
116        .map_err(map_manager_err)
117    }
118
119    /// Delete a file by id.
120    pub async fn delete(&self, id: &str) -> Result<models::DefaultV2MessageResponse, ManagerError> {
121        with_retry(&self.retry, false, || {
122            file_api::delete_file(self.cfg.as_ref(), id)
123        })
124        .await
125        .map_err(map_manager_err)
126    }
127
128    /// Trigger a download for a file by id.
129    ///
130    /// The underlying endpoint redirects to a download link; the generated client discards the
131    /// response body, so this returns `()` once the server-side download has been triggered.
132    /// Use [`bulk_download`](Self::bulk_download) / [`bulk_download_post`](Self::bulk_download_post)
133    /// when you need the actual bytes.
134    pub async fn download(&self, id: &str) -> Result<(), ManagerError> {
135        with_retry(&self.retry, true, || {
136            file_api::download_file(self.cfg.as_ref(), id)
137        })
138        .await
139        .map_err(map_manager_err)?;
140        Ok(())
141    }
142
143    /// Bulk-delete files by id. Each `id` must be a valid UUID.
144    pub async fn bulk_delete(
145        &self,
146        ids: Vec<String>,
147    ) -> Result<models::DefaultV2MessageResponse, ManagerError> {
148        let ids = ids
149            .iter()
150            .map(|id| {
151                uuid::Uuid::parse_str(id)
152                    .map_err(|e| ManagerError::InvalidArgument(format!("id {id:?}: {e}")))
153            })
154            .collect::<Result<Vec<_>, _>>()?;
155        let body = models::FileBulkDeleteRequest { ids };
156        with_retry(&self.retry, false, || {
157            file_api::bulk_delete_files(self.cfg.as_ref(), body.clone())
158        })
159        .await
160        .map_err(map_manager_err)
161    }
162
163    /// Download multiple files as a ZIP archive (GET), returning the raw bytes.
164    pub async fn bulk_download(&self, ids: Vec<String>) -> Result<Vec<u8>, ManagerError> {
165        let ids_joined = ids.join(",");
166        let resp = file_api::get_bulk_file_download(self.cfg.as_ref(), &ids_joined)
167            .await
168            .map_err(map_manager_err)?;
169        let bytes = resp
170            .bytes()
171            .await
172            .map_err(|e| ManagerError::Network(e.to_string()))?
173            .to_vec();
174        Ok(bytes)
175    }
176
177    /// Download multiple files as a ZIP archive (POST), returning the raw bytes.
178    /// Each `id` must be a valid UUID.
179    pub async fn bulk_download_post(&self, ids: Vec<String>) -> Result<Vec<u8>, ManagerError> {
180        let ids = ids
181            .iter()
182            .map(|id| {
183                uuid::Uuid::parse_str(id)
184                    .map_err(|e| ManagerError::InvalidArgument(format!("id {id:?}: {e}")))
185            })
186            .collect::<Result<Vec<_>, _>>()?;
187        let body = models::FileBulkDownloadRequest { ids };
188        let resp = file_api::post_bulk_file_download(self.cfg.as_ref(), body)
189            .await
190            .map_err(map_manager_err)?;
191        let bytes = resp
192            .bytes()
193            .await
194            .map_err(|e| ManagerError::Network(e.to_string()))?
195            .to_vec();
196        Ok(bytes)
197    }
198}