UNPKG

grabbed

Version:

grabs emails and pulls attachments and dumps into a folder.

113 lines (97 loc) 3.14 kB
// Generated by CoffeeScript 1.6.3 var MailParser, async, dateFormat, dropboxDir, fs, md5, mkdirp, os, path, q, userHome, _; fs = require("fs"); path = require("path"); os = require("os"); md5 = require('MD5'); _ = require("underscore"); mkdirp = require("mkdirp").sync; MailParser = require("mailparser").MailParser; dateFormat = require("dateformat"); async = require("async"); if (os.platform() === "win32") { userHome = process.env.USERPROFILE; } else { userHome = process.env.HOME; } dropboxDir = path.join(userHome, 'Dropbox', 'CCTV', 'motion_clips'); mkdirp(dropboxDir); q = async.queue(function(task, callback) { var file, nextJob, parseFile, parser, readFile, rmFile, writeImages; nextJob = callback; parser = new MailParser(); file = task; readFile = function(next) { var doneFullPath, donePath, email, filePath, fullPath; console.log("Reading email file... " + task); filePath = path.join(process.cwd(), 'messages'); fullPath = path.join(filePath, file); donePath = path.resolve(filePath, "./parsed"); doneFullPath = path.join(donePath, file); console.log(fullPath); email = fs.readFileSync(fullPath); console.log("Done reading email " + task + "."); return next(null, email); }; parseFile = function(email, next) { console.log("parsing file..."); parser.on("end", function(mail_object) { return next(null, mail_object); }); parser.write(email); return parser.end(); }; writeImages = function(msg, next) { var attachments, msgDate, processAttachment; msgDate = new Date(msg.headers.date); processAttachment = function(attachment, callback) { var fileDate, fileExt, fileName, filePath, fileTime, fullFilePath; fileExt = path.extname(attachment.fileName); fileDate = dateFormat(msgDate, 'yyyy-mm-dd'); fileTime = dateFormat(msgDate, 'HHMMss'); fileName = fileTime + "_" + md5(attachment.fileName) + fileExt; filePath = path.join(dropboxDir, fileDate); mkdirp(filePath); fullFilePath = path.join(filePath, fileName); return fs.writeFile(fullFilePath, attachment.content, function(err) { return callback(null); }); }; attachments = msg.attachments; return async.eachSeries(attachments, processAttachment, function(err) { if (err != null) { throw err; } return next(null); }); }; rmFile = function(callback) { readFile = path.join(process.cwd(), 'messages', task); return fs.unlink(readFile, function(err) { if (err != null) { throw err; } return callback(); }); }; return async.waterfall([readFile, parseFile, writeImages, rmFile], function(err, result) { if (err != null) { throw err; } return nextJob(); }); }, 1); q.drain = function() { console.log("all MESSAGES have been processed"); process.exit(); }; fs.readdir('./messages', function(err, files) { if (err != null) { throw err; } return _.each(files, function(file) { return q.push(file, function(err) { console.log("finished processing email"); }); }); });