From 551daa141b93f6e85ed8685cda5a3c2eb2701f27 Mon Sep 17 00:00:00 2001 From: Julian Lam Date: Fri, 13 Apr 2018 16:12:11 -0400 Subject: [PATCH] basic methods for #6455 --- src/posts.js | 1 + src/posts/uploads.js | 61 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/posts/uploads.js diff --git a/src/posts.js b/src/posts.js index 6061017b89..2b4e19dfb5 100644 --- a/src/posts.js +++ b/src/posts.js @@ -26,6 +26,7 @@ require('./posts/votes')(Posts); require('./posts/bookmarks')(Posts); require('./posts/queue')(Posts); require('./posts/diffs')(Posts); +require('./posts/uploads')(Posts); Posts.exists = function (pid, callback) { db.isSortedSetMember('posts:pid', pid, callback); diff --git a/src/posts/uploads.js b/src/posts/uploads.js new file mode 100644 index 0000000000..42c90477a9 --- /dev/null +++ b/src/posts/uploads.js @@ -0,0 +1,61 @@ +'use strict'; + +var async = require('async'); + +var db = require('../database'); + +module.exports = function (Posts) { + Posts.uploads = {}; + + Posts.uploads.sync = function (pid, callback) { + // Scans a post and updates sorted set of uploads + const searchRegex = /\/assets\/uploads\/files\/([^\s]+\.[\w]+)/g; + + async.parallel({ + content: async.apply(Posts.getPostField, pid, 'content'), + uploads: async.apply(Posts.uploads.list, pid), + }, function (err, data) { + if (err) { + return callback(err); + } + + // Extract upload file paths from post content + let match = searchRegex.exec(data.content); + const uploads = []; + while (match) { + uploads.push(match[1]); + match = searchRegex.exec(data.content); + } + + // Create add/remove sets + const add = uploads.filter(path => !data.uploads.includes(path)); + const remove = data.uploads.filter(path => !uploads.includes(path)); + + async.parallel([ + async.apply(Posts.uploads.associate, pid, add), + async.apply(Posts.uploads.dissociate, pid, remove), + ], callback); + }); + }; + + Posts.uploads.list = function (pid, callback) { + // Returns array of this post's uploads + db.getSortedSetRange('post:' + pid + ':uploads', 0, -1, callback); + }; + + Posts.uploads.associate = function (pid, filePaths, callback) { + // Adds an upload to a post's sorted set of uploads + const now = Date.now(); + const scores = filePaths.map(() => now); + filePaths = !Array.isArray(filePaths) ? [filePaths] : filePaths; + + db.sortedSetAdd('post:' + pid + ':uploads', scores, filePaths, callback); + }; + + Posts.uploads.dissociate = function (pid, filePaths, callback) { + // Removes an upload from a post's sorted set of uploads + filePaths = !Array.isArray(filePaths) ? [filePaths] : filePaths; + + db.sortedSetRemove('post:' + pid + ':uploads', filePaths, callback); + }; +};