/
index.js
87 lines (74 loc) · 2.26 KB
/
index.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
const { EventEmitter } = require('events');
/**
* start create new mail
* @returns JSON
*/
async function getRandomMail() {
const mail = (await getMailApi())[0]
const event = new EventEmitter()
getMailMessage(mail, event)
return {
mail, event
}
}
/**
* 1secmail.com api process
* @param advanced {boolean} - Create new message or another action
* @param username {string} - username of mail
* @param domain {string} - domain of mail
* @param id {int} - id of mail message
*/
async function getMailApi(advanced = true, username, domain, id) {
var response;
if (advanced) {
response = await (await fetch('https://www.1secmail.com/api/v1/?action=genRandomMailbox')).json();
} else {
response = await (await fetch(`https://www.1secmail.com/api/v1/?action=${id ? "readMessage" : "getMessages"}&login=${username}&domain=${domain}${id ? `&id=${id}` : ""}`)).json();
}
return response
}
/**
* Process new mail
* @param mail {string} - Mail username and domain
* @param event {EventEmitter} - Event message
*/
function getMailMessage(mail, event) {
var lastID = []
setInterval(async () => {
const [username, domain] = mail.split('@')
const msgs = await getMailApi(false, username, domain)
if (!msgs.length) return null;
msgs.filter(msg => !lastID.includes(msg.id)).map(async (msg) => {
var message = await getMailApi(false, username, domain, msg.id)
lastID.push(msg.id)
event.emit('newMsg', messageModel(message))
})
}, 3000)
}
/**
* Returns the model of message
* @returns json
*/
function messageModel(json, username, domain, model = {}) {
model.id = json.id
model.sender = json.from
model.subject = json.subject
model.date = new Date(json.date)
model.msgBody = json.body
model.msgText = json.textBody
model.attachments = json.attachments.filter(
(attachment) =>
"filename" in attachment &&
"size" in attachment &&
"contentType" in attachment
).map(v => {
return {
fileName: v.filename,
fileSize: v.size,
fileContentType: v.contentType,
fileUrl: `https://www.1secmail.com/api/v1/?action=download&login=${username}&domain=${domain}&id=${json.id}&file=${v.filename}`
}
})
return model
}
module.exports = getRandomMail