Last active
December 18, 2017 22:12
-
-
Save guidouil/815599e154f68dc55fda850132c115b8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Server side route to read data-form comming from mailgun | |
// /imports/startup/server/routes.js | |
import { Meteor } from 'meteor/meteor'; | |
import { WebApp } from 'meteor/webapp'; | |
import formidable from 'formidable'; | |
import ical from 'ical'; | |
import fs from 'fs'; | |
const newSurveyFromMail = Meteor.bindEnvironment((senderMail, event) => { | |
Meteor.call('newSurveyFromMail', senderMail, event); | |
}); | |
WebApp.connectHandlers.use('/incomingmail', (request, response, next) => { | |
// create temp dir if !exist | |
const path = '/tmp'; | |
if (!fs.existsSync(path)) { | |
fs.mkdirSync(path); | |
} | |
if (request && request.headers && request.headers['user-agent'] && request.headers['user-agent'].includes('mailgun')) { | |
const form = new formidable.IncomingForm({ uploadDir: path }); | |
form.parse(request, (err, fields, files) => { | |
if (err) { | |
console.log('err:', err); | |
} | |
// we are only looking for mail with ics attached | |
if (files && files['attachment-1'] && files['attachment-1'].name.includes('.ics')) { | |
let event; | |
const ics = ical.parseFile(files['attachment-1'].path); | |
// remove id container of ics, just need root object | |
for (const key in ics) { | |
if (ics.hasOwnProperty(key)) { | |
event = ics[key]; | |
} | |
} | |
let senderMail = fields.From; | |
// Correct if mail format is like: Full Name <full.name@domain.com> | |
if (senderMail.includes('<')) { | |
const mailParts = senderMail.split('<'); | |
senderMail = mailParts[1].slice(0, -1); | |
} | |
// Call Meteor method | |
newSurveyFromMail(senderMail, event); | |
} | |
response.statusCode = 200; | |
response.end(); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment