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

61 lines
1.8 KiB
JavaScript
Raw Normal View History

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) => {
const File = sequelize.define('file', {
accountId: { type: Sequelize.STRING, allowNull: false },
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}) => {
return message.getFolder()
.then((folder) => connection.openBox(folder.name))
2016-06-30 10:13:56 +08:00
.then((imapBox) => imapBox.fetchStream({
uid: message.folderImapUID,
2016-06-30 10:13:56 +08:00
options: {
bodies: [this.partId],
struct: true,
},
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',
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,
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;
};