bitbucket_cli/api/
client.rs1use anyhow::{Context, Result};
2use reqwest::{Client, Response, StatusCode};
3use serde::de::DeserializeOwned;
4
5use crate::auth::{AuthManager, Credential, OAuthFlow};
6use crate::models::Paginated;
7
8const API_BASE_URL: &str = "https://api.bitbucket.org/2.0";
9
10#[derive(Clone)]
12pub struct BitbucketClient {
13 client: Client,
14 credential: Credential,
15}
16
17impl BitbucketClient {
18 pub fn new(credential: Credential) -> Result<Self> {
20 let client = Client::builder()
21 .user_agent("bitbucket-cli")
22 .timeout(std::time::Duration::from_secs(30))
23 .connect_timeout(std::time::Duration::from_secs(10))
24 .build()
25 .context("Failed to create HTTP client")?;
26
27 Ok(Self { client, credential })
28 }
29
30 pub fn auth_header(&self) -> String {
32 self.credential.auth_header()
33 }
34
35 pub async fn from_stored() -> Result<Self> {
37 let auth_manager = AuthManager::new()?;
38 let credential = auth_manager
39 .get_credentials()?
40 .context("Not authenticated. Run 'bitbucket auth login' first.")?;
41
42 let credential = if credential.needs_refresh() {
44 if let (
45 Credential::OAuth {
46 refresh_token: Some(refresh_token),
47 ..
48 },
49 Some((client_id, client_secret)),
50 ) = (&credential, credential.oauth_consumer_credentials())
51 {
52 let flow = OAuthFlow::new(client_id.to_string(), client_secret.to_string());
53 match flow.refresh_token(&auth_manager, refresh_token).await {
54 Ok(refreshed) => refreshed,
55 Err(e) => {
56 eprintln!("Warning: token refresh failed: {}", e);
57 credential }
59 }
60 } else {
61 credential
62 }
63 } else {
64 credential
65 };
66
67 Self::new(credential)
68 }
69
70 pub fn base_url(&self) -> &str {
72 API_BASE_URL
73 }
74
75 pub fn url(&self, path: &str) -> String {
77 format!("{}{}", API_BASE_URL, path)
78 }
79
80 pub async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
82 let response = self
83 .client
84 .get(self.url(path))
85 .header("Authorization", self.credential.auth_header())
86 .send()
87 .await
88 .context("Request failed")?;
89
90 self.handle_response(response).await
91 }
92
93 pub async fn get_with_query<T: DeserializeOwned>(
95 &self,
96 path: &str,
97 query: &[(&str, &str)],
98 ) -> Result<T> {
99 let response = self
100 .client
101 .get(self.url(path))
102 .header("Authorization", self.credential.auth_header())
103 .query(query)
104 .send()
105 .await
106 .context("Request failed")?;
107
108 self.handle_response(response).await
109 }
110
111 pub(crate) async fn get_absolute<T: DeserializeOwned>(&self, url: &str) -> Result<T> {
113 let response = self
114 .client
115 .get(url)
116 .header("Authorization", self.credential.auth_header())
117 .send()
118 .await
119 .context("Request failed")?;
120
121 self.handle_response(response).await
122 }
123
124 pub(crate) async fn get_text(&self, path: &str, accept: Option<&str>) -> Result<String> {
126 let mut request = self
127 .client
128 .get(self.url(path))
129 .header("Authorization", self.credential.auth_header());
130
131 if let Some(accept) = accept {
132 request = request.header("Accept", accept);
133 }
134
135 let response = request.send().await.context("Request failed")?;
136 let status = response.status();
137
138 if status.is_success() {
139 response
140 .text()
141 .await
142 .context("Failed to read response body")
143 } else {
144 self.handle_error(status, response).await
145 }
146 }
147
148 pub async fn post<T: DeserializeOwned, B: serde::Serialize>(
150 &self,
151 path: &str,
152 body: &B,
153 ) -> Result<T> {
154 let response = self
155 .client
156 .post(self.url(path))
157 .header("Authorization", self.credential.auth_header())
158 .json(body)
159 .send()
160 .await
161 .context("Request failed")?;
162
163 self.handle_response(response).await
164 }
165
166 pub async fn post_no_response<B: serde::Serialize>(&self, path: &str, body: &B) -> Result<()> {
168 let response = self
169 .client
170 .post(self.url(path))
171 .header("Authorization", self.credential.auth_header())
172 .json(body)
173 .send()
174 .await
175 .context("Request failed")?;
176
177 self.handle_empty_response(response).await
178 }
179
180 pub async fn post_multipart(&self, path: &str, form: reqwest::multipart::Form) -> Result<()> {
185 let response = self
186 .client
187 .post(self.url(path))
188 .header("Authorization", self.credential.auth_header())
189 .multipart(form)
190 .timeout(std::time::Duration::from_secs(900))
194 .send()
195 .await
196 .context("Request failed")?;
197
198 self.handle_empty_response(response).await
199 }
200
201 pub async fn put<T: DeserializeOwned, B: serde::Serialize>(
203 &self,
204 path: &str,
205 body: &B,
206 ) -> Result<T> {
207 let response = self
208 .client
209 .put(self.url(path))
210 .header("Authorization", self.credential.auth_header())
211 .json(body)
212 .send()
213 .await
214 .context("Request failed")?;
215
216 self.handle_response(response).await
217 }
218
219 pub async fn delete(&self, path: &str) -> Result<()> {
221 let response = self
222 .client
223 .delete(self.url(path))
224 .header("Authorization", self.credential.auth_header())
225 .send()
226 .await
227 .context("Request failed")?;
228
229 self.handle_empty_response(response).await
230 }
231
232 pub async fn get_all_pages<T: DeserializeOwned>(&self, path: &str) -> Result<Vec<T>> {
234 let mut all_items = Vec::new();
235 let mut next_url: Option<String> = Some(self.url(path));
236
237 while let Some(url) = next_url {
238 let response = self
239 .client
240 .get(&url)
241 .header("Authorization", self.credential.auth_header())
242 .send()
243 .await
244 .context("Request failed")?;
245
246 let page: Paginated<T> = self.handle_response(response).await?;
247 all_items.extend(page.values);
248 next_url = page.next;
249 }
250
251 Ok(all_items)
252 }
253
254 async fn handle_response<T: DeserializeOwned>(&self, response: Response) -> Result<T> {
256 let status = response.status();
257
258 if status.is_success() {
259 response
260 .json()
261 .await
262 .context("Failed to parse response JSON")
263 } else {
264 self.handle_error(status, response).await
265 }
266 }
267
268 async fn handle_empty_response(&self, response: Response) -> Result<()> {
270 let status = response.status();
271
272 if status.is_success() {
273 Ok(())
274 } else {
275 self.handle_error(status, response).await
276 }
277 }
278
279 async fn handle_error<T>(&self, status: StatusCode, response: Response) -> Result<T> {
281 let body = response.text().await.unwrap_or_default();
282
283 match status {
284 StatusCode::UNAUTHORIZED => {
285 anyhow::bail!("Authentication failed. Try running 'bitbucket auth login' again.")
286 }
287 StatusCode::FORBIDDEN => {
288 anyhow::bail!("Access denied. You don't have permission to access this resource.")
289 }
290 StatusCode::NOT_FOUND => {
291 anyhow::bail!("Resource not found.")
292 }
293 StatusCode::TOO_MANY_REQUESTS => {
294 anyhow::bail!("Rate limit exceeded. Please wait and try again.")
295 }
296 _ => {
297 if let Ok(error) = serde_json::from_str::<ApiError>(&body) {
299 if let Some(msg) = error.error.message {
300 anyhow::bail!("API error: {}", msg);
301 }
302 }
303 anyhow::bail!("API error ({}): {}", status, body)
304 }
305 }
306 }
307}
308
309#[derive(serde::Deserialize)]
310struct ApiError {
311 error: ApiErrorDetail,
312}
313
314#[derive(serde::Deserialize)]
315struct ApiErrorDetail {
316 message: Option<String>,
317}