task_picker/sources/
gitlab.rs

1use anyhow::{Ok, Result};
2use chrono::{DateTime, NaiveDate, Utc};
3use json::JsonValue;
4use serde::{Deserialize, Serialize};
5use ureq::Agent;
6
7use crate::tasks::Task;
8
9use super::GITLAB_ICON;
10
11#[derive(Serialize, Deserialize, Clone)]
12#[serde(default)]
13pub struct GitLabSource {
14    #[serde(skip)]
15    agent: Agent,
16    pub name: String,
17    pub server_url: String,
18    pub user_name: String,
19}
20
21impl Default for GitLabSource {
22    fn default() -> Self {
23        Self {
24            agent: Agent::new(),
25            name: "GitLab".to_string(),
26            server_url: "https://gitlab.com/api/v4/".to_string(),
27            user_name: Default::default(),
28        }
29    }
30}
31
32impl GitLabSource {
33    fn query_todos<S>(&self, secret: Option<S>) -> Result<Vec<Task>>
34    where
35        S: AsRef<str>,
36    {
37        let mut request = self
38            .agent
39            .get(&format!("{}/todos?state=pending", self.server_url,));
40        if let Some(secret) = secret {
41            request = request.set("PRIVATE-TOKEN", secret.as_ref());
42        }
43        let response = request.call()?;
44        let body = response.into_string()?;
45        let all_todos = json::parse(&body)?;
46
47        let mut result = Vec::default();
48
49        if let JsonValue::Array(all_todos) = all_todos {
50            for todo in all_todos {
51                let project = todo["project"]["name_with_namespace"]
52                    .as_str()
53                    .unwrap_or(&self.name);
54
55                let title = todo["body"].as_str().unwrap_or_default();
56
57                // Work items sometimes have a woring "target_url, but the
58                // "web_url" of the target is correct and should be prefered.
59                let url = if let Some(target_url) = todo["target"]["web_url"].as_str() {
60                    target_url
61                } else {
62                    todo["target_url"].as_str().unwrap_or_default()
63                };
64
65                let due: Option<DateTime<Utc>> = todo["target"]["due_date"]
66                    .as_str()
67                    .map(|due_date| NaiveDate::parse_from_str(due_date, "%Y-%m-%d"))
68                    .transpose()?
69                    .and_then(|due_date| due_date.and_hms_opt(0, 0, 0))
70                    .map(|due_date| DateTime::from_naive_utc_and_offset(due_date, Utc));
71
72                let created: Option<DateTime<Utc>> = todo["created_at"]
73                    .as_str()
74                    .map(|d| DateTime::parse_from_str(d, "%+"))
75                    .transpose()?
76                    .map(|d| d.into());
77
78                let task = Task {
79                    project: format!("{} {}", GITLAB_ICON, project),
80                    title: title.to_string(),
81                    description: url.to_string(),
82                    due,
83                    created,
84                    id: Some(url.to_string()),
85                };
86                result.push(task);
87            }
88        }
89        Ok(result)
90    }
91
92    pub fn query_tasks<S>(&self, secret: Option<S>) -> Result<Vec<Task>>
93    where
94        S: AsRef<str>,
95    {
96        let mut result = Vec::default();
97
98        let todos = self.query_todos(secret)?;
99        result.extend(todos);
100
101        Ok(result)
102    }
103}