1#![allow(dead_code)]
2
3use std::path::Path;
4use std::time::Duration;
5
6use anyhow::{anyhow, Context, Result};
7use reqwest::blocking::{multipart, Client, Response};
8use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
9
10use crate::config::Config;
11use crate::models::{
12 ApiErrorResponse, AttachmentsResponse, MarkdownRenderResponse, PaginatedProjects,
13 PaginatedPrompts, Project, ProjectInput, Prompt, PromptDetail, PromptInput, Stats,
14 TogglePinResponse,
15};
16
17#[derive(Clone)]
18pub struct ApiClient {
19 client: Client,
20 pub base_url: String,
21 pub api_token: Option<String>,
22}
23
24impl ApiClient {
25 pub fn new(config: &Config) -> Self {
26 let client = Client::builder()
27 .timeout(Duration::from_secs(10))
28 .build()
29 .expect("Failed to build HTTP client");
30
31 Self {
32 client,
33 base_url: config.base_url.clone(),
34 api_token: config.api_token.clone(),
35 }
36 }
37
38 pub fn set_base_url(&mut self, url: &str) {
39 self.base_url = crate::config::normalize_url(url);
40 }
41
42 fn headers(&self) -> HeaderMap {
43 let mut headers = HeaderMap::new();
44 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
45 if let Some(token) = &self.api_token {
46 if let Ok(val) = HeaderValue::from_str(&format!("Bearer {}", token)) {
47 headers.insert(AUTHORIZATION, val);
48 }
49 }
50 headers
51 }
52
53 fn check_response(&self, res: Response) -> Result<Response> {
54 let status = res.status();
55 if status.is_success() {
56 Ok(res)
57 } else {
58 let error_text = res.text().unwrap_or_default();
59 if let Ok(err_obj) = serde_json::from_str::<ApiErrorResponse>(&error_text) {
60 let detail_msg = err_obj
61 .details
62 .map(|d| d.join(", "))
63 .unwrap_or_default();
64 Err(anyhow!(
65 "HTTP {}: {} {}",
66 status.as_u16(),
67 err_obj.error,
68 detail_msg
69 ))
70 } else {
71 Err(anyhow!("HTTP {}: {}", status.as_u16(), error_text))
72 }
73 }
74 }
75
76 pub fn get_stats(&self) -> Result<Stats> {
78 let url = format!("{}/api/v1/stats", self.base_url);
79 let res = self
80 .client
81 .get(&url)
82 .headers(self.headers())
83 .send()
84 .context("Failed to connect to Devbook server")?;
85 let res = self.check_response(res)?;
86 Ok(res.json()?)
87 }
88
89 pub fn render_markdown(&self, text: &str) -> Result<String> {
91 let url = format!("{}/api/v1/markdown/render", self.base_url);
92 let body = serde_json::json!({ "text": text });
93 let res = self
94 .client
95 .post(&url)
96 .headers(self.headers())
97 .json(&body)
98 .send()
99 .context("Failed to connect to Devbook server")?;
100 let res = self.check_response(res)?;
101 let parsed: MarkdownRenderResponse = res.json()?;
102 Ok(parsed.html)
103 }
104
105 pub fn list_projects(&self, q: Option<&str>) -> Result<Vec<Project>> {
107 let mut url = format!("{}/api/v1/projects?limit=100", self.base_url);
108 if let Some(query) = q.filter(|s| !s.trim().is_empty()) {
109 url.push_str("&q=");
110 url.push_str(&urlencoding(query));
111 }
112 let res = self
113 .client
114 .get(&url)
115 .headers(self.headers())
116 .send()
117 .context("Failed to connect to Devbook server")?;
118 let res = self.check_response(res)?;
119 let paginated: PaginatedProjects = res.json()?;
120 Ok(paginated.projects)
121 }
122
123 pub fn create_project(&self, input: &ProjectInput) -> Result<Project> {
124 let url = format!("{}/api/v1/projects", self.base_url);
125 let body = serde_json::json!({ "project": input });
126 let res = self
127 .client
128 .post(&url)
129 .headers(self.headers())
130 .json(&body)
131 .send()?;
132 let res = self.check_response(res)?;
133 Ok(res.json()?)
134 }
135
136 pub fn update_project(&self, id: u64, input: &ProjectInput) -> Result<Project> {
137 let url = format!("{}/api/v1/projects/{}", self.base_url, id);
138 let body = serde_json::json!({ "project": input });
139 let res = self
140 .client
141 .patch(&url)
142 .headers(self.headers())
143 .json(&body)
144 .send()?;
145 let res = self.check_response(res)?;
146 Ok(res.json()?)
147 }
148
149 pub fn delete_project(&self, id: u64) -> Result<()> {
150 let url = format!("{}/api/v1/projects/{}", self.base_url, id);
151 let res = self.client.delete(&url).headers(self.headers()).send()?;
152 self.check_response(res)?;
153 Ok(())
154 }
155
156 pub fn list_prompts(
158 &self,
159 project_id: Option<u64>,
160 scope: Option<&str>,
161 pinned: Option<bool>,
162 search: Option<&str>,
163 ) -> Result<Vec<Prompt>> {
164 let mut url = format!("{}/api/v1/prompts?limit=100", self.base_url);
165 if let Some(pid) = project_id {
166 url.push_str(&format!("&project_id={}", pid));
167 } else if let Some(sc) = scope {
168 url.push_str(&format!("&scope={}", sc));
169 }
170 if let Some(pin) = pinned {
171 url.push_str(&format!("&pinned={}", pin));
172 }
173 if let Some(q) = search.filter(|s| !s.trim().is_empty()) {
174 url.push_str("&q=");
175 url.push_str(&urlencoding(q));
176 }
177
178 let res = self
179 .client
180 .get(&url)
181 .headers(self.headers())
182 .send()
183 .context("Failed to connect to Devbook server")?;
184 let res = self.check_response(res)?;
185 let paginated: PaginatedPrompts = res.json()?;
186 Ok(paginated.prompts)
187 }
188
189 pub fn get_prompt(&self, id: u64) -> Result<PromptDetail> {
190 let url = format!("{}/api/v1/prompts/{}?render_markdown=true", self.base_url, id);
191 let res = self
192 .client
193 .get(&url)
194 .headers(self.headers())
195 .send()
196 .context("Failed to connect to Devbook server")?;
197 let res = self.check_response(res)?;
198 Ok(res.json()?)
199 }
200
201 pub fn create_prompt(&self, input: &PromptInput) -> Result<PromptDetail> {
202 let url = format!("{}/api/v1/prompts", self.base_url);
203 let body = serde_json::json!({ "prompt": input });
204 let res = self
205 .client
206 .post(&url)
207 .headers(self.headers())
208 .json(&body)
209 .send()?;
210 let res = self.check_response(res)?;
211 Ok(res.json()?)
212 }
213
214 pub fn update_prompt(&self, id: u64, input: &PromptInput) -> Result<PromptDetail> {
215 let url = format!("{}/api/v1/prompts/{}", self.base_url, id);
216 let body = serde_json::json!({ "prompt": input });
217 let res = self
218 .client
219 .patch(&url)
220 .headers(self.headers())
221 .json(&body)
222 .send()?;
223 let res = self.check_response(res)?;
224 Ok(res.json()?)
225 }
226
227 pub fn delete_prompt(&self, id: u64) -> Result<()> {
228 let url = format!("{}/api/v1/prompts/{}", self.base_url, id);
229 let res = self.client.delete(&url).headers(self.headers()).send()?;
230 self.check_response(res)?;
231 Ok(())
232 }
233
234 pub fn toggle_pin(&self, id: u64) -> Result<TogglePinResponse> {
235 let url = format!("{}/api/v1/prompts/{}/toggle_pin", self.base_url, id);
236 let res = self.client.patch(&url).headers(self.headers()).send()?;
237 let res = self.check_response(res)?;
238 Ok(res.json()?)
239 }
240
241 pub fn reorder_pinned(&self, ids: &[u64]) -> Result<()> {
242 let url = format!("{}/api/v1/prompts/reorder_pinned", self.base_url);
243 let body = serde_json::json!({ "prompt_ids": ids });
244 let res = self
245 .client
246 .patch(&url)
247 .headers(self.headers())
248 .json(&body)
249 .send()?;
250 self.check_response(res)?;
251 Ok(())
252 }
253
254 pub fn list_attachments(&self, prompt_id: u64) -> Result<Vec<crate::models::Attachment>> {
256 let url = format!("{}/api/v1/prompts/{}/attachments", self.base_url, prompt_id);
257 let res = self.client.get(&url).headers(self.headers()).send()?;
258 let res = self.check_response(res)?;
259 let resp: AttachmentsResponse = res.json()?;
260 Ok(resp.attachments)
261 }
262
263 pub fn upload_attachment(&self, prompt_id: u64, file_path: &Path) -> Result<()> {
264 let url = format!("{}/api/v1/prompts/{}/attachments", self.base_url, prompt_id);
265 let form = multipart::Form::new().file("files[]", file_path)?;
266
267 let mut req = self.client.post(&url);
268 if let Some(token) = &self.api_token {
269 req = req.header(AUTHORIZATION, format!("Bearer {}", token));
270 }
271
272 let res = req.multipart(form).send()?;
273 self.check_response(res)?;
274 Ok(())
275 }
276
277 pub fn delete_attachment(&self, prompt_id: u64, attachment_id: u64) -> Result<()> {
278 let url = format!(
279 "{}/api/v1/prompts/{}/attachments/{}",
280 self.base_url, prompt_id, attachment_id
281 );
282 let res = self.client.delete(&url).headers(self.headers()).send()?;
283 self.check_response(res)?;
284 Ok(())
285 }
286
287 pub fn download_attachment(&self, raw_url: &str, dest_path: &Path) -> Result<()> {
288 let full_url = if raw_url.starts_with("http://") || raw_url.starts_with("https://") {
289 raw_url.to_string()
290 } else {
291 format!("{}{}", self.base_url, raw_url)
292 };
293
294 let mut req = self.client.get(&full_url);
295 if let Some(token) = &self.api_token {
296 req = req.header(AUTHORIZATION, format!("Bearer {}", token));
297 }
298
299 let res = req.send()?;
300 let mut res = self.check_response(res)?;
301 let mut file = std::fs::File::create(dest_path)?;
302 res.copy_to(&mut file)?;
303 Ok(())
304 }
305}
306
307fn urlencoding(input: &str) -> String {
308 let mut out = String::new();
309 for b in input.bytes() {
310 match b {
311 b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
312 out.push(b as char);
313 }
314 b' ' => out.push('+'),
315 _ => {
316 out.push_str(&format!("%{:02X}", b));
317 }
318 }
319 }
320 out
321}