diff --git a/src/js/dao/email-dao.js b/src/js/dao/email-dao.js index bd9db48..b072d48 100644 --- a/src/js/dao/email-dao.js +++ b/src/js/dao/email-dao.js @@ -157,7 +157,9 @@ define(function(require) { */ EmailDAO.prototype.imapGetMessage = function(options, callback) { var self = this, - message; + expectedItems, + itemCounter = 0, + message, attachments = []; // validate options if (!options.folder || !options.uid) { @@ -169,10 +171,29 @@ define(function(require) { function messageReady(err, gottenMessage) { message = gottenMessage; + itemCounter++; + // remember how many items should be fetched before the callback fires + expectedItems = (message.attachments instanceof Array) ? message.attachments.length + 1 : 1; + check(); } - function attachmentReady(err, attmt) { - message.parsedAttachment = attmt; + function attachmentReady(err, gottenAttachment) { + // parse uint8array to base to make it serializable for postMessage + gottenAttachment.base64 = btoa(gottenAttachment.uint8Array); + delete gottenAttachment.uint8Array; + + attachments.push(gottenAttachment); + itemCounter++; + check(); + } + + function check() { + // go for another round you don't yet know how mich to fetch or you haven't fetch enough + if (!expectedItems || itemCounter < expectedItems) { + return; + } + + message.attachments = (attachments.length > 0) ? attachments : undefined; callback(null, message); } diff --git a/test/new-unit/email-dao-test.js b/test/new-unit/email-dao-test.js index 2f8c372..34929d1 100644 --- a/test/new-unit/email-dao-test.js +++ b/test/new-unit/email-dao-test.js @@ -172,6 +172,24 @@ define(function(require) { }); }); + it('should parse message body without attachement', function(done) { + var uid = 415; + + imapClientStub.getMessage.yields(null, { + uid: uid + }); + emailDao.imapGetMessage({ + folder: 'INBOX', + uid: uid + }, function(err, message) { + expect(imapClientStub.getMessage.calledOnce).to.be.true; + expect(err).to.not.exist; + expect(message.uid).to.equal(uid); + expect(message.attachments).to.not.exist; + done(); + }); + }); + it('should parse message body and attachement', function(done) { var uid = 415, newImapClientStub = { @@ -179,7 +197,8 @@ define(function(require) { }; sinon.stub(newImapClientStub, 'getMessage', function(options, messageReady, attachmentReady) { messageReady(null, { - uid: uid + uid: uid, + attachments: ['file.txt'] }); attachmentReady(null, { uint8Array: new Uint8Array(42) @@ -194,7 +213,7 @@ define(function(require) { expect(newImapClientStub.getMessage.calledOnce).to.be.true; expect(err).to.not.exist; expect(message.uid).to.equal(uid); - expect(message.parsedAttachment.uint8Array.length).to.equal(42); + expect(message.attachments[0].base64).to.exist; emailDao._imapClient = imapClientStub; done(); });