Switch from hashed to random attachment file names

Using hashes, we get the benefit of deduplication but if a user receives two
messages with the same attachment, deleting one would delete it for both since
they are only stored once. To avoid the complexity of tracking number of
references, we simply generate random file names similar to iMessage on MacOS
(?) and Signal Android.
This commit is contained in:
Daniel Gasienica 2018-03-13 17:42:12 -04:00
parent d9de6dacba
commit 1283c77518
2 changed files with 17 additions and 31 deletions

View file

@ -1,7 +1,6 @@
const crypto = require('crypto');
const FSE = require('fs-extra');
const isArrayBuffer = require('lodash/isArrayBuffer');
const isBuffer = require('lodash/isBuffer');
const isString = require('lodash/isString');
const Path = require('path');
@ -17,29 +16,20 @@ exports.writeAttachmentData = (root) => {
}
const buffer = new Buffer(arrayBuffer);
const path = Path.join(root, exports._getAttachmentPath(buffer));
const path = Path.join(root, exports._getAttachmentPath());
await FSE.ensureFile(path);
await FSE.writeFile(path, buffer);
return path;
};
};
exports._getAttachmentName = (buffer) => {
if (!isBuffer(buffer)) {
throw new TypeError('`buffer` must be a buffer');
}
const hash = crypto.createHash('sha256');
hash.update(buffer);
return hash.digest('hex');
exports._getAttachmentName = () => {
const buffer = crypto.randomBytes(32);
return buffer.toString('hex');
};
exports._getAttachmentPath = (buffer) => {
if (!isBuffer(buffer)) {
throw new TypeError('`buffer` must be a buffer');
}
const name = exports._getAttachmentName(buffer);
exports._getAttachmentPath = () => {
const name = exports._getAttachmentName();
const prefix = name.slice(0, 3);
return Path.join(prefix, name);
};