summaryrefslogtreecommitdiff
path: root/ci-lib-native/src/notifier.rs
blob: dd4a35c9b8a5dc11c94d05e8f772c58c1379bd18 (plain)
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
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use axum::http::StatusCode;
use lettre::transport::smtp::authentication::{Credentials, Mechanism};
use lettre::{Message, Transport};
use lettre::transport::smtp::extension::ClientId;
use lettre::transport::smtp::client::{SmtpConnection, TlsParametersBuilder};
use std::time::Duration;
use std::path::Path;

use ci_lib_core::dbctx::DbCtx;

pub struct RemoteNotifier {
    pub remote_path: String,
    pub notifier: NotifierConfig,
}

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
pub enum NotifierConfig {
    GitHub {
        token: String,
    },
    Email {
        username: String,
        password: String,
        mailserver: String,
        from: String,
        to: String,
    }
}

impl NotifierConfig {
    pub fn github_from_file<P: AsRef<Path>>(path: P) -> Result<Self, String> {
        let path = path.as_ref();
        let bytes = std::fs::read(path)
            .map_err(|e| format!("can't read notifier config at {}: {:?}", path.display(), e))?;
        let config = serde_json::from_slice(&bytes)
            .map_err(|e| format!("can't deserialize notifier config at {}: {:?}", path.display(), e))?;

        if matches!(config, NotifierConfig::GitHub { .. }) {
            Ok(config)
        } else {
            Err(format!("config at {} doesn't look like a github config (but was otherwise valid?)", path.display()))
        }
    }

    pub fn email_from_file<P: AsRef<Path>>(path: P) -> Result<Self, String> {
        let path = path.as_ref();
        let bytes = std::fs::read(path)
            .map_err(|e| format!("can't read notifier config at {}: {:?}", path.display(), e))?;
        let config = serde_json::from_slice(&bytes)
            .map_err(|e| format!("can't deserialize notifier config at {}: {:?}", path.display(), e))?;

        if matches!(config, NotifierConfig::Email { .. }) {
            Ok(config)
        } else {
            Err(format!("config at {} doesn't look like an email config (but was otherwise valid?)", path.display()))
        }
    }
}

impl RemoteNotifier {
    pub async fn tell_pending_job(&self, ctx: &Arc<DbCtx>, repo_id: u64, sha: &str, job_id: u64) -> Result<(), String> {
        self.tell_job_status(
            ctx,
            repo_id, sha, job_id,
            "pending", "build is queued", &format!("https://{}/{}/{}", "ci.butactuallyin.space", &self.remote_path, sha)
        ).await
    }

    pub async fn tell_complete_job(&self, ctx: &Arc<DbCtx>, repo_id: u64, sha: &str, job_id: u64, desc: Result<String, String>) -> Result<(), String> {
        match desc {
            Ok(status) => {
                self.tell_job_status(
                    ctx,
                    repo_id, sha, job_id,
                    "success", &status, &format!("https://{}/{}/{}", "ci.butactuallyin.space", &self.remote_path, sha)
                ).await
            },
            Err(status) => {
                self.tell_job_status(
                    ctx,
                    repo_id, sha, job_id,
                    "failure", &status, &format!("https://{}/{}/{}", "ci.butactuallyin.space", &self.remote_path, sha)
                ).await
            }
        }
    }

    pub async fn tell_job_status(&self, ctx: &Arc<DbCtx>, repo_id: u64, sha: &str, job_id: u64, state: &str, desc: &str, target_url: &str) -> Result<(), String> {
        match &self.notifier {
            NotifierConfig::GitHub { token } => {
                let status_info = serde_json::json!({
                    "state": state,
                    "description": desc,
                    "target_url": target_url,
                    "context": "actuallyinspace runner",
                });

                // TODO: should pool (probably in ctx?) to have an upper bound in concurrent
                // connections.
                let client = reqwest::Client::new();
                let req = client.post(&format!("https://api.github.com/repos/{}/statuses/{}", &self.remote_path, sha))
                    .body(serde_json::to_string(&status_info).expect("can stringify json"))
                    .header("content-type", "application/json")
                    .header("user-agent", "iximeow")
                    .header("authorization", format!("Bearer {}", token))
                    .header("accept", "application/vnd.github+json");
                eprintln!("sending {:?}", req);
                eprintln!("  body: {}", serde_json::to_string(&status_info).expect("can stringify json"));
                let res = req
                    .send()
                    .await;

                match res {
                    Ok(res) => {
                        if res.status() == StatusCode::OK || res.status() == StatusCode::CREATED{
                            Ok(())
                        } else {
                            Err(format!("bad response: {}, response data: {:?}", res.status().as_u16(), res))
                        }
                    }
                    Err(e) => {
                        Err(format!("failure sending request: {:?}", e))
                    }
                }
            }
            NotifierConfig::Email { username, password, mailserver, from, to } => {
                eprintln!("[.] emailing {} for job {} via {}", state, &self.remote_path, mailserver);

                let subject = format!("{}: job for {}", state, &self.remote_path);

                let body = format!("{}", subject);

                // TODO: when ci.butactuallyin.space has valid certs again, ... fix this.
                let tls = TlsParametersBuilder::new(mailserver.to_string())
                    .dangerous_accept_invalid_certs(true)
                    .build()
                    .unwrap();

                let mut mailer = SmtpConnection::connect(
                    mailserver,
                    Some(Duration::from_millis(5000)),
                    &ClientId::Domain("ci.butactuallyin.space".to_string()),
                    None,
                    None,
                ).unwrap();

                mailer.starttls(
                    &tls,
                    &ClientId::Domain("ci.butactuallyin.space".to_string()),
                ).unwrap();

                let resp = mailer.auth(
                    &[Mechanism::Plain, Mechanism::Login],
                    &Credentials::new(username.to_owned(), password.to_owned())
                ).unwrap();
                assert!(resp.is_positive());

                let email = Message::builder()
                    .from(from.parse().unwrap())
                    .to(to.parse().unwrap())
                    .subject(&subject)
                    .body(body)
                    .unwrap();

                match mailer.send(email.envelope(), &email.formatted()) {
                    Ok(_) => {
                        eprintln!("[+] notified {}@{}", username, mailserver);
                        Ok(())
                    }
                    Err(e) => {
                        eprintln!("[-] could not send email: {:?}", e);
                        Err(e.to_string())
                    }
                }
            }
        }
    }
}