2017-08-07 02:25:10 +08:00
|
|
|
'use strict';
|
|
|
|
|
2017-08-07 16:29:29 +08:00
|
|
|
const GridstoreStorage = require('./attachments/gridstore-storage.js');
|
2017-08-07 02:25:10 +08:00
|
|
|
const crypto = require('crypto');
|
|
|
|
let cryptoAsync;
|
|
|
|
try {
|
|
|
|
cryptoAsync = require('@ronomon/crypto-async'); // eslint-disable-line global-require
|
|
|
|
} catch (E) {
|
|
|
|
// ignore
|
|
|
|
}
|
|
|
|
|
|
|
|
class AttachmentStorage {
|
|
|
|
constructor(options) {
|
2017-08-07 16:29:29 +08:00
|
|
|
this.options = options || {};
|
|
|
|
|
|
|
|
let type = (options.options && options.options.type) || 'gridstore';
|
|
|
|
|
|
|
|
switch (type) {
|
|
|
|
case 'gridstore':
|
|
|
|
default:
|
|
|
|
this.storage = new GridstoreStorage(this.options);
|
|
|
|
break;
|
|
|
|
}
|
2017-08-07 02:25:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
get(attachmentId, callback) {
|
2017-08-07 16:29:29 +08:00
|
|
|
return this.storage.get(attachmentId, callback);
|
2017-08-07 02:25:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
create(attachment, callback) {
|
|
|
|
this.calculateHash(attachment.body, (err, hash) => {
|
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
|
|
|
}
|
2017-08-07 16:29:29 +08:00
|
|
|
return this.storage.create(attachment, hash, callback);
|
2017-08-07 02:25:10 +08:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-09-18 16:18:34 +08:00
|
|
|
createReadStream(id, attachmentData) {
|
|
|
|
return this.storage.createReadStream(id, attachmentData);
|
2017-08-07 02:25:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
deleteMany(ids, magic, callback) {
|
|
|
|
let pos = 0;
|
|
|
|
let deleteNext = () => {
|
|
|
|
if (pos >= ids.length) {
|
|
|
|
return callback(null, true);
|
|
|
|
}
|
|
|
|
let id = ids[pos++];
|
|
|
|
this.delete(id, magic, deleteNext);
|
|
|
|
};
|
|
|
|
deleteNext();
|
|
|
|
}
|
|
|
|
|
|
|
|
updateMany(ids, count, magic, callback) {
|
2017-08-07 16:29:29 +08:00
|
|
|
this.storage.update(ids, count, magic, callback);
|
2017-08-07 02:25:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
delete(id, magic, callback) {
|
2017-08-07 16:29:29 +08:00
|
|
|
this.storage.delete(id, magic, callback);
|
|
|
|
}
|
2017-08-07 02:25:10 +08:00
|
|
|
|
2017-08-07 16:29:29 +08:00
|
|
|
deleteOrphaned(callback) {
|
|
|
|
this.storage.deleteOrphaned(callback);
|
2017-08-07 02:25:10 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
calculateHash(input, callback) {
|
|
|
|
let algo = 'sha256';
|
|
|
|
|
|
|
|
if (!cryptoAsync) {
|
2017-09-18 16:18:34 +08:00
|
|
|
setImmediate(() =>
|
|
|
|
callback(
|
|
|
|
null,
|
|
|
|
crypto
|
|
|
|
.createHash(algo)
|
|
|
|
.update(input)
|
|
|
|
.digest('hex')
|
|
|
|
)
|
|
|
|
);
|
2017-08-07 02:25:10 +08:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
cryptoAsync.hash(algo, input, (err, hash) => {
|
|
|
|
if (err) {
|
|
|
|
return callback(err);
|
|
|
|
}
|
|
|
|
return callback(null, hash.toString('hex'));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = AttachmentStorage;
|