Mailspring/packages/nylas-core/models/account/message.js

79 lines
2.2 KiB
JavaScript
Raw Normal View History

const crypto = require('crypto');
const IMAPConnection = require('../../imap-connection')
const {JSONType, JSONARRAYType} = require('../../database-types');
2016-06-19 18:02:32 +08:00
module.exports = (sequelize, Sequelize) => {
const Message = sequelize.define('Message', {
rawBody: Sequelize.STRING,
rawHeaders: Sequelize.STRING,
messageId: Sequelize.STRING,
body: Sequelize.STRING,
2016-06-22 08:25:25 +08:00
headers: JSONType('headers'),
2016-06-19 18:02:32 +08:00
subject: Sequelize.STRING,
snippet: Sequelize.STRING,
hash: Sequelize.STRING,
2016-06-19 18:02:32 +08:00
date: Sequelize.DATE,
unread: Sequelize.BOOLEAN,
starred: Sequelize.BOOLEAN,
processed: Sequelize.INTEGER,
to: JSONARRAYType('to'),
from: JSONARRAYType('from'),
cc: JSONARRAYType('cc'),
bcc: JSONARRAYType('bcc'),
CategoryUID: { type: Sequelize.STRING, allowNull: true},
2016-06-19 18:02:32 +08:00
}, {
indexes: [
{
unique: true,
fields: ['hash'],
},
],
2016-06-19 18:02:32 +08:00
classMethods: {
2016-06-23 08:34:21 +08:00
associate: ({Category, Thread}) => {
Message.belongsTo(Category)
2016-06-23 08:34:21 +08:00
Message.belongsTo(Thread)
2016-06-19 18:02:32 +08:00
},
hashForHeaders: (headers) => {
return crypto.createHash('sha256').update(headers, 'utf8').digest('hex');
},
2016-06-19 18:02:32 +08:00
},
2016-06-23 05:17:45 +08:00
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
})
})
},
2016-06-23 05:17:45 +08:00
toJSON: function toJSON() {
return {
id: this.id,
body: this.body,
subject: this.subject,
snippet: this.snippet,
date: this.date.getTime() / 1000.0,
unread: this.unread,
starred: this.starred,
category_id: this.CategoryId,
};
},
},
2016-06-19 18:02:32 +08:00
});
return Message;
};