feat: #7743, user/digest, user/email, user/follow

v1.18.x
Barış Soner Uşaklı 6 years ago
parent 13aaf07bf5
commit c610eb1430

@ -14,112 +14,71 @@ var utils = require('../utils');
var Digest = module.exports; var Digest = module.exports;
Digest.execute = function (payload, callback) { Digest.execute = async function (payload) {
callback = callback || function () {}; const digestsDisabled = meta.config.disableEmailSubscriptions === 1;
var digestsDisabled = meta.config.disableEmailSubscriptions === 1;
if (digestsDisabled) { if (digestsDisabled) {
winston.info('[user/jobs] Did not send digests (' + payload.interval + ') because subscription system is disabled.'); winston.info('[user/jobs] Did not send digests (' + payload.interval + ') because subscription system is disabled.');
return callback(); return;
} }
let subscribers = payload.subscribers;
async.waterfall([ if (!subscribers) {
function (next) { subscribers = await Digest.getSubscribers(payload.interval);
if (payload.subscribers) {
setImmediate(next, undefined, payload.subscribers);
} else {
Digest.getSubscribers(payload.interval, next);
} }
},
function (subscribers, next) {
if (!subscribers.length) { if (!subscribers.length) {
return callback(); return;
} }
try {
var data = { const count = await Digest.send({
interval: payload.interval, interval: payload.interval,
subscribers: subscribers, subscribers: subscribers,
}; });
Digest.send(data, next);
},
], function (err, count) {
if (err) {
winston.error('[user/jobs] Could not send digests (' + payload.interval + ')', err);
} else {
winston.info('[user/jobs] Digest (' + payload.interval + ') scheduling completed. ' + count + ' email(s) sent.'); winston.info('[user/jobs] Digest (' + payload.interval + ') scheduling completed. ' + count + ' email(s) sent.');
} catch (err) {
winston.error('[user/jobs] Could not send digests (' + payload.interval + ')', err);
throw err;
} }
callback(err);
});
}; };
Digest.getSubscribers = function (interval, callback) { Digest.getSubscribers = async function (interval) {
async.waterfall([ var subscribers = [];
function (next) {
var subs = [];
batch.processSortedSet('users:joindate', function (uids, next) { await batch.processSortedSet('users:joindate', async function (uids) {
async.waterfall([ const settings = await user.getMultipleUserSettings(uids);
function (next) { let subUids = [];
user.getMultipleUserSettings(uids, next);
},
function (settings, next) {
const subUids = [];
settings.forEach(function (hash) { settings.forEach(function (hash) {
if (hash.dailyDigestFreq === interval) { if (hash.dailyDigestFreq === interval) {
subUids.push(hash.uid); subUids.push(hash.uid);
} }
}); });
user.bans.filterBanned(subUids, next); subUids = await user.bans.filterBanned(subUids);
}, subscribers = subscribers.concat(subUids);
function (uids, next) { }, { interval: 1000 });
subs = subs.concat(uids);
next(); const results = await plugins.fireHook('filter:digest.subscribers', {
},
], next);
}, { interval: 1000 }, function (err) {
next(err, subs);
});
},
function (subscribers, next) {
plugins.fireHook('filter:digest.subscribers', {
interval: interval, interval: interval,
subscribers: subscribers, subscribers: subscribers,
}, next); });
}, return results.subscribers;
function (results, next) {
next(null, results.subscribers);
},
], callback);
}; };
Digest.send = function (data, callback) { Digest.send = async function (data) {
var emailsSent = 0; var emailsSent = 0;
if (!data || !data.subscribers || !data.subscribers.length) { if (!data || !data.subscribers || !data.subscribers.length) {
return callback(null, emailsSent); return emailsSent;
} }
var now = new Date(); const now = new Date();
async.waterfall([ const users = await user.getUsersFields(data.subscribers, ['uid', 'username', 'userslug', 'lastonline']);
function (next) {
user.getUsersFields(data.subscribers, ['uid', 'username', 'userslug', 'lastonline'], next);
},
function (users, next) {
async.eachLimit(users, 100, function (userObj, next) {
async.waterfall([
function (next) {
async.parallel({
notifications: async.apply(user.notifications.getDailyUnread, userObj.uid),
topics: async.apply(getTermTopics, data.interval, userObj.uid, 0, 9),
}, next);
},
function (data, next) {
var notifications = data.notifications.filter(Boolean);
async.eachLimit(users, 100, async function (userObj) {
let [notifications, topics] = await Promise.all([
user.notifications.getDailyUnread(userObj.uid),
getTermTopics(data.interval, userObj.uid, 0, 9),
]);
notifications = notifications.filter(Boolean);
// If there are no notifications and no new topics, don't bother sending a digest // If there are no notifications and no new topics, don't bother sending a digest
if (!notifications.length && !data.topics.length) { if (!notifications.length && !topics.length) {
return next(); return;
} }
notifications.forEach(function (notification) { notifications.forEach(function (notification) {
@ -129,12 +88,11 @@ Digest.send = function (data, callback) {
}); });
// Fix relative paths in topic data // Fix relative paths in topic data
data.topics = data.topics.map(function (topicObj) { topics = topics.map(function (topicObj) {
var user = topicObj.hasOwnProperty('teaser') && topicObj.teaser !== undefined ? topicObj.teaser.user : topicObj.user; const user = topicObj.hasOwnProperty('teaser') && topicObj.teaser !== undefined ? topicObj.teaser.user : topicObj.user;
if (user && user.picture && utils.isRelativeUrl(user.picture)) { if (user && user.picture && utils.isRelativeUrl(user.picture)) {
user.picture = nconf.get('base_url') + user.picture; user.picture = nconf.get('base_url') + user.picture;
} }
return topicObj; return topicObj;
}); });
emailsSent += 1; emailsSent += 1;
@ -151,16 +109,11 @@ Digest.send = function (data, callback) {
winston.error('[user/jobs] Could not send digest email', err); winston.error('[user/jobs] Could not send digest email', err);
} }
}); });
next();
},
], next);
}, next);
},
], function (err) {
callback(err, emailsSent);
}); });
return emailsSent;
};
function getTermTopics(term, uid, start, stop, callback) { async function getTermTopics(term, uid, start, stop) {
const options = { const options = {
uid: uid, uid: uid,
start: start, start: start,
@ -169,27 +122,14 @@ Digest.send = function (data, callback) {
sort: 'posts', sort: 'posts',
teaserPost: 'last-post', teaserPost: 'last-post',
}; };
let data = await topics.getSortedTopics(options);
async.waterfall([
function (next) {
topics.getSortedTopics(options, next);
},
function (data, next) {
if (!data.topics.length) { if (!data.topics.length) {
topics.getLatestTopics(options, next); data = await topics.getLatestTopics(options);
} else {
next(null, data);
} }
},
(data, next) => {
data.topics.forEach(function (topicObj) { data.topics.forEach(function (topicObj) {
if (topicObj && topicObj.teaser && topicObj.teaser.content && topicObj.teaser.content.length > 255) { if (topicObj && topicObj.teaser && topicObj.teaser.content && topicObj.teaser.content.length > 255) {
topicObj.teaser.content = topicObj.teaser.content.slice(0, 255) + '...'; topicObj.teaser.content = topicObj.teaser.content.slice(0, 255) + '...';
} }
}); });
return data.topics;
next(null, data.topics); }
},
], callback);
}
};

@ -1,7 +1,6 @@
'use strict'; 'use strict';
var async = require('async');
var nconf = require('nconf'); var nconf = require('nconf');
var user = require('../user'); var user = require('../user');
@ -13,30 +12,24 @@ var emailer = require('../emailer');
var UserEmail = module.exports; var UserEmail = module.exports;
UserEmail.exists = function (email, callback) { UserEmail.exists = async function (email) {
user.getUidByEmail(email.toLowerCase(), function (err, exists) { const uid = await user.getUidByEmail(email.toLowerCase());
callback(err, !!exists); return !!uid;
});
}; };
UserEmail.available = function (email, callback) { UserEmail.available = async function (email) {
db.isSortedSetMember('email:uid', email.toLowerCase(), function (err, exists) { const exists = await db.isSortedSetMember('email:uid', email.toLowerCase());
callback(err, !exists); return !exists;
});
}; };
UserEmail.sendValidationEmail = function (uid, options, callback) { UserEmail.sendValidationEmail = async function (uid, options) {
/* /*
* Options: * Options:
* - email, overrides email retrieval * - email, overrides email retrieval
* - force, sends email even if it is too soon to send another * - force, sends email even if it is too soon to send another
*/ */
// Handling for 2 arguments options = options || {};
if (arguments.length === 2 && typeof options === 'function') {
callback = options;
options = {};
}
// Fallback behaviour (email passed in as second argument) // Fallback behaviour (email passed in as second argument)
if (typeof options === 'string') { if (typeof options === 'string') {
@ -45,117 +38,66 @@ UserEmail.sendValidationEmail = function (uid, options, callback) {
}; };
} }
callback = callback || function () {}; let confirm_code = utils.generateUUID();
var confirm_code = utils.generateUUID(); const confirm_link = nconf.get('url') + '/confirm/' + confirm_code;
var confirm_link = nconf.get('url') + '/confirm/' + confirm_code;
var emailInterval = meta.config.emailConfirmInterval; const emailInterval = meta.config.emailConfirmInterval;
async.waterfall([
function (next) {
// If no email passed in (default), retrieve email from uid // If no email passed in (default), retrieve email from uid
if (options.email && options.email.length) { if (!options.email || !options.email.length) {
return setImmediate(next, null, options.email); options.email = await user.getUserField(uid, 'email');
} }
user.getUserField(uid, 'email', next);
},
function (email, next) {
options.email = email;
if (!options.email) { if (!options.email) {
return callback(); return;
} }
let sent = false;
if (options.force) { if (!options.force) {
return setImmediate(next, null, false); sent = await db.get('uid:' + uid + ':confirm:email:sent');
} }
db.get('uid:' + uid + ':confirm:email:sent', next);
},
function (sent, next) {
if (sent) { if (sent) {
return next(new Error('[[error:confirm-email-already-sent, ' + emailInterval + ']]')); throw new Error('[[error:confirm-email-already-sent, ' + emailInterval + ']]');
} }
db.set('uid:' + uid + ':confirm:email:sent', 1, next); await db.set('uid:' + uid + ':confirm:email:sent', 1);
}, await db.pexpireAt('uid:' + uid + ':confirm:email:sent', Date.now() + (emailInterval * 60 * 1000));
function (next) { confirm_code = await plugins.fireHook('filter:user.verify.code', confirm_code);
db.pexpireAt('uid:' + uid + ':confirm:email:sent', Date.now() + (emailInterval * 60 * 1000), next);
}, await db.setObject('confirm:' + confirm_code, {
function (next) {
plugins.fireHook('filter:user.verify.code', confirm_code, next);
},
function (_confirm_code, next) {
confirm_code = _confirm_code;
db.setObject('confirm:' + confirm_code, {
email: options.email.toLowerCase(), email: options.email.toLowerCase(),
uid: uid, uid: uid,
}, next); });
}, await db.expireAt('confirm:' + confirm_code, Math.floor((Date.now() / 1000) + (60 * 60 * 24)));
function (next) { const username = await user.getUserField(uid, 'username');
db.expireAt('confirm:' + confirm_code, Math.floor((Date.now() / 1000) + (60 * 60 * 24)), next);
}, const data = {
function (next) {
user.getUserField(uid, 'username', next);
},
function (username, next) {
var title = meta.config.title || meta.config.browserTitle || 'NodeBB';
var template = options.template || 'welcome';
var data = {
username: username, username: username,
confirm_link: confirm_link, confirm_link: confirm_link,
confirm_code: confirm_code, confirm_code: confirm_code,
subject: options.subject || '[[email:welcome-to, ' + title + ']]', subject: options.subject || '[[email:welcome-to, ' + (meta.config.title || meta.config.browserTitle || 'NodeBB') + ']]',
template: template, template: options.template || 'welcome',
uid: uid, uid: uid,
}; };
if (plugins.hasListeners('action:user.verify')) { if (plugins.hasListeners('action:user.verify')) {
plugins.fireHook('action:user.verify', { uid: uid, data: data }); plugins.fireHook('action:user.verify', { uid: uid, data: data });
next();
} else { } else {
emailer.send(template, uid, data, next); await emailer.send(data.template, uid, data);
} }
}, return confirm_code;
function (next) {
next(null, confirm_code);
},
], callback);
}; };
UserEmail.confirm = function (code, callback) { UserEmail.confirm = async function (code) {
var confirmObj; const confirmObj = await db.getObject('confirm:' + code);
async.waterfall([
function (next) {
db.getObject('confirm:' + code, next);
},
function (_confirmObj, next) {
confirmObj = _confirmObj;
if (!confirmObj || !confirmObj.uid || !confirmObj.email) { if (!confirmObj || !confirmObj.uid || !confirmObj.email) {
return next(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
const currentEmail = await user.getUserField(confirmObj.uid, 'email');
user.getUserField(confirmObj.uid, 'email', next);
},
function (currentEmail, next) {
if (!currentEmail || currentEmail.toLowerCase() !== confirmObj.email) { if (!currentEmail || currentEmail.toLowerCase() !== confirmObj.email) {
return next(new Error('[[error:invalid-email]]')); throw new Error('[[error:invalid-email]]');
} }
await user.setUserField(confirmObj.uid, 'email:confirmed', 1);
async.series([ await db.delete('confirm:' + code);
async.apply(user.setUserField, confirmObj.uid, 'email:confirmed', 1), await db.delete('uid:' + confirmObj.uid + ':confirm:email:sent');
async.apply(db.delete, 'confirm:' + code), await db.sortedSetRemove('users:notvalidated', confirmObj.uid);
async.apply(db.delete, 'uid:' + confirmObj.uid + ':confirm:email:sent'), await plugins.fireHook('action:user.email.confirmed', { uid: confirmObj.uid, email: confirmObj.email });
function (next) {
db.sortedSetRemove('users:notvalidated', confirmObj.uid, next);
},
function (next) {
plugins.fireHook('action:user.email.confirmed', { uid: confirmObj.uid, email: confirmObj.email }, next);
},
], next);
},
], function (err) {
callback(err);
});
}; };

@ -1,103 +1,85 @@
'use strict'; 'use strict';
var async = require('async');
var plugins = require('../plugins'); var plugins = require('../plugins');
var db = require('../database'); var db = require('../database');
module.exports = function (User) { module.exports = function (User) {
User.follow = function (uid, followuid, callback) { User.follow = async function (uid, followuid) {
toggleFollow('follow', uid, followuid, callback); await toggleFollow('follow', uid, followuid);
}; };
User.unfollow = function (uid, unfollowuid, callback) { User.unfollow = async function (uid, unfollowuid) {
toggleFollow('unfollow', uid, unfollowuid, callback); await toggleFollow('unfollow', uid, unfollowuid);
}; };
function toggleFollow(type, uid, theiruid, callback) { async function toggleFollow(type, uid, theiruid) {
if (parseInt(uid, 10) <= 0 || parseInt(theiruid, 10) <= 0) { if (parseInt(uid, 10) <= 0 || parseInt(theiruid, 10) <= 0) {
return callback(new Error('[[error:invalid-uid]]')); throw new Error('[[error:invalid-uid]]');
} }
if (parseInt(uid, 10) === parseInt(theiruid, 10)) { if (parseInt(uid, 10) === parseInt(theiruid, 10)) {
return callback(new Error('[[error:you-cant-follow-yourself]]')); throw new Error('[[error:you-cant-follow-yourself]]');
} }
const exists = await User.exists(theiruid);
async.waterfall([
function (next) {
User.exists(theiruid, next);
},
function (exists, next) {
if (!exists) { if (!exists) {
return next(new Error('[[error:no-user]]')); throw new Error('[[error:no-user]]');
} }
User.isFollowing(uid, theiruid, next); const isFollowing = await User.isFollowing(uid, theiruid);
},
function (isFollowing, next) {
if (type === 'follow') { if (type === 'follow') {
if (isFollowing) { if (isFollowing) {
return next(new Error('[[error:already-following]]')); throw new Error('[[error:already-following]]');
} }
var now = Date.now(); const now = Date.now();
async.parallel([ await Promise.all([
async.apply(db.sortedSetAddBulk, [ db.sortedSetAddBulk([
['following:' + uid, now, theiruid], ['following:' + uid, now, theiruid],
['followers:' + theiruid, now, uid], ['followers:' + theiruid, now, uid],
]), ]),
async.apply(User.incrementUserFieldBy, uid, 'followingCount', 1), User.incrementUserFieldBy(uid, 'followingCount', 1),
async.apply(User.incrementUserFieldBy, theiruid, 'followerCount', 1), User.incrementUserFieldBy(theiruid, 'followerCount', 1),
], next); ]);
} else { } else {
if (!isFollowing) { if (!isFollowing) {
return next(new Error('[[error:not-following]]')); throw new Error('[[error:not-following]]');
} }
async.parallel([ await Promise.all([
async.apply(db.sortedSetRemove, 'following:' + uid, theiruid), db.sortedSetRemoveBulk([
async.apply(db.sortedSetRemove, 'followers:' + theiruid, uid), ['following:' + uid, theiruid],
async.apply(User.decrementUserFieldBy, uid, 'followingCount', 1), ['followers:' + theiruid, uid],
async.apply(User.decrementUserFieldBy, theiruid, 'followerCount', 1), ]),
], next); User.decrementUserFieldBy(uid, 'followingCount', 1),
User.decrementUserFieldBy(theiruid, 'followerCount', 1),
]);
} }
},
], function (err) {
callback(err);
});
} }
User.getFollowing = function (uid, start, stop, callback) { User.getFollowing = async function (uid, start, stop) {
getFollow(uid, 'following', start, stop, callback); return await getFollow(uid, 'following', start, stop);
}; };
User.getFollowers = function (uid, start, stop, callback) { User.getFollowers = async function (uid, start, stop) {
getFollow(uid, 'followers', start, stop, callback); return await getFollow(uid, 'followers', start, stop);
}; };
function getFollow(uid, type, start, stop, callback) { async function getFollow(uid, type, start, stop) {
if (parseInt(uid, 10) <= 0) { if (parseInt(uid, 10) <= 0) {
return setImmediate(callback, null, []); return [];
} }
async.waterfall([ const uids = await db.getSortedSetRevRange(type + ':' + uid, start, stop);
function (next) { const data = await plugins.fireHook('filter:user.' + type, {
db.getSortedSetRevRange(type + ':' + uid, start, stop, next);
},
function (uids, next) {
plugins.fireHook('filter:user.' + type, {
uids: uids, uids: uids,
uid: uid, uid: uid,
start: start, start: start,
stop: stop, stop: stop,
}, next); });
}, return await User.getUsers(data.uids, uid);
function (data, next) {
User.getUsers(data.uids, uid, next);
},
], callback);
} }
User.isFollowing = function (uid, theirid, callback) { User.isFollowing = async function (uid, theirid) {
if (parseInt(uid, 10) <= 0 || parseInt(theirid, 10) <= 0) { if (parseInt(uid, 10) <= 0 || parseInt(theirid, 10) <= 0) {
return setImmediate(callback, null, false); return false;
} }
db.isSortedSetMember('following:' + uid, theirid, callback); return await db.isSortedSetMember('following:' + uid, theirid);
}; };
}; };

Loading…
Cancel
Save