2016-06-30 10:13:56 +08:00
|
|
|
const IMAPConnection = require('../../imap-connection')
|
|
|
|
const NylasError = require('../../nylas-error')
|
|
|
|
|
2016-06-29 02:32:15 +08:00
|
|
|
module.exports = (sequelize, Sequelize) => {
|
2016-06-30 01:36:32 +08:00
|
|
|
const File = sequelize.define('file', {
|
|
|
|
accountId: { type: Sequelize.STRING, allowNull: false },
|
2016-06-30 02:22:38 +08:00
|
|
|
version: Sequelize.INTEGER,
|
2016-06-29 04:55:00 +08:00
|
|
|
filename: Sequelize.STRING,
|
2016-06-30 10:13:56 +08:00
|
|
|
partId: Sequelize.STRING,
|
2016-06-29 04:55:00 +08:00
|
|
|
contentType: Sequelize.STRING,
|
2016-06-29 02:32:15 +08:00
|
|
|
size: Sequelize.INTEGER,
|
|
|
|
}, {
|
|
|
|
classMethods: {
|
|
|
|
associate: ({Message}) => {
|
|
|
|
File.belongsTo(Message)
|
|
|
|
},
|
|
|
|
},
|
2016-06-29 04:55:00 +08:00
|
|
|
instanceMethods: {
|
2016-06-30 10:13:56 +08:00
|
|
|
fetch: function fetch({account, db}) {
|
|
|
|
const settings = Object.assign({}, account.connectionSettings, account.decryptedCredentials())
|
|
|
|
return Promise.props({
|
|
|
|
message: this.getMessage(),
|
|
|
|
connection: IMAPConnection.connect(db, settings),
|
|
|
|
})
|
|
|
|
.then(({message, connection}) => {
|
2016-07-01 00:29:21 +08:00
|
|
|
return message.getFolder()
|
|
|
|
.then((folder) => connection.openBox(folder.name))
|
2016-06-30 10:13:56 +08:00
|
|
|
.then((imapBox) => imapBox.fetchStream({
|
2016-07-01 00:33:04 +08:00
|
|
|
uid: message.folderImapUID,
|
2016-06-30 10:13:56 +08:00
|
|
|
options: {
|
|
|
|
bodies: [this.partId],
|
|
|
|
struct: true,
|
2016-07-01 00:29:21 +08:00
|
|
|
},
|
2016-06-30 10:13:56 +08:00
|
|
|
}))
|
|
|
|
.then((stream) => {
|
|
|
|
if (stream) {
|
|
|
|
return Promise.resolve(stream)
|
|
|
|
}
|
|
|
|
return Promise.reject(new NylasError(`Unable to fetch binary data for File ${this.id}`))
|
|
|
|
})
|
|
|
|
.finally(() => connection.end())
|
|
|
|
})
|
|
|
|
},
|
2016-06-29 04:55:00 +08:00
|
|
|
toJSON: function toJSON() {
|
|
|
|
return {
|
|
|
|
id: this.id,
|
2016-06-29 09:14:54 +08:00
|
|
|
object: 'file',
|
2016-06-30 01:36:32 +08:00
|
|
|
account_id: this.accountId,
|
|
|
|
message_id: this.messageId,
|
2016-06-29 04:55:00 +08:00
|
|
|
filename: this.filename,
|
2016-06-30 10:13:56 +08:00
|
|
|
part_id: this.partId,
|
2016-06-30 01:36:32 +08:00
|
|
|
content_type: this.contentType,
|
2016-06-29 04:55:00 +08:00
|
|
|
size: this.size,
|
|
|
|
};
|
|
|
|
},
|
|
|
|
},
|
2016-06-29 02:32:15 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
return File;
|
|
|
|
};
|