Files
NodeBB/src/posts/attachments.js

61 lines
1.5 KiB
JavaScript
Raw Normal View History

'use strict';
const crypto = require('crypto');
2024-06-13 19:49:04 -04:00
const _ = require('lodash');
const db = require('../database');
const Attachments = module.exports;
2024-06-13 19:49:04 -04:00
const posts = require('./index');
Attachments.get = async (pid) => {
2024-06-13 19:49:04 -04:00
const hashes = await posts.getPostField(pid, `attachments`);
return Attachments.getAttachments(hashes);
};
2024-06-13 19:49:04 -04:00
Attachments.getAttachments = async (hashes) => {
const keys = hashes.map(hash => `attachment:${hash}`);
return (await db.getObjects(keys)).filter(Boolean);
};
Attachments.update = async (pid, attachments) => {
if (!attachments) {
return;
}
const bulkOps = {
hash: [],
};
2024-06-13 19:49:04 -04:00
const hashes = [];
2024-06-14 11:49:25 -04:00
attachments.filter(Boolean).forEach(({ _type, mediaType, url, name, width, height }) => {
if (!url) { // only required property
return;
}
const hash = crypto.createHash('sha256').update(url).digest('hex');
const key = `attachment:${hash}`;
if (_type) {
_type = 'attachment';
}
bulkOps.hash.push([key, { _type, mediaType, url, name, width, height }]);
2024-06-13 19:49:04 -04:00
hashes.push(hash);
});
await Promise.all([
db.setObjectBulk(bulkOps.hash),
2024-06-13 19:49:04 -04:00
db.setObjectField(`post:${pid}`, 'attachments', hashes.join(',')),
]);
};
Attachments.empty = async (pids) => {
2024-06-13 19:49:04 -04:00
const postKeys = pids.map(pid => `post:${pid}`);
const hashes = await posts.getPostsFields(postKeys, ['attachments']);
const keys = _.uniq(_.flatten(hashes));
await Promise.all([
db.deleteAll(keys.map(hash => `attachment:${hash}`)),
db.deleteObjectFields(postKeys, ['attachments']),
]);
};