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
use std::fs;

use anyhow::Error;
use futures::future;
use futures::future::BoxFuture;
use futures::future::FutureExt;
use reqwest::Client as HttpClient;
use reqwest::ClientBuilder as HttpClientBuilder;
use reqwest::Identity;
use serde_json::Value;

use crate::client::config::PhabricatorClientConfig;
use crate::dto::Task;
use crate::dto::TaskFamily;
use crate::dto::User;
use crate::types::ResultAnyError;

pub struct PhabricatorClient {
  http: HttpClient,
  host: String,
  api_token: String,
}

#[derive(Debug, Clone, thiserror::Error)]
pub enum ErrorType {
  #[error("Certificate identity path: {pkcs12_path:?}, error: {message:?}")]
  CertificateIdentityError {
    pkcs12_path: String,
    message: String,
  },

  #[error("Fail to configure http client, error: {message:?}")]
  FailToConfigureHttpClient { message: String },

  #[error("Validation error: {message:?}")]
  ValidationError { message: String },

  #[error("Fetch sub tasks error: {message:?}")]
  FetchSubTasksError { message: String },

  #[error("Fetch task error: {message:?}")]
  FetchTaskError { message: String },

  #[error("Parse error: {message:?}")]
  ParseError { message: String },
}

impl PhabricatorClient {
  /// This function will trim 'T' at the start of phabricator id.
  /// This is to cover case when you copy-paste the phabricator id from url,
  /// e.g. yourphabhost.com/T1234
  /// ```
  /// # use phab_lib::client::phabricator::PhabricatorClient;
  ///
  /// let phabricator_id  = PhabricatorClient::clean_id("T1234");
  /// assert_eq!(phabricator_id, "1234");
  /// ```
  pub fn clean_id(id: &str) -> &str {
    return id.trim_start_matches('T');
  }

  pub fn new(config: PhabricatorClientConfig) -> ResultAnyError<PhabricatorClient> {
    let mut http_client_builder = Ok(HttpClientBuilder::new());
    let PhabricatorClientConfig {
      host,
      api_token,
      cert_identity_config,
    } = config;

    let cert_identity: Option<Result<_, _>> = cert_identity_config.map(|config| {
      return fs::read(&config.pkcs12_path)
        .map_err(|err| ErrorType::FailToConfigureHttpClient {
          message: err.to_string(),
        })
        .and_then(|bytes| {
          return Identity::from_pkcs12_der(&bytes, &config.pkcs12_password).map_err(|err| {
            ErrorType::CertificateIdentityError {
              pkcs12_path: String::from(config.pkcs12_path),
              message: err.to_string(),
            }
          });
        });
    });

    if let Some(cert_identity) = cert_identity {
      http_client_builder =
        http_client_builder.and_then(|http_client_builder: HttpClientBuilder| {
          return cert_identity.map(|cert_identity: Identity| {
            return http_client_builder.identity(cert_identity);
          });
        });
    }

    return http_client_builder
      .and_then(|http_client_builder| {
        http_client_builder
          .build()
          .map_err(|err| ErrorType::FailToConfigureHttpClient {
            message: err.to_string(),
          })
      })
      .map_err(Error::new)
      .map(|http_client| {
        return PhabricatorClient {
          http: http_client,
          host: String::from(host),
          api_token: String::from(api_token),
        };
      });
  }
}

impl PhabricatorClient {
  pub async fn get_user_by_phid(&self, user_phid: &str) -> ResultAnyError<Option<User>> {
    return self
      .get_users_by_phids(vec![user_phid])
      .await
      .map(|users| users.get(0).map(ToOwned::to_owned));
  }

  pub async fn get_task_by_id(&self, task_id: &str) -> ResultAnyError<Option<Task>> {
    return self
      .get_tasks_by_ids(vec![task_id])
      .await
      .map(|tasks| tasks.get(0).map(ToOwned::to_owned));
  }

  pub async fn get_users_by_phids(&self, user_phids: Vec<&str>) -> ResultAnyError<Vec<User>> {
    let mut form: Vec<(String, &str)> = vec![("api.token".to_owned(), self.api_token.as_str())];

    for i in 0..user_phids.len() {
      let key = format!("constraints[phids][{}]", i);
      let user_phid = user_phids.get(i).unwrap();

      form.push((key, user_phid));
    }

    let url = format!("{}/api/user.search", self.host);

    log::debug!("Getting user by id {} {:?}", url, form);

    let result = self
      .http
      .post(&url)
      .form(&form)
      .send()
      .await
      .map_err(Error::new)?;

    let response_text = result.text().await.map_err(Error::new)?;

    log::debug!("Response {}", response_text);

    let body: Value = serde_json::from_str(response_text.as_str()).map_err(Error::new)?;

    if let Value::Array(users_json) = &body["result"]["data"] {
      if users_json.is_empty() {
        return Ok(vec![]);
      }

      log::debug!("Parsing {:?}", users_json);

      // We only have 1 possible assignment
      let users: Vec<User> = users_json.iter().map(User::from_json).collect();

      log::debug!("Parsed {:?}", users);

      return Ok(users);
    } else {
      return Err(
        ErrorType::ParseError {
          message: format!("Cannot parse {}", &body),
        }
        .into(),
      );
    }
  }

  pub async fn get_tasks_by_ids(&self, task_ids: Vec<&str>) -> ResultAnyError<Vec<Task>> {
    let mut form: Vec<(String, &str)> = vec![
      ("api.token".to_owned(), self.api_token.as_str()),
      ("order".to_owned(), "oldest"),
      ("attachments[columns]".to_owned(), "true"),
      ("attachments[projects]".to_owned(), "true"),
    ];

    for i in 0..task_ids.len() {
      let key = format!("constraints[ids][{}]", i);
      let task_id = PhabricatorClient::clean_id(task_ids.get(i).unwrap());

      form.push((key, task_id));
    }

    let url = format!("{}/api/maniphest.search", self.host);

    log::debug!("Getting task by id {} {:?}", url, form);

    let result = self
      .http
      .post(&url)
      .form(&form)
      .send()
      .await
      .map_err(Error::new)?;

    let response_text = result.text().await.map_err(Error::new)?;

    log::debug!("Response {}", response_text);

    let body: Value = serde_json::from_str(response_text.as_str()).map_err(Error::new)?;

    if let Value::Array(tasks_json) = &body["result"]["data"] {
      if tasks_json.is_empty() {
        return Ok(vec![]);
      }

      log::debug!("Parsing {:?}", tasks_json);

      // We only have 1 possible assignment
      let tasks: Vec<Task> = tasks_json.iter().map(Task::from_json).collect();

      log::debug!("Parsed {:?}", tasks);

      return Ok(tasks);
    } else {
      return Err(
        ErrorType::ParseError {
          message: format!("Cannot parse {}", &body),
        }
        .into(),
      );
    }
  }

  pub async fn get_task_family(&self, root_task_id: &str) -> ResultAnyError<Option<TaskFamily>> {
    let parent_task = self.get_task_by_id(root_task_id).await?;

    if parent_task.is_none() {
      return Ok(None);
    }

    let parent_task = parent_task.unwrap();

    let child_tasks = self.get_child_tasks(vec![root_task_id]).await?;
    let task_family = TaskFamily {
      parent_task,
      children: child_tasks,
    };

    return Ok(Some(task_family));
  }

  pub fn get_child_tasks<'a>(
    &'a self,
    parent_task_ids: Vec<&'a str>,
  ) -> BoxFuture<'a, ResultAnyError<Vec<TaskFamily>>> {
    return async move {
      if parent_task_ids.is_empty() {
        return Err(
          ErrorType::ValidationError {
            message: String::from("Parent ids cannot be empty"),
          }
          .into(),
        );
      }

      let mut form: Vec<(String, &str)> = vec![("api.token".to_owned(), self.api_token.as_str())];

      for i in 0..parent_task_ids.len() {
        let task_id = PhabricatorClient::clean_id(parent_task_ids.get(i).unwrap());
        let key = format!("constraints[parentIDs][{}]", i);

        form.push((key, task_id));
      }

      form.push(("order".to_owned(), "oldest"));
      form.push(("attachments[columns]".to_owned(), "true"));
      form.push(("attachments[projects]".to_owned(), "true"));

      let url = format!("{}/api/maniphest.search", self.host);

      log::debug!("Getting tasks {} {:?}", url, form);

      let result = self
        .http
        .post(&url)
        .form(&form)
        .send()
        .await
        .map_err(Error::new)?;

      let response_text = result.text().await.map_err(Error::new)?;

      log::debug!("Response {}", response_text);

      let body: Value = serde_json::from_str(response_text.as_str()).map_err(Error::new)?;

      if let Value::Array(tasks_json) = &body["result"]["data"] {
        let tasks: Vec<BoxFuture<ResultAnyError<TaskFamily>>> = tasks_json
          .iter()
          .map(|v: &Value| -> BoxFuture<ResultAnyError<TaskFamily>> {
            return async move {
              let parent_task = Task::from_json(&v);

              let children = self
                .get_child_tasks(vec![parent_task.id.as_str()])
                .await
                .map_err(|err| {
                  return ErrorType::FetchSubTasksError {
                    message: format!(
                      "Could not fetch sub tasks with parent id {}, err: {}",
                      parent_task.id, err
                    ),
                  };
                })?;

              return Ok(TaskFamily {
                parent_task,
                children,
              });
            }
            .boxed();
          })
          .collect();

        let (tasks, failed_tasks): (Vec<_>, Vec<_>) = future::join_all(tasks)
          .await
          .into_iter()
          .partition(Result::is_ok);

        if !failed_tasks.is_empty() {
          let error = ErrorType::FetchSubTasksError {
            message: failed_tasks
              .into_iter()
              .fold(String::new(), |acc, task_result| {
                return format!("{}\n{}", acc, task_result.err().unwrap());
              }),
          };

          return Err(error.into());
        }

        let task_families: Vec<TaskFamily> = tasks.into_iter().map(Result::unwrap).collect();

        return Ok(task_families);
      } else {
        return Err(
          ErrorType::ParseError {
            message: format!("Cannot parse {}", &body),
          }
          .into(),
        );
      }
    }
    .boxed();
  }
}