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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use crate::types::*;
use base64::{engine::general_purpose, Engine as _};
use reqwest::header::{HeaderMap, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE};
use reqwest::{Client, ClientBuilder, Response, Url};
use std::{convert::From, time::Duration};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum JiraClientError {
    #[error("Request failed")]
    HttpError(#[from] reqwest::Error),
    #[error("Body malformed or invalid: {0}")]
    JiraRequestBodyError(String),
    #[error("Unable to parse response: {0}")]
    JiraResponseDeserializeError(String),
    #[error("Unable to build JiraAPIClient struct:{0}")]
    ConfigError(String),
    #[error("Unable to parse Url: {0}")]
    UrlParseError(String),
    #[error("{0}")]
    TryFromError(String),
    #[error("{0}")]
    UnknownError(String),
}

/// JiraApiClient config object
#[derive(Debug, Clone)]
pub struct JiraClientConfig {
    pub credential: Credential,
    pub max_query_results: u32,
    pub url: String,
    pub timeout: u64,
    pub tls_accept_invalid_certs: bool,
}

/// Supported Authentication methods
#[derive(Debug, Clone)]
pub enum Credential {
    /// Anonymous
    /// Omit Authorization header
    Anonymous,
    /// User email/username and token
    /// Authorization: Basic <b64 login:token>
    ApiToken { login: String, token: String },
    /// Personal Access Token
    /// Authorization: Bearer <PAT>
    PersonalAccessToken(String),
}

/// Reusable client for interfacing with Jira
#[derive(Debug, Clone)]
pub struct JiraAPIClient {
    pub url: Url,
    pub version: String,

    pub(crate) client: Client,
    pub(crate) max_results: u32,
}

impl JiraAPIClient {
    fn build_headers(credentials: &Credential) -> HeaderMap {
        let header_content = HeaderValue::from_static("application/json");

        let auth_header = match credentials {
            Credential::Anonymous => None,
            Credential::ApiToken {
                login: user_login,
                token: api_token,
            } => {
                let jira_encoded_auth = general_purpose::STANDARD_NO_PAD
                    .encode(format!("{}:{}", user_login, api_token,));
                Some(HeaderValue::from_str(&format!("Basic {}", jira_encoded_auth)).unwrap())
            }
            Credential::PersonalAccessToken(token) => {
                Some(HeaderValue::from_str(&format!("Bearer {}", token)).unwrap())
            }
        };

        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT, header_content.clone());
        headers.insert(CONTENT_TYPE, header_content);

        if let Some(mut auth_header_value) = auth_header {
            auth_header_value.set_sensitive(true);
            headers.insert(AUTHORIZATION, auth_header_value);
        }

        headers
    }

    /// Instantiate a reusable API client.
    ///
    /// ```rust
    /// use jira_issue_api::types::*;
    /// use jira_issue_api::{Credential, JiraClientConfig, JiraAPIClient};
    ///
    /// let anon = Credential::Anonymous;
    ///
    /// // let credential = Credential::PersonalAccessToken("xxxxxxx".to_string())
    ///
    /// // let api_token = Credential::ApiToken {
    /// //     login: "user@example.com".to_string(),
    /// //     token: "xxxxxxx".to_string(),
    /// // };
    ///
    /// let jira_cfg = JiraClientConfig {
    ///     credential: anon,
    ///     max_query_results: 50u32,
    ///     url: "https://domain.atlassian.net".to_string(),
    ///     timeout: 10u64,
    ///     tls_accept_invalid_certs: false,
    /// };
    ///
    /// let client = JiraAPIClient::new(&jira_cfg).unwrap();
    /// ```
    pub fn new(cfg: &JiraClientConfig) -> Result<JiraAPIClient, JiraClientError> {
        let client = ClientBuilder::new()
            .default_headers(JiraAPIClient::build_headers(&cfg.credential))
            .danger_accept_invalid_certs(cfg.tls_accept_invalid_certs)
            .https_only(true)
            .timeout(Duration::from_secs(cfg.timeout))
            .build()
            .map_err(|e| JiraClientError::ConfigError(e.to_string()))?;

        Ok(JiraAPIClient {
            url: Url::parse(cfg.url.as_str())
                .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?,
            version: String::from("latest"),
            client,
            max_results: cfg.max_query_results,
        })
    }

    pub async fn query_issues(
        &self,
        query: &String,
    ) -> Result<PostIssueQueryResponseBody, JiraClientError> {
        let search_url = self
            .url
            .join("/rest/api/latest/search")
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;
        let body = PostIssueQueryBody {
            jql: query.to_owned(),
            start_at: 0,
            max_results: self.max_results,
            fields: vec![String::from("summary")],
        };

        let response = self
            .client
            .post(search_url)
            .json(&body)
            .send()
            .await
            .map_err(JiraClientError::HttpError)?;

        response
            .json::<PostIssueQueryResponseBody>()
            .await
            .map_err(|e| JiraClientError::JiraResponseDeserializeError(e.to_string()))
    }

    pub async fn post_worklog(
        &self,
        issue_key: &IssueKey,
        body: PostWorklogBody,
    ) -> Result<Response, JiraClientError> {
        let worklog_url = match self
            .url
            .join(format!("/rest/api/latest/issue/{}/worklog", issue_key).as_str())
        {
            Ok(url) => url,
            Err(e) => Err(JiraClientError::UrlParseError(e.to_string()))?,
        };

        // If any pattern matches, do not prompt.
        if matches!(
            (body.time_spent.is_some(), body.time_spent_seconds.is_some()),
            (false, false) | (true, true)
        ) {
            return Err(JiraClientError::JiraRequestBodyError(
                "time_spent and time_spent_seconds are both 'Some()' or 'None'".to_string(),
            ));
        }

        self.client
            .post(worklog_url)
            .json(&body)
            .send()
            .await
            .map_err(JiraClientError::HttpError)
    }

    pub async fn post_comment(
        &self,
        issue_key: &IssueKey,
        body: PostCommentBody,
    ) -> Result<Response, JiraClientError> {
        let comment_url = self
            .url
            .join(format!("/rest/api/latest/issue/{}/comment", issue_key).as_str())
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;

        self.client
            .post(comment_url)
            .json(&body)
            .send()
            .await
            .map_err(JiraClientError::HttpError)
    }

    pub async fn get_transitions(
        &self,
        issue_key: &IssueKey,
        expand: bool,
    ) -> Result<GetTransitionsBody, JiraClientError> {
        let mut transitions_url = self
            .url
            .join(format!("/rest/api/latest/issue/{}/transitions", issue_key).as_str())
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;

        if expand {
            transitions_url.set_query(Some("expand=transitions.fields"))
        }

        let response = self
            .client
            .get(transitions_url)
            .send()
            .await
            .map_err(JiraClientError::HttpError)?;

        response
            .json::<GetTransitionsBody>()
            .await
            .map_err(|e| JiraClientError::JiraResponseDeserializeError(e.to_string()))
    }

    pub async fn post_transition(
        &self,
        issue_key: &IssueKey,
        transition: &PostTransitionBody,
    ) -> Result<Response, JiraClientError> {
        let transition_url = self
            .url
            .join(format!("/rest/api/latest/issue/{}/transitions", issue_key).as_str())
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;

        let response = self
            .client
            .post(transition_url)
            .json(transition)
            .send()
            .await
            .map_err(JiraClientError::HttpError)?;

        Ok(response)
    }

    pub async fn get_assignable_users(
        &self,
        params: &GetAssignableUserParams,
    ) -> Result<Vec<User>, JiraClientError> {
        let mut users_url = self
            .url
            .join("/rest/api/latest/user/assignable/search")
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;
        let mut query: String = format!("maxResults={}", params.max_results.unwrap_or(1000));

        if params.project.is_none() && params.issue_key.is_none() {
            Err(JiraClientError::JiraRequestBodyError(
                "Both project and issue_key are None, define either to query for assignable users."
                    .to_string(),
            ))?
        }

        if let Some(issue_key) = params.issue_key.clone() {
            query.push_str(format!("&issueKey={}", issue_key).as_str());
        }
        if let Some(username) = params.username.clone() {
            #[cfg(feature = "cloud")]
            query.push_str(format!("&query={}", username).as_str());
            #[cfg(not(feature = "cloud"))]
            query.push_str(format!("&username={}", username).as_str());
        }
        if let Some(project) = params.project.clone() {
            query.push_str(format!("&project={}", project).as_str());
        }

        users_url.set_query(Some(query.as_str()));

        let response = self
            .client
            .get(users_url)
            .send()
            .await
            .map_err(JiraClientError::HttpError)?;

        response
            .json::<Vec<User>>()
            .await
            .map_err(|e| JiraClientError::JiraResponseDeserializeError(e.to_string()))
    }

    pub async fn post_assign_user(
        &self,
        issue_key: &IssueKey,
        user: &User,
    ) -> Result<Response, JiraClientError> {
        let assign_url = self
            .url
            .join(format!("/rest/api/latest/issue/{}/assignee", issue_key).as_str())
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;

        let body = PostAssignBody::from(user.clone());

        let response = self
            .client
            .put(assign_url)
            .json(&body)
            .send()
            .await
            .map_err(JiraClientError::HttpError)?;
        Ok(response)
    }

    /// cloud:  user.account_id
    /// server: user.name
    pub async fn get_user(&self, user: String) -> Result<User, JiraClientError> {
        let user_url = self
            .url
            .join("/rest/api/latest/user")
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;

        let key = match cfg!(feature = "cloud") {
            true => "accountId",
            false => "username",
        };

        let response = self
            .client
            .get(user_url)
            .query(&[(key, user)])
            .send()
            .await
            .map_err(JiraClientError::HttpError)?;

        response
            .json::<User>()
            .await
            .map_err(|e| JiraClientError::JiraResponseDeserializeError(e.to_string()))
    }

    #[cfg(feature = "cloud")]
    pub async fn search_filters(
        &self,
        filter: Option<String>,
    ) -> Result<GetFilterResponseBody, JiraClientError> {
        let mut search_url = self
            .url
            .join("/rest/api/latest/filter/search")
            .map_err(|e| JiraClientError::UrlParseError(e.to_string()))?;
        let query = if let Some(filter) = filter {
            format!(
                "expand=jql&maxResults={}&filterName={}",
                self.max_results, filter
            )
        } else {
            format!("expand=jql&maxResults={}", self.max_results)
        };

        search_url.set_query(Some(query.as_str()));

        let response = self
            .client
            .get(search_url)
            .send()
            .await
            .map_err(JiraClientError::HttpError)?;

        response
            .json::<GetFilterResponseBody>()
            .await
            .map_err(JiraClientError::HttpError)
    }
}