From caaef8d5b56f74037463a33ada30cd03732000e8 Mon Sep 17 00:00:00 2001 From: Juan Tejada Date: Sat, 25 Jun 2016 11:24:49 -0700 Subject: [PATCH] Add /messages/ enpoint + support for raw message/rfc822 - When message/rfc822 is requested, fetch ray message from IMAP connection --- packages/nylas-api/routes/messages.js | 43 +++++++++++++++++++ packages/nylas-core/models/account/message.js | 22 ++++++++++ 2 files changed, 65 insertions(+) diff --git a/packages/nylas-api/routes/messages.js b/packages/nylas-api/routes/messages.js index fb898371c..219f21349 100644 --- a/packages/nylas-api/routes/messages.js +++ b/packages/nylas-api/routes/messages.js @@ -1,6 +1,7 @@ const Joi = require('joi'); const Serialization = require('../serialization'); + module.exports = (server) => { server.route({ method: 'GET', @@ -33,4 +34,46 @@ module.exports = (server) => { }) }, }); + + server.route({ + method: 'GET', + path: '/messages/{id}', + config: { + description: 'Returns message for specified id.', + notes: 'Notes go here', + tags: ['messages'], + validate: { + params: { + id: Joi.string(), + }, + }, + response: { + schema: Joi.alternatives().try( + Serialization.jsonSchema('Message'), + Joi.string() + ), + }, + }, + handler: (request, reply) => { + request.getAccountDatabase() + .then((db) => { + const {headers: {accept}} = request + const {params: {id}} = request + const account = request.auth.credentials + const query = db.Message.findOne({where: {id}}) + + if (accept === 'message/rfc822') { + query.then((message) => { + message.fetchRaw({account, db}) + .then((raw) => reply(raw)) + .catch((error) => console.log(error)) + }) + } else { + query.then((message) => { + reply(Serialization.jsonStringify(message)); + }) + } + }) + }, + }) }; diff --git a/packages/nylas-core/models/account/message.js b/packages/nylas-core/models/account/message.js index d43f8ce3b..63046bd75 100644 --- a/packages/nylas-core/models/account/message.js +++ b/packages/nylas-core/models/account/message.js @@ -1,6 +1,8 @@ const crypto = require('crypto'); +const IMAPConnection = require('../../imap-connection') const {JSONType, JSONARRAYType} = require('../../database-types'); + module.exports = (sequelize, Sequelize) => { const Message = sequelize.define('Message', { rawBody: Sequelize.STRING, @@ -37,6 +39,26 @@ module.exports = (sequelize, Sequelize) => { }, }, instanceMethods: { + fetchRaw({account, db}) { + return this.getCategory() + .then((category) => { + const settings = Object.assign({}, account.connectionSettings, account.decryptedCredentials()) + const conn = new IMAPConnection(db, settings) + return conn.connect() + .then(() => conn.openBox(category.name)) + .then(() => { + return new Promise((resolve) => { + conn.fetchMessages([this.CategoryUID], (attributes, headers, body) => { + resolve(`${headers}${body}`) + }) + }) + }) + .then((raw) => { + conn.end() + return raw + }) + }) + }, toJSON: function toJSON() { return { id: this.id,