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

78 lines
2.3 KiB
JavaScript
Raw Normal View History

const crypto = require('crypto');
const IMAPConnection = require('../../imap-connection')
const NylasError = require('../../nylas-error')
const {JSONType, JSONARRAYType} = require('../../database-types');
2016-06-19 18:02:32 +08:00
module.exports = (sequelize, Sequelize) => {
const Message = sequelize.define('Message', {
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-29 02:32:15 +08:00
associate: ({Category, File, Thread}) => {
Message.belongsTo(Category)
2016-06-29 02:32:15 +08:00
Message.hasMany(File, {as: 'files'})
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: {
2016-06-28 01:27:38 +08:00
fetchRaw: function fetchRaw({account, db}) {
const settings = Object.assign({}, account.connectionSettings, account.decryptedCredentials())
return Promise.props({
category: this.getCategory(),
connection: IMAPConnection.connect(db, settings),
})
.then(({category, connection}) => {
return connection.openBox(category.name)
.then((imapBox) => imapBox.fetchMessage(this.CategoryUID))
.then((message) => {
if (message) {
return Promise.resolve(`${message.headers}${message.body}`)
}
return Promise.reject(new NylasError(`Unable to fetch raw message for Message ${this.id}`))
})
.finally(() => connection.end())
})
},
2016-06-28 01:27:38 +08:00
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;
};