Files
NodeBB/src/posts/uploads.js

176 lines
5.8 KiB
JavaScript
Raw Normal View History

2018-04-13 16:12:11 -04:00
'use strict';
const nconf = require('nconf');
const crypto = require('crypto');
const path = require('path');
const winston = require('winston');
const mime = require('mime');
const validator = require('validator');
const db = require('../database');
const image = require('../image');
const user = require('../user');
const topics = require('../topics');
const file = require('../file');
const meta = require('../meta');
2018-04-13 16:12:11 -04:00
module.exports = function (Posts) {
Posts.uploads = {};
const md5 = filename => crypto.createHash('md5').update(filename).digest('hex');
const pathPrefix = path.join(nconf.get('upload_path'));
const searchRegex = /\/assets\/uploads\/(files\/[^\s")]+\.?[\w]*)/g;
const _getFullPath = relativePath => path.join(pathPrefix, relativePath);
const _filterValidPaths = async filePaths => (await Promise.all(filePaths.map(async (filePath) => {
const fullPath = _getFullPath(filePath);
return fullPath.startsWith(pathPrefix) && await file.exists(fullPath) ? filePath : false;
}))).filter(Boolean);
2019-07-17 19:05:55 -04:00
Posts.uploads.sync = async function (pid) {
// Scans a post's content and updates sorted set of uploads
2018-04-13 16:12:11 -04:00
const [content, currentUploads, isMainPost] = await Promise.all([
2019-07-17 19:05:55 -04:00
Posts.getPostField(pid, 'content'),
Posts.uploads.list(pid),
Posts.isMain(pid),
2019-07-17 19:05:55 -04:00
]);
2018-04-13 16:12:11 -04:00
2019-07-17 19:05:55 -04:00
// Extract upload file paths from post content
let match = searchRegex.exec(content);
const uploads = [];
while (match) {
uploads.push(match[1].replace('-resized', ''));
match = searchRegex.exec(content);
}
2018-04-13 16:12:11 -04:00
// Main posts can contain topic thumbs, which are also tracked by pid
if (isMainPost) {
const tid = await Posts.getPostField(pid, 'tid');
let thumbs = await topics.thumbs.get(tid);
const replacePath = path.posix.join(`${nconf.get('relative_path')}${nconf.get('upload_url')}/`);
2021-11-03 22:47:15 -04:00
thumbs = thumbs.map(thumb => thumb.url.replace(replacePath, '')).filter(path => !validator.isURL(path, {
require_protocol: true,
}));
uploads.push(...thumbs);
}
2019-07-17 19:05:55 -04:00
// Create add/remove sets
const add = uploads.filter(path => !currentUploads.includes(path));
const remove = currentUploads.filter(path => !uploads.includes(path));
await Promise.all([
Posts.uploads.associate(pid, add),
Posts.uploads.dissociate(pid, remove),
]);
2018-04-13 16:12:11 -04:00
};
2019-07-17 19:05:55 -04:00
Posts.uploads.list = async function (pid) {
2021-02-03 23:59:08 -07:00
return await db.getSortedSetMembers(`post:${pid}:uploads`);
2018-04-13 16:12:11 -04:00
};
Posts.uploads.listWithSizes = async function (pid) {
Async refactor in place (#7736) * feat: allow both callback&and await * feat: ignore async key * feat: callbackify and promisify in same file * Revert "feat: callbackify and promisify in same file" This reverts commit cea206a9b8e6d8295310074b18cc82a504487862. * feat: no need to store .callbackify * feat: change getTopics to async * feat: remove .async * fix: byScore * feat: rewrite topics/index and social with async/await * fix: rewrite topics/data.js fix issue with async.waterfall, only pass result if its not undefined * feat: add callbackify to redis/psql * feat: psql use await * fix: redis :volcano: * feat: less returns * feat: more await rewrite * fix: redis tests * feat: convert sortedSetAdd rewrite psql transaction to async/await * feat: :dog: * feat: test * feat: log client and query * feat: log bind * feat: more logs * feat: more logs * feat: check perform * feat: dont callbackify transaction * feat: remove logs * fix: main functions * feat: more logs * fix: increment * fix: rename * feat: remove cls * fix: remove console.log * feat: add deprecation message to .async usage * feat: update more dbal methods * fix: redis :voodoo: * feat: fix redis zrem, convert setObject * feat: upgrade getObject methods * fix: psql getObjectField * fix: redis tests * feat: getObjectKeys * feat: getObjectValues * feat: isObjectField * fix: add missing return * feat: delObjectField * feat: incrObjectField * fix: add missing await * feat: remove exposed helpers * feat: list methods * feat: flush/empty * feat: delete * fix: redis delete all * feat: get/set * feat: incr/rename * feat: type * feat: expire * feat: setAdd * feat: setRemove * feat: isSetMember * feat: getSetMembers * feat: setCount, setRemoveRandom * feat: zcard,zcount * feat: sortedSetRank * feat: isSortedSetMember * feat: zincrby * feat: sortedSetLex * feat: processSortedSet * fix: add mising await * feat: debug psql * fix: psql test * fix: test * fix: another test * fix: test fix * fix: psql tests * feat: remove logs * feat: user arrow func use builtin async promises * feat: topic bookmarks * feat: topic.delete * feat: topic.restore * feat: topics.purge * feat: merge * feat: suggested * feat: topics/user.js * feat: topics modules * feat: topics/follow * fix: deprecation msg * feat: fork * feat: topics/posts * feat: sorted/recent * feat: topic/teaser * feat: topics/tools * feat: topics/unread * feat: add back node versions disable deprecation notice wrap async controllers in try/catch * feat: use db directly * feat: promisify in place * fix: redis/psql * feat: deprecation message logs for psql * feat: more logs * feat: more logs * feat: logs again * feat: more logs * fix: call release * feat: restore travis, remove logs * fix: loops * feat: remove .async. usage
2019-07-09 12:46:49 -04:00
const paths = await Posts.uploads.list(pid);
2021-02-03 23:59:08 -07:00
const sizes = await db.getObjects(paths.map(path => `upload:${md5(path)}`)) || [];
2019-03-27 23:52:13 -04:00
return sizes.map((sizeObj, idx) => ({
...sizeObj,
name: paths[idx],
}));
};
2019-07-17 19:05:55 -04:00
Posts.uploads.isOrphan = async function (filePath) {
2021-02-03 23:59:08 -07:00
const length = await db.sortedSetCard(`upload:${md5(filePath)}:pids`);
2019-07-17 19:05:55 -04:00
return length === 0;
2018-04-16 16:44:17 -04:00
};
2019-07-17 19:05:55 -04:00
Posts.uploads.getUsage = async function (filePaths) {
// Given an array of file names, determines which pids they are used in
if (!Array.isArray(filePaths)) {
filePaths = [filePaths];
}
const keys = filePaths.map(fileObj => `upload:${md5(fileObj.path.replace('-resized', ''))}:pids`);
2019-07-17 19:05:55 -04:00
return await Promise.all(keys.map(k => db.getSortedSetRange(k, 0, -1)));
};
2019-07-17 19:05:55 -04:00
Posts.uploads.associate = async function (pid, filePaths) {
2018-04-13 16:12:11 -04:00
// Adds an upload to a post's sorted set of uploads
filePaths = !Array.isArray(filePaths) ? [filePaths] : filePaths;
2018-05-19 12:57:59 -04:00
if (!filePaths.length) {
2019-07-17 19:05:55 -04:00
return;
2018-05-19 12:57:59 -04:00
}
filePaths = await _filterValidPaths(filePaths); // Only process files that exist and are within uploads directory
2019-07-17 19:05:55 -04:00
const now = Date.now();
const scores = filePaths.map(() => now);
2021-02-03 23:59:08 -07:00
const bulkAdd = filePaths.map(path => [`upload:${md5(path)}:pids`, now, pid]);
2019-07-17 19:05:55 -04:00
await Promise.all([
2021-02-03 23:59:08 -07:00
db.sortedSetAdd(`post:${pid}:uploads`, scores, filePaths),
2019-07-17 19:05:55 -04:00
db.sortedSetAddBulk(bulkAdd),
Posts.uploads.saveSize(filePaths),
]);
2018-04-13 16:12:11 -04:00
};
2019-07-17 19:05:55 -04:00
Posts.uploads.dissociate = async function (pid, filePaths) {
2018-04-13 16:12:11 -04:00
// Removes an upload from a post's sorted set of uploads
filePaths = !Array.isArray(filePaths) ? [filePaths] : filePaths;
2018-05-19 12:57:59 -04:00
if (!filePaths.length) {
2019-07-17 19:05:55 -04:00
return;
2018-05-19 12:57:59 -04:00
}
2018-04-13 16:12:11 -04:00
2021-02-03 23:59:08 -07:00
const bulkRemove = filePaths.map(path => [`upload:${md5(path)}:pids`, pid]);
const promises = [
2021-02-03 23:59:08 -07:00
db.sortedSetRemove(`post:${pid}:uploads`, filePaths),
2019-07-17 19:05:55 -04:00
db.sortedSetRemoveBulk(bulkRemove),
];
await Promise.all(promises);
if (!meta.config.preserveOrphanedUploads) {
const deletePaths = (await Promise.all(
filePaths.map(async filePath => (await Posts.uploads.isOrphan(filePath) ? filePath : false))
)).filter(Boolean);
const uploaderUids = (await db.getObjectsFields(deletePaths.map(path => `upload:${md5(path)}`, ['uid']))).map(o => (o ? o.uid || null : null));
await Promise.all(uploaderUids.map((uid, idx) => (
uid && isFinite(uid) ? user.deleteUpload(uid, uid, deletePaths[idx]) : null
)).filter(Boolean));
await Posts.uploads.deleteFromDisk(deletePaths);
}
2018-04-13 16:12:11 -04:00
};
2019-09-04 16:58:58 -04:00
Posts.uploads.dissociateAll = async (pid) => {
const current = await Posts.uploads.list(pid);
await Posts.uploads.dissociate(pid, current);
};
Posts.uploads.deleteFromDisk = async (filePaths) => {
if (typeof filePaths === 'string') {
filePaths = [filePaths];
} else if (!Array.isArray(filePaths)) {
throw new Error(`[[error:wrong-parameter-type, filePaths, ${typeof filePaths}, array]]`);
}
filePaths = (await _filterValidPaths(filePaths)).map(_getFullPath);
await Promise.all(filePaths.map(file.delete));
2019-09-04 16:58:58 -04:00
};
Posts.uploads.saveSize = async (filePaths) => {
filePaths = filePaths.filter((fileName) => {
const type = mime.getType(fileName);
return type && type.match(/image./);
});
2021-02-04 00:01:39 -07:00
await Promise.all(filePaths.map(async (fileName) => {
try {
const size = await image.size(_getFullPath(fileName));
2021-02-03 23:59:08 -07:00
await db.setObject(`upload:${md5(fileName)}`, {
2019-07-17 19:05:55 -04:00
width: size.width,
height: size.height,
});
} catch (err) {
2021-02-03 23:59:08 -07:00
winston.error(`[posts/uploads] Error while saving post upload sizes (${fileName}): ${err.message}`);
}
}));
};
2018-04-13 16:12:11 -04:00
};