From b4606c0604eada8cdbd372c33f5faa39912b88d9 Mon Sep 17 00:00:00 2001 From: Adam Soltys Date: Fri, 19 Mar 2021 14:37:06 -0700 Subject: mail checker --- mail.js | 109 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 mail.js (limited to 'mail.js') diff --git a/mail.js b/mail.js new file mode 100644 index 00000000..feb2888a --- /dev/null +++ b/mail.js @@ -0,0 +1,109 @@ +var fs = require("fs"); +var Imap = require("imap"), + inspect = require("util").inspect; + +var imap = new Imap(config.imap); +const persist = require("./lib/persist"); +const emails = persist("data/emails.json"); + +function openInbox(cb) { + imap.openBox("INBOX", true, cb); +} + +setInterval(() => { + imap.once("ready", function() { + openInbox(function(err, box) { + if (err) throw err; + var f = imap.seq.fetch(`${box.messages.total - 5}:*`, { + bodies: ["TEXT"], + struct: true + }); + f.on("message", function(msg, seqno) { + var prefix = "(#" + seqno + ") "; + msg.on("body", function(stream, info) { + var buffer = ""; + stream.on("data", function(chunk) { + //stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt', {flags:'a+'})); + buffer += chunk.toString("utf8"); + }); + stream.once("end", async function() { + if (!emails[seqno] && buffer.includes(config.imap.secret)) { + let amount = buffer.replace(/.*\$(.*)\.\d\d \(CAD\).*/gms, "$1"); + emails[seqno] = amount; + console.log( + seqno, + buffer.replace(/.*\$(.*)\.\d\d \(CAD\).*/gms, "$1") + ); + + try { + await db.transaction(async transaction => { + const account = await db.Account.findOne({ + where: { + user_id: config.imap.user_id, + asset: config.liquid.btcasset, + pubkey: null + }, + include: { + model: db.User, + as: "user", + }, + lock: transaction.LOCK.UPDATE, + transaction + }); + + let { user } = account; + + let rate = app.get("rates")["CAD"]; + console.log(rate); + + await account.increment({ balance: amount }, { transaction }); + let payment = await db.Payment.create({ + account_id: account.id, + user_id: account.user_id, + hash: `Interac deposit: ${amount} CAD`, + amount: Math.round((amount / rate) * 100000000), + currency: "CAD", + rate, + received: true, + tip: 0, + confirmed: true, + address: "", + network: "COINOS" + }); + payment = payment.get({ plain: true }); + payment.account = account.get({ plain: true }); + + emit(user.username, "account", account); + emit(user.username, "payment", payment); + }); + } catch (e) { + console.log(e); + } + } + }); + }); + msg.once("end", function() { + // console.log(prefix + 'Finished'); + }); + + imap.seq.addFlags(seqno, ["Seen"]); + }); + f.once("error", function(err) { + console.log("Fetch error: " + err); + }); + f.once("end", function() { + imap.end(); + }); + }); + }); + + imap.once("error", function(err) { + console.log(err); + }); + + imap.once("end", function() { + console.log("Connection ended"); + }); + + imap.connect(); +}, 30000); -- cgit v1.2.3