-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
106 lines (89 loc) · 2.6 KB
/
main.js
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
const fetch = require("cross-fetch");
const url = require("url");
module.exports = {
// api base url & path
apiHost: "https://api.maildrop.cc",
apiRelativePath: "/v2/mailbox",
// api key for 'x-api-key' header
apiKey: "",
// api key expiry timestamp
apiKeyExpiry: 0,
/**
* async
* @function deleteMail
* @param {String} email="" required, email id
* @param {String} id="" required, individual email object id
* @return {Object} like this { deleted: true }
*/
async deleteMail(email = "", id = "") {
if (!email || !id) throw new Error("invalid args");
const alias = email.replace(/@maildrop.cc$/, "");
const options = {
headers: { "x-api-key": await this.getApiKey() },
method: "DELETE",
};
return await (
await fetch(
url.resolve(this.apiHost, `${this.apiRelativePath}/${alias}/${id}`),
options
)
).json();
},
/**
* async
* @function fetchMails
* @param {String} email="" required, email id
* @return {Object[]} like this { id, from, to, subject, date, body, html }[]
*/
async fetchMails(email = "") {
if (!email) throw new Error("email required");
const alias = email.replace(/@maildrop.cc$/, "");
const mails = [];
const options = { headers: { "x-api-key": await this.getApiKey() } };
const inbox = await (
await fetch(
url.resolve(this.apiHost, `${this.apiRelativePath}/${alias}`),
options
)
).json();
for (const message of inbox.messages) {
const data = await (
await fetch(
url.resolve(
this.apiHost,
`${this.apiRelativePath}/${alias}/${message.id}`
),
options
)
).json();
// contains raw body & html
mails.push(data);
}
// { id, from, to, subject, date, body, html }[]
return mails;
},
/**
* async
* @function getApiKey
* @param {Boolean} force=false optional, for forceful refresh
* @return {String} api key for x-api-key header
*/
async getApiKey(force = false) {
if (force || !this.apiKey || this.apiKeyExpiry < new Date().getTime()) {
const html = await (await fetch(this.webHost)).text();
const js = await (
await fetch(
url.resolve(
this.webHost,
html.match(/([^"]+static\/js\/main[^"]+)/)[1]
)
)
).text();
this.apiKey = js.match(/x-api-key":"([^"]+)/)[1];
this.apiKeyExpiry = new Date().getTime() + 6 * 60 * 60 * 1000; // 6 hour expiration
}
return this.apiKey;
},
// to get web html & js
webHost: "https://maildrop.cc",
};