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
use std::{error::Error, time::Duration};

use scraper::Html;
use serde_json::{json, Value};
use tokio::time::sleep;

use crate::AccountCredentials;

#[derive(Debug, Clone)]
/// Client for https://mail.tm/
pub struct Client {
    pub client: reqwest::Client,
    pub account_id: String,
    token: String,
    pub email_address: String,
}

impl Client {
    pub async fn new(account_credentials: &AccountCredentials) -> Result<Self, Box<dyn Error>> {
        let client = reqwest::Client::new();

        let domains: Vec<String> = reqwest::get("https://api.mail.tm/domains")
            .await?
            .json::<Value>()
            .await?["hydra:member"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v["domain"].as_str().unwrap().to_string())
            .collect();

        let domain = &domains[0];
        let address = format!("{}@{}", account_credentials.username, domain);

        let email_address = client
            .post("https://api.mail.tm/accounts")
            .header("Content-Type", "application/json")
            .body(
                json!({"address": address, "password": account_credentials.password }).to_string(),
            )
            .send()
            .await?
            .json::<Value>()
            .await?["address"]
            .as_str()
            .unwrap()
            .to_string();

        let auth_response = client
            .post("https://api.mail.tm/token")
            .header("Content-Type", "application/json")
            .body(
                json!({"address": email_address, "password": account_credentials.password })
                    .to_string(),
            )
            .send()
            .await?
            .json::<Value>()
            .await?;

        let (token, account_id) = (
            auth_response["token"].as_str().unwrap().to_string(),
            auth_response["id"].as_str().unwrap().to_string(),
        );

        Ok(Self {
            client,
            account_id,
            token,
            email_address,
        })
    }

    pub async fn request_latest_message_html(&self) -> Result<Option<Html>, Box<dyn Error>> {
        sleep(Duration::from_secs(1)).await;
        let response = self
            .client
            .get("https://api.mail.tm/messages")
            .bearer_auth(&self.token)
            .send()
            .await?;

        if let Some(content_length) = response.content_length() {
            if content_length == 0 {
                return Ok(None);
            }
        }

        let messages: Vec<String> = response
            .json::<Value>()
            .await?
            .get("hydra:member")
            .unwrap()
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.get("id").unwrap().as_str().unwrap().to_string())
            .collect();

        if messages.is_empty() {
            return Ok(None);
        }

        let message_id = messages.first().unwrap();

        let response = self
            .client
            .get(format!("https://api.mail.tm/messages/{}", message_id))
            .bearer_auth(&self.token)
            .send()
            .await?;

        if let Some(content_length) = response.content_length() {
            if content_length == 0 {
                return Ok(None);
            }
        }

        let html_string = response
            .json::<Value>()
            .await?
            .get("html")
            .unwrap()
            .as_array()
            .unwrap()
            .first()
            .unwrap()
            .as_str()
            .unwrap()
            .to_string();

        self.client
            .delete(format!("https://api.mail.tm/messages/{}", message_id))
            .bearer_auth(&self.token)
            .send()
            .await?;

        let html = Html::parse_document(&html_string);

        return Ok(Some(html));
    }

    pub async fn delete(&self) -> Result<(), Box<dyn Error>> {
        self.client
            .delete(format!("https://api.mail.tm/token/{}", self.account_id))
            .bearer_auth(&self.token)
            .send()
            .await?;

        Ok(())
    }
}