Node.js based forum software built for the modern web
redis wrapper removed. pretty safe to say that we didn't really need it in the first place.
psychobunnyfb8391367053
diff --git a/src/categories.js b/src/categories.jsindex 5173e64955..9e740db8f4 100644--- a/src/categories.js+++ b/src/categories.js@@ -1,90 +1,93 @@-var RDB = require('./redis.js'),- posts = require('./posts.js'),- utils = require('./utils.js'),- user = require('./user.js');--(function(Categories) {--- // An admin-only function. Seeing how we have no control panel yet ima leave this right here. sit pretty, you- Categories.create = function(data, callback) {- RDB.incr('global:next_category_id', function(cid) {- var slug = cid + '/' + utils.slugify(data.name);- RDB.rpush('categories:cid', cid);-- // Topic Info- RDB.set('cid:' + cid + ':name', data.name);- RDB.set('cid:' + cid + ':description', data.description);- RDB.set('cid:' + cid + ':icon', data.icon);- RDB.set('cid:' + cid + ':blockclass', data.blockclass);- RDB.set('cid:' + cid + ':slug', slug);-- RDB.set('category:slug:' + slug + ':cid', cid);-- if (callback) callback({'status': 1});- });- };-- Categories.edit = function(data, callback) {- // just a reminder to self that name + slugs are stored into topics data as well.- };-- Categories.get = function(callback) {- RDB.lrange('categories:cid', 0, -1, function(cids) {- Categories.get_category(cids, callback);- });- }-- Categories.get_category = function(cids, callback) {- var name = [],- description = [],- icon = [],- blockclass = [],- slug = [];-- for (var i=0, ii=cids.length; i<ii; i++) {- name.push('cid:' + cids[i] + ':name');- description.push('cid:' + cids[i] + ':description');- icon.push('cid:' + cids[i] + ':icon');- blockclass.push('cid:' + cids[i] + ':blockclass');- slug.push('cid:' + cids[i] + ':slug');- }-- if (cids.length > 0) {- RDB.multi()- .mget(name)- .mget(description)- .mget(icon)- .mget(blockclass)- .mget(slug)- .exec(function(err, replies) {- name = replies[0];- description = replies[1];- icon = replies[2];- blockclass = replies[3];- slug = replies[4];-- var categories = [];- for (var i=0, ii=cids.length; i<ii; i++) {- categories.push({- 'name' : name[i],- 'cid' : cids[i],- 'slug' : slug[i],- 'description' : description[i],- 'blockclass' : blockclass[i],- 'icon' : icon[i],- /*'topics' : [0,1], later- 'latest_post' : {- 'uid' : 1,- 'pid' : 1,- timestamp and shit- }*/- });- }-- callback({'categories': categories});- });- } else callback({'categories' : []});- };-+var RDB = require('./redis.js'),+ posts = require('./posts.js'),+ utils = require('./utils.js'),+ user = require('./user.js');++(function(Categories) {+++ // An admin-only function. Seeing how we have no control panel yet ima leave this right here. sit pretty, you+ Categories.create = function(data, callback) {+ RDB.incr('global:next_category_id', function(err, cid) {+ RDB.handle(err);++ var slug = cid + '/' + utils.slugify(data.name);+ RDB.rpush('categories:cid', cid);++ // Topic Info+ RDB.set('cid:' + cid + ':name', data.name);+ RDB.set('cid:' + cid + ':description', data.description);+ RDB.set('cid:' + cid + ':icon', data.icon);+ RDB.set('cid:' + cid + ':blockclass', data.blockclass);+ RDB.set('cid:' + cid + ':slug', slug);++ RDB.set('category:slug:' + slug + ':cid', cid);++ if (callback) callback({'status': 1});+ });+ };++ Categories.edit = function(data, callback) {+ // just a reminder to self that name + slugs are stored into topics data as well.+ };++ Categories.get = function(callback) {+ RDB.lrange('categories:cid', 0, -1, function(err, cids) {+ RDB.handle(err);+ Categories.get_category(cids, callback);+ });+ }++ Categories.get_category = function(cids, callback) {+ var name = [],+ description = [],+ icon = [],+ blockclass = [],+ slug = [];++ for (var i=0, ii=cids.length; i<ii; i++) {+ name.push('cid:' + cids[i] + ':name');+ description.push('cid:' + cids[i] + ':description');+ icon.push('cid:' + cids[i] + ':icon');+ blockclass.push('cid:' + cids[i] + ':blockclass');+ slug.push('cid:' + cids[i] + ':slug');+ }++ if (cids.length > 0) {+ RDB.multi()+ .mget(name)+ .mget(description)+ .mget(icon)+ .mget(blockclass)+ .mget(slug)+ .exec(function(err, replies) {+ name = replies[0];+ description = replies[1];+ icon = replies[2];+ blockclass = replies[3];+ slug = replies[4];++ var categories = [];+ for (var i=0, ii=cids.length; i<ii; i++) {+ categories.push({+ 'name' : name[i],+ 'cid' : cids[i],+ 'slug' : slug[i],+ 'description' : description[i],+ 'blockclass' : blockclass[i],+ 'icon' : icon[i],+ /*'topics' : [0,1], later+ 'latest_post' : {+ 'uid' : 1,+ 'pid' : 1,+ timestamp and shit+ }*/+ });+ }++ callback({'categories': categories});+ });+ } else callback({'categories' : []});+ };+}(exports));\ No newline at end of filediff --git a/src/posts.js b/src/posts.jsindex b05a264798..53b98710e1 100644--- a/src/posts.js+++ b/src/posts.js@@ -1,248 +1,261 @@-var RDB = require('./redis.js'),- utils = require('./utils.js'),- marked = require('marked'),- user = require('./user.js'),- config = require('../config.js');--(function(Posts) {-- Posts.get = function(callback, tid, current_user, start, end) {- if (start == null) start = 0;- if (end == null) end = start + 10;-- var post_data, user_data, thread_data, vote_data, viewer_data;--- //compile thread after all data is asynchronously called- function generateThread() {- if (!post_data ||! user_data || !thread_data || !vote_data || !viewer_data) return;-- var posts = [];-- for (var i=0, ii= post_data.pid.length; i<ii; i++) {- var uid = post_data.uid[i],- pid = post_data.pid[i];-- posts.push({- 'pid' : pid,- 'uid' : uid,- 'content' : marked(post_data.content[i] || ''),- 'post_rep' : post_data.reputation[i] || 0,- 'timestamp' : post_data.timestamp[i],- 'relativeTime': utils.relativeTime(post_data.timestamp[i]),- 'username' : user_data[uid].username || 'anonymous',- 'user_rep' : user_data[uid].reputation || 0,- 'gravatar' : user_data[uid].picture,- 'fav_star_class' : vote_data[pid] ? 'icon-star' : 'icon-star-empty',- 'display_moderator_tools' : uid == current_user ? 'show' : 'none'- });- }-- callback({- 'topic_name':thread_data.topic_name,- 'category_name':thread_data.category_name,- 'category_slug':thread_data.category_slug,- 'locked': parseInt(thread_data.locked) || 0,- 'deleted': parseInt(thread_data.deleted) || 0,- 'pinned': parseInt(thread_data.pinned) || 0,- 'topic_id': tid,- 'expose_tools': viewer_data.reputation >= config.privilege_thresholds.manage_thread ? 1 : 0,- 'posts': posts- });- }--- // get all data for thread in asynchronous fashion- RDB.lrange('tid:' + tid + ':posts', start, end, function(pids) {- var content = [], uid = [], timestamp = [], pid = [], post_rep = [];-- for (var i=0, ii=pids.length; i<ii; i++) {- content.push('pid:' + pids[i] + ':content');- uid.push('pid:' + pids[i] + ':uid');- timestamp.push('pid:' + pids[i] + ':timestamp');- post_rep.push('pid:' + pids[i] + ':rep');- pid.push(pids[i]);- }--- Posts.getFavouritesByPostIDs(pids, current_user, function(fav_data) {- vote_data = fav_data;- generateThread();- });--- RDB.multi()- .mget(content)- .mget(uid)- .mget(timestamp)- .mget(post_rep)- .get('tid:' + tid + ':title')- .get('tid:' + tid + ':locked')- .get('tid:' + tid + ':category_name')- .get('tid:' + tid + ':category_slug')- .get('tid:' + tid + ':deleted')- .get('tid:' + tid + ':pinned')- .exec(function(err, replies) {- post_data = {- pid: pids,- content: replies[0],- uid: replies[1],- timestamp: replies[2],- reputation: replies[3]- };-- thread_data = {- topic_name: replies[4],- locked: replies[5] || 0,- category_name: replies[6],- category_slug: replies[7],- deleted: replies[8] || 0,- pinned: replies[9] || 0- };-- user.getMultipleUserFields(post_data.uid, ['username','reputation','picture'], function(user_details){- user_data = user_details;- generateThread();- });- });- });-- user.getUserField(current_user, 'reputation', function(reputation){- viewer_data = {- reputation: reputation- };- generateThread();- });- }--- Posts.reply = function(socket, tid, uid, content) {- Posts.create(uid, tid, content, function(pid) {- if (pid > 0) {- RDB.rpush('tid:' + tid + ':posts', pid);-- socket.emit('event:alert', {- title: 'Reply Successful',- message: 'You have successfully replied. Click here to view your reply.',- type: 'notify',- timeout: 2000- });--- user.getUserFields(uid, ['username','reputation','picture'], function(data){-- var timestamp = new Date().getTime();-- io.sockets.in('topic_' + tid).emit('event:new_post', {- 'posts' : [- {- 'pid' : pid,- 'content' : marked(content || ''),- 'uid' : uid,- 'username' : data.username || 'anonymous',- 'user_rep' : data.reputation || 0,- 'post_rep' : 0,- 'gravatar' : data.picture,- 'timestamp' : timestamp,- 'relativeTime': utils.relativeTime(timestamp),- 'fav_star_class' :'icon-star-empty'- }- ]- });- });- } else {- socket.emit('event:alert', {- title: 'Reply Unsuccessful',- message: 'Your reply could not be posted at this time. Please try again later.',- type: 'notify',- timeout: 2000- });- }- });- };-- Posts.create = function(uid, tid, content, callback) {- if (uid === null) return;-- RDB.get('tid:' + tid + ':locked', function(locked) {- if (!locked || locked === '0') {- RDB.incr('global:next_post_id', function(pid) {- // Posts Info- RDB.set('pid:' + pid + ':content', content);- RDB.set('pid:' + pid + ':uid', uid);- RDB.set('pid:' + pid + ':timestamp', new Date().getTime());- RDB.set('pid:' + pid + ':rep', 0);-- RDB.incr('tid:' + tid + ':postcount');-- // User Details - move this out later- RDB.lpush('uid:' + uid + ':posts', pid);-- user.incrementUserFieldBy(uid, 'postcount', 1);-- if (callback)- callback(pid);- });- } else {- callback(-1);- }- });- }--- Posts.favourite = function(io, pid, room_id, uid) {- RDB.get('pid:' + pid + ':uid', function(uid_of_poster) {- Posts.hasFavourited(pid, uid, function(hasFavourited) {- if (hasFavourited == false) {- RDB.sadd('pid:' + pid + ':users_favourited', uid);-- user.incrementUserFieldBy(uid_of_poster, 'reputation', 1);-- RDB.incr('pid:' + pid + ':rep');-- if (room_id) {- io.sockets.in(room_id).emit('event:rep_up', {uid: uid_of_poster, pid: pid});- }- }- });- });- }-- Posts.unfavourite = function(io, pid, room_id, uid) {- RDB.get('pid:' + pid + ':uid', function(uid_of_poster) {- Posts.hasFavourited(pid, uid, function(hasFavourited) {- if (hasFavourited == true) {-- RDB.srem('pid:' + pid + ':users_favourited', uid);- user.incrementUserFieldBy(uid_of_poster, 'reputation', -1);- RDB.decr('pid:' + pid + ':rep');-- if (room_id) {- io.sockets.in(room_id).emit('event:rep_down', {uid: uid_of_poster, pid: pid});- }- }- });- });- }-- Posts.hasFavourited = function(pid, uid, callback) {- RDB.sismember('pid:' + pid + ':users_favourited', uid, function(hasFavourited) {- callback(hasFavourited);- });- }-- Posts.getFavouritesByPostIDs = function(pids, uid, callback) {- var loaded = 0;- var data = {};-- for (var i=0, ii=pids.length; i<ii; i++) {- (function(post_id) {- Posts.hasFavourited(post_id, uid, function(hasFavourited){- data[post_id] = hasFavourited;- loaded ++;- if (loaded == pids.length) callback(data);- });- }(pids[i]))- }- }+var RDB = require('./redis.js'),+ utils = require('./utils.js'),+ marked = require('marked'),+ user = require('./user.js'),+ config = require('../config.js');++(function(Posts) {++ Posts.get = function(callback, tid, current_user, start, end) {+ if (start == null) start = 0;+ if (end == null) end = start + 10;++ var post_data, user_data, thread_data, vote_data, viewer_data;+++ //compile thread after all data is asynchronously called+ function generateThread() {+ if (!post_data ||! user_data || !thread_data || !vote_data || !viewer_data) return;++ var posts = [];++ for (var i=0, ii= post_data.pid.length; i<ii; i++) {+ var uid = post_data.uid[i],+ pid = post_data.pid[i];++ posts.push({+ 'pid' : pid,+ 'uid' : uid,+ 'content' : marked(post_data.content[i] || ''),+ 'post_rep' : post_data.reputation[i] || 0,+ 'timestamp' : post_data.timestamp[i],+ 'relativeTime': utils.relativeTime(post_data.timestamp[i]),+ 'username' : user_data[uid].username || 'anonymous',+ 'user_rep' : user_data[uid].reputation || 0,+ 'gravatar' : user_data[uid].picture,+ 'fav_star_class' : vote_data[pid] ? 'icon-star' : 'icon-star-empty',+ 'display_moderator_tools' : uid == current_user ? 'show' : 'none'+ });+ }++ callback({+ 'topic_name':thread_data.topic_name,+ 'category_name':thread_data.category_name,+ 'category_slug':thread_data.category_slug,+ 'locked': parseInt(thread_data.locked) || 0,+ 'deleted': parseInt(thread_data.deleted) || 0,+ 'pinned': parseInt(thread_data.pinned) || 0,+ 'topic_id': tid,+ 'expose_tools': viewer_data.reputation >= config.privilege_thresholds.manage_thread ? 1 : 0,+ 'posts': posts+ });+ }+++ // get all data for thread in asynchronous fashion+ RDB.lrange('tid:' + tid + ':posts', start, end, function(err, pids) {+ RDB.handle(err);++ var content = [], uid = [], timestamp = [], pid = [], post_rep = [];++ for (var i=0, ii=pids.length; i<ii; i++) {+ content.push('pid:' + pids[i] + ':content');+ uid.push('pid:' + pids[i] + ':uid');+ timestamp.push('pid:' + pids[i] + ':timestamp');+ post_rep.push('pid:' + pids[i] + ':rep');+ pid.push(pids[i]);+ }+++ Posts.getFavouritesByPostIDs(pids, current_user, function(fav_data) {+ vote_data = fav_data;+ generateThread();+ });+++ RDB.multi()+ .mget(content)+ .mget(uid)+ .mget(timestamp)+ .mget(post_rep)+ .get('tid:' + tid + ':title')+ .get('tid:' + tid + ':locked')+ .get('tid:' + tid + ':category_name')+ .get('tid:' + tid + ':category_slug')+ .get('tid:' + tid + ':deleted')+ .get('tid:' + tid + ':pinned')+ .exec(function(err, replies) {+ post_data = {+ pid: pids,+ content: replies[0],+ uid: replies[1],+ timestamp: replies[2],+ reputation: replies[3]+ };++ thread_data = {+ topic_name: replies[4],+ locked: replies[5] || 0,+ category_name: replies[6],+ category_slug: replies[7],+ deleted: replies[8] || 0,+ pinned: replies[9] || 0+ };++ user.getMultipleUserFields(post_data.uid, ['username','reputation','picture'], function(user_details){+ user_data = user_details;+ generateThread();+ });+ });+ });++ user.getUserField(current_user, 'reputation', function(reputation){+ viewer_data = {+ reputation: reputation+ };+ generateThread();+ });+ }+++ Posts.reply = function(socket, tid, uid, content) {+ Posts.create(uid, tid, content, function(pid) {+ if (pid > 0) {+ RDB.rpush('tid:' + tid + ':posts', pid);++ socket.emit('event:alert', {+ title: 'Reply Successful',+ message: 'You have successfully replied. Click here to view your reply.',+ type: 'notify',+ timeout: 2000+ });+++ user.getUserFields(uid, ['username','reputation','picture'], function(data){++ var timestamp = new Date().getTime();++ io.sockets.in('topic_' + tid).emit('event:new_post', {+ 'posts' : [+ {+ 'pid' : pid,+ 'content' : marked(content || ''),+ 'uid' : uid,+ 'username' : data.username || 'anonymous',+ 'user_rep' : data.reputation || 0,+ 'post_rep' : 0,+ 'gravatar' : data.picture,+ 'timestamp' : timestamp,+ 'relativeTime': utils.relativeTime(timestamp),+ 'fav_star_class' :'icon-star-empty'+ }+ ]+ });+ });+ } else {+ socket.emit('event:alert', {+ title: 'Reply Unsuccessful',+ message: 'Your reply could not be posted at this time. Please try again later.',+ type: 'notify',+ timeout: 2000+ });+ }+ });+ };++ Posts.create = function(uid, tid, content, callback) {+ if (uid === null) return;++ RDB.get('tid:' + tid + ':locked', function(err, locked) {+ RDB.handle(err);++ if (!locked || locked === '0') {+ RDB.incr('global:next_post_id', function(err, pid) {+ RDB.handle(err);++ // Posts Info+ RDB.set('pid:' + pid + ':content', content);+ RDB.set('pid:' + pid + ':uid', uid);+ RDB.set('pid:' + pid + ':timestamp', new Date().getTime());+ RDB.set('pid:' + pid + ':rep', 0);++ RDB.incr('tid:' + tid + ':postcount');++ // User Details - move this out later+ RDB.lpush('uid:' + uid + ':posts', pid);++ user.incrementUserFieldBy(uid, 'postcount', 1);++ if (callback)+ callback(pid);+ });+ } else {+ callback(-1);+ }+ });+ }+++ Posts.favourite = function(io, pid, room_id, uid) {+ RDB.get('pid:' + pid + ':uid', function(err, uid_of_poster) {+ RDB.handle(err);++ Posts.hasFavourited(pid, uid, function(hasFavourited) {+ if (hasFavourited == false) {+ RDB.sadd('pid:' + pid + ':users_favourited', uid);++ user.incrementUserFieldBy(uid_of_poster, 'reputation', 1);++ RDB.incr('pid:' + pid + ':rep');++ if (room_id) {+ io.sockets.in(room_id).emit('event:rep_up', {uid: uid_of_poster, pid: pid});+ }+ }+ });+ });+ }++ Posts.unfavourite = function(io, pid, room_id, uid) {+ RDB.get('pid:' + pid + ':uid', function(err, uid_of_poster) {+ RDB.handle(err);++ Posts.hasFavourited(pid, uid, function(hasFavourited) {+ if (hasFavourited == true) {++ RDB.srem('pid:' + pid + ':users_favourited', uid);+ user.incrementUserFieldBy(uid_of_poster, 'reputation', -1);+ RDB.decr('pid:' + pid + ':rep');++ if (room_id) {+ io.sockets.in(room_id).emit('event:rep_down', {uid: uid_of_poster, pid: pid});+ }+ }+ });+ });+ }++ Posts.hasFavourited = function(pid, uid, callback) {+ RDB.sismember('pid:' + pid + ':users_favourited', uid, function(err, hasFavourited) {+ RDB.handle(err);+ callback(hasFavourited);+ });+ }++ Posts.getFavouritesByPostIDs = function(pids, uid, callback) {+ var loaded = 0;+ var data = {};++ for (var i=0, ii=pids.length; i<ii; i++) {+ (function(post_id) {+ Posts.hasFavourited(post_id, uid, function(err, hasFavourited) {+ RDB.handle(err);++ data[post_id] = hasFavourited;+ loaded ++;+ if (loaded == pids.length) callback(data);+ });+ }(pids[i]))+ }+ }}(exports));\ No newline at end of filediff --git a/src/redis.js b/src/redis.jsindex 140e2e11d6..fe1dc371c2 100644--- a/src/redis.js+++ b/src/redis.js@@ -1,106 +1,106 @@-(function(RedisDB) {- var PRODUCTION = false,- ERROR_LOGS = true,-- redis = require('redis'),- config = require('../config.js'),- db = redis.createClient(config.redis.port, config.redis.host, config.redis.options);-- RedisDB.db = db;-- // todo (holy cow): append,auth,bgrewriteaof,bgsave,bitcount,bitop,blpop,brpop,brpoplpush,client kill,client list,client getname,client setname,config get,config set,config resetstat,dbsize,debug object,debug segfault,decrby,discard,dump,echo,eval,evalsha,exec,exists,expireat,flushall,flushdb,getbit,getrange,getset,hdel,hexists,hget,hgetall,hincrby,hincrbyfloat,hkeys,hlen,hmget,hmset,hset,hsetnx,hvals,incrby,incrbyfloat,info,lastsave,lindex,linsert,llen,lpop,lpushx,lrem,lset,ltrim,migrate,monitor,move,mset,msetnx,object,persist,pexpire,pexpireat,ping,psetex,psubscribe,pttl,publish,punsubscribe,quit,randomkey,rename,renamenx,restore,rpop,rpoplpush,rpush,rpushx,sadd,save,scard,script exists,script flush,script kill,script load,sdiff,sdiffstore,select,setbit,setex,setnx,setrange,shutdown,sinter,sinterstore,sismember,slaveof,slowlog,smembers,smove,sort,spop,srandmember,srem,strlen,subscribe,sunion,sunionstore,sync,time,ttl,type,unsubscribe,unwatch,watch,zadd,zcard,zcount,zincrby,zinterstore,zrange,zrangebyscore,zrank,zrem,zremrangebyrank,zremrangebyscore,zrevrange,zrevrangebyscore,zrevrank,zscore,zunionstore- // done: get, set, incr, decr, del, mget, multi, expire, lpush, lrange, keys-- function return_handler(error, data, callback, error_handler) {- if (error !== null) {- if (error_handler !== null) {- error_handler(error);- } else if (PRODUCTION === false) {- throw new Exception('RedisDB Error: ' + error);- } else if (ERROR_LOGS === true) {- console.log('RedisDB Error: ' + error);- }- } else {- callback(data);- }- }-- RedisDB.set = function(key, value, expiry) {- db.set(key, value);- if (expiry !== undefined) RedisDB.expire(key, expiry);- };-- RedisDB.get = function(key, callback, error_handler) {- db.get(key, function(error, data) {- return_handler(error, data, callback, error_handler);- });- };-- RedisDB.mget = function(keys, callback, error_handler) {- db.mget(keys, function(error, data) {- return_handler(error, data, callback, error_handler);- });- };-- RedisDB.multi = function() {- return db.multi();- }-- RedisDB.keys = function(pattern, callback, error_handler) {- return db.keys(pattern, function(error, data) {- return_handler(error, data, callback, error_handler);- });- }-- RedisDB.del = function(key, callback) {- db.del(key);- }-- RedisDB.expire = function(key, expiry) {- db.expire(key, expiry);- }-- // Atomic Operations- RedisDB.incr = function(key, callback, error_handler) {- db.incr(key, function(error, data) {- if (callback) {- return_handler(error, data, callback, error_handler);- }- });- };-- RedisDB.decr = function(key) {- db.decr(key);- };-- // Lists- RedisDB.lpush = function(key, item) {- db.lpush(key, item);- }-- RedisDB.rpush = function(key, item) {- db.rpush(key, item);- }-- RedisDB.lrange = function(key, start, end, callback, error_handler) {- db.lrange(key, start, end, function(error, data) {- return_handler(error, data, callback, error_handler);- });- }-- // Sets- RedisDB.sadd = function(key, item) {- db.sadd(key, item);- };-- RedisDB.srem = function(key, item) {- db.srem(key, item);- };-- RedisDB.sismember = function(key, item, callback, error_handler) {- db.sismember(key, item, function(error, data) {- return_handler(error, data, callback, error_handler);- });- };-+(function(RedisDB) {+ var PRODUCTION = false,+ ERROR_LOGS = true,++ redis = require('redis'),+ config = require('../config.js'),+ RedisDB = redis.createClient(config.redis.port, config.redis.host, config.redis.options);++ //RedisDB.db = db;++ // todo (holy cow): append,auth,bgrewriteaof,bgsave,bitcount,bitop,blpop,brpop,brpoplpush,client kill,client list,client getname,client setname,config get,config set,config resetstat,dbsize,debug object,debug segfault,decrby,discard,dump,echo,eval,evalsha,exec,exists,expireat,flushall,flushdb,getbit,getrange,getset,hdel,hexists,hget,hgetall,hincrby,hincrbyfloat,hkeys,hlen,hmget,hmset,hset,hsetnx,hvals,incrby,incrbyfloat,info,lastsave,lindex,linsert,llen,lpop,lpushx,lrem,lset,ltrim,migrate,monitor,move,mset,msetnx,object,persist,pexpire,pexpireat,ping,psetex,psubscribe,pttl,publish,punsubscribe,quit,randomkey,rename,renamenx,restore,rpop,rpoplpush,rpush,rpushx,sadd,save,scard,script exists,script flush,script kill,script load,sdiff,sdiffstore,select,setbit,setex,setnx,setrange,shutdown,sinter,sinterstore,sismember,slaveof,slowlog,smembers,smove,sort,spop,srandmember,srem,strlen,subscribe,sunion,sunionstore,sync,time,ttl,type,unsubscribe,unwatch,watch,zadd,zcard,zcount,zincrby,zinterstore,zrange,zrangebyscore,zrank,zrem,zremrangebyrank,zremrangebyscore,zrevrange,zrevrangebyscore,zrevrank,zscore,zunionstore+ // done: get, set, incr, decr, del, mget, multi, expire, lpush, lrange, keys++ function return_handler(error, data, callback, error_handler) {+ if (error !== null) {+ if (error_handler !== null) {+ error_handler(error);+ } else if (PRODUCTION === false) {+ throw new Exception('RedisDB Error: ' + error);+ } else if (ERROR_LOGS === true) {+ console.log('RedisDB Error: ' + error);+ }+ } else {+ callback(data);+ }+ }++ RedisDB.set = function(key, value, expiry) {+ db.set(key, value);+ if (expiry !== undefined) RedisDB.expire(key, expiry);+ };++ RedisDB.get = function(key, callback, error_handler) {+ db.get(key, function(error, data) {+ return_handler(error, data, callback, error_handler);+ });+ };++ RedisDB.mget = function(keys, callback, error_handler) {+ db.mget(keys, function(error, data) {+ return_handler(error, data, callback, error_handler);+ });+ };++ RedisDB.multi = function() {+ return db.multi();+ }++ RedisDB.keys = function(pattern, callback, error_handler) {+ return db.keys(pattern, function(error, data) {+ return_handler(error, data, callback, error_handler);+ });+ }++ RedisDB.del = function(key, callback) {+ db.del(key);+ }++ RedisDB.expire = function(key, expiry) {+ db.expire(key, expiry);+ }++ // Atomic Operations+ RedisDB.incr = function(key, callback, error_handler) {+ db.incr(key, function(error, data) {+ if (callback) {+ return_handler(error, data, callback, error_handler);+ }+ });+ };++ RedisDB.decr = function(key) {+ db.decr(key);+ };++ // Lists+ RedisDB.lpush = function(key, item) {+ db.lpush(key, item);+ }++ RedisDB.rpush = function(key, item) {+ db.rpush(key, item);+ }++ RedisDB.lrange = function(key, start, end, callback, error_handler) {+ db.lrange(key, start, end, function(error, data) {+ return_handler(error, data, callback, error_handler);+ });+ }++ // Sets+ RedisDB.sadd = function(key, item) {+ db.sadd(key, item);+ };++ RedisDB.srem = function(key, item) {+ db.srem(key, item);+ };++ RedisDB.sismember = function(key, item, callback, error_handler) {+ db.sismember(key, item, function(error, data) {+ return_handler(error, data, callback, error_handler);+ });+ };+}(exports));\ No newline at end of filediff --git a/src/topics.js b/src/topics.jsindex bd02ac8405..89e6c9ab26 100644--- a/src/topics.js+++ b/src/topics.js@@ -1,303 +1,306 @@-var RDB = require('./redis.js'),- posts = require('./posts.js'),- utils = require('./utils.js'),- user = require('./user.js'),- configs = require('../config.js'),- categories = require('./categories.js');--(function(Topics) {-- Topics.get_by_category = function(callback, category, start, end) {-- }---- Topics.get = function(callback, category_id, start, end) {- if (start == null) start = 0;- if (end == null) end = start + 10;-- //build a proper wrapper for this and move it into above function later- var range_var = (category_id) ? 'categories:' + category_id + ':tid' : 'topics:tid';-- RDB.db.smembers(range_var, function(err, tids) {- var title = [],- uid = [],- timestamp = [],- slug = [],- postcount = [],- locked = [],- deleted = [],- pinned = [];-- for (var i=0, ii=tids.length; i<ii; i++) {- title.push('tid:' + tids[i] + ':title');- uid.push('tid:' + tids[i] + ':uid');- timestamp.push('tid:' + tids[i] + ':timestamp');- slug.push('tid:' + tids[i] + ':slug');- postcount.push('tid:' + tids[i] + ':postcount');- locked.push('tid:' + tids[i] + ':locked');- deleted.push('tid:' + tids[i] + ':deleted');- pinned.push('tid:' + tids[i] + ':pinned');- }-- var multi = RDB.multi()- .get('cid:' + category_id + ':name');-- if (tids.length > 0) {- multi- .mget(title)- .mget(uid)- .mget(timestamp)- .mget(slug)- .mget(postcount)- .mget(locked)- .mget(deleted)- .mget(pinned)- }--- multi.exec(function(err, replies) {- category_name = replies[0];- var topics = [];-- if (tids.length > 0) {- title = replies[1];- uid = replies[2];- timestamp = replies[3];- slug = replies[4];- postcount = replies[5];- locked = replies[6];- deleted = replies[7];- pinned = replies[8];-- user.get_usernames_by_uids(uid, function(userNames) {-- for (var i=0, ii=title.length; i<ii; i++) {-- topics.push({- 'title' : title[i],- 'uid' : uid[i],- 'username': userNames[i],- 'timestamp' : timestamp[i],- 'relativeTime': utils.relativeTime(timestamp[i]),- 'slug' : slug[i],- 'post_count' : postcount[i],- 'lock-icon': locked[i] === '1' ? 'icon-lock' : 'none',- 'deleted': deleted[i],- 'pinned': parseInt(pinned[i] || 0), // For sorting purposes- 'pin-icon': pinned[i] === '1' ? 'icon-pushpin' : 'none'- });- }-- // Float pinned topics to the top- topics = topics.sort(function(a, b) {- return b.pinned - a.pinned;- });-- callback({- 'category_name' : category_id ? category_name : 'Recent',- 'show_topic_button' : category_id ? 'show' : 'hidden',- 'category_id': category_id || 0,- 'topics': topics- });-- });- }- else {- callback({- 'category_name' : category_id ? category_name : 'Recent',- 'show_topic_button' : category_id ? 'show' : 'hidden',- 'category_id': category_id || 0,- 'topics': []- });- }---- });- });- }-- Topics.post = function(socket, uid, title, content, category_id) {- if (!category_id) throw new Error('Attempted to post without a category_id');-- if (uid === 0) {- socket.emit('event:alert', {- title: 'Thank you for posting',- message: 'Since you are unregistered, your post is awaiting approval. Click here to register now.',- type: 'warning',- timeout: 7500,- clickfn: function() {- ajaxify.go('register');- }- });- return; // for now, until anon code is written.- }-- RDB.incr('global:next_topic_id', function(tid) {-- // Global Topics- if (uid == null) uid = 0;- if (uid !== null) {- RDB.db.sadd('topics:tid', tid);- } else {- // need to add some unique key sent by client so we can update this with the real uid later- RDB.lpush('topics:queued:tid', tid);- }-- var slug = tid + '/' + utils.slugify(title);-- // Topic Info- RDB.set('tid:' + tid + ':title', title);- RDB.set('tid:' + tid + ':uid', uid);- RDB.set('tid:' + tid + ':slug', slug);- RDB.set('tid:' + tid + ':timestamp', new Date().getTime());--- RDB.set('topic:slug:' + slug + ':tid', tid);-- // Posts- posts.create(uid, tid, content, function(pid) {- if (pid > 0) RDB.lpush('tid:' + tid + ':posts', pid);- });--- // User Details - move this out later- RDB.lpush('uid:' + uid + ':topics', tid);-- socket.emit('event:alert', {- title: 'Thank you for posting',- message: 'You have successfully posted. Click here to view your post.',- type: 'notify',- timeout: 2000- });--- // in future it may be possible to add topics to several categories, so leaving the door open here.- RDB.db.sadd('categories:' + category_id + ':tid', tid);- RDB.set('tid:' + tid + ':cid', category_id);- categories.get_category([category_id], function(data) {- RDB.set('tid:' + tid + ':category_name', data.categories[0].name);- RDB.set('tid:' + tid + ':category_slug', data.categories[0].slug);- });-- });- };-- Topics.lock = function(tid, uid, socket) {- user.getUserField(uid, 'reputation', function(rep) {- if (rep >= configs.privilege_thresholds.manage_thread) {- // Mark thread as locked- RDB.set('tid:' + tid + ':locked', 1);-- if (socket) {- io.sockets.in('topic_' + tid).emit('event:topic_locked', {- tid: tid,- status: 'ok'- });- }- }- });- }-- Topics.unlock = function(tid, uid, socket) {- user.getUserField(uid, 'reputation', function(rep) {- if (rep >= configs.privilege_thresholds.manage_thread) {- // Mark thread as locked- RDB.del('tid:' + tid + ':locked');-- if (socket) {- io.sockets.in('topic_' + tid).emit('event:topic_unlocked', {- tid: tid,- status: 'ok'- });- }- }- });- }-- Topics.delete = function(tid, uid, socket) {- user.getUserField(uid, 'reputation', function(rep) {- if (rep >= configs.privilege_thresholds.manage_thread) {- // Mark thread as deleted- RDB.set('tid:' + tid + ':deleted', 1);- Topics.lock(tid, uid);-- if (socket) {- io.sockets.in('topic_' + tid).emit('event:topic_deleted', {- tid: tid,- status: 'ok'- });- }- }- });- }-- Topics.restore = function(tid, uid, socket) {- user.getUserField(uid, 'reputation', function(rep) {- if (rep >= configs.privilege_thresholds.manage_thread) {- // Mark thread as deleted- RDB.del('tid:' + tid + ':deleted');- Topics.unlock(tid, uid);-- if (socket) {- io.sockets.in('topic_' + tid).emit('event:topic_restored', {- tid: tid,- status: 'ok'- });- }- }- });- }-- Topics.pin = function(tid, uid, socket) {- user.getUserField(uid, 'reputation', function(rep) {- if (rep >= configs.privilege_thresholds.manage_thread) {- // Mark thread as deleted- RDB.set('tid:' + tid + ':pinned', 1);-- if (socket) {- io.sockets.in('topic_' + tid).emit('event:topic_pinned', {- tid: tid,- status: 'ok'- });- }- }- });- }-- Topics.unpin = function(tid, uid, socket) {- user.getUserField(uid, 'reputation', function(rep) {- if (rep >= configs.privilege_thresholds.manage_thread) {- // Mark thread as deleted- RDB.del('tid:' + tid + ':pinned');-- if (socket) {- io.sockets.in('topic_' + tid).emit('event:topic_unpinned', {- tid: tid,- status: 'ok'- });- }- }- });- }-- Topics.move = function(tid, cid, socket) {- RDB.get('tid:' + tid + ':cid', function(oldCid) {- RDB.db.smove('categories:' + oldCid + ':tid', 'categories:' + cid + ':tid', tid, function(err, result) {- if (!err && result === 1) {- RDB.set('tid:' + tid + ':cid', cid);- categories.get_category([cid], function(data) {- RDB.set('tid:' + tid + ':category_name', data.categories[0].name);- RDB.set('tid:' + tid + ':category_slug', data.categories[0].slug);- });- socket.emit('api:topic.move', { status: 'ok' });- io.sockets.in('topic_' + tid).emit('event:topic_moved', { tid: tid });- } else {- socket.emit('api:topic.move', { status: 'error' });- }- });- });- }+var RDB = require('./redis.js'),+ posts = require('./posts.js'),+ utils = require('./utils.js'),+ user = require('./user.js'),+ configs = require('../config.js'),+ categories = require('./categories.js');++(function(Topics) {++ Topics.get_by_category = function(callback, category, start, end) {++ }++++ Topics.get = function(callback, category_id, start, end) {+ if (start == null) start = 0;+ if (end == null) end = start + 10;++ //build a proper wrapper for this and move it into above function later+ var range_var = (category_id) ? 'categories:' + category_id + ':tid' : 'topics:tid';++ RDB.smembers(range_var, function(err, tids) {+ var title = [],+ uid = [],+ timestamp = [],+ slug = [],+ postcount = [],+ locked = [],+ deleted = [],+ pinned = [];++ for (var i=0, ii=tids.length; i<ii; i++) {+ title.push('tid:' + tids[i] + ':title');+ uid.push('tid:' + tids[i] + ':uid');+ timestamp.push('tid:' + tids[i] + ':timestamp');+ slug.push('tid:' + tids[i] + ':slug');+ postcount.push('tid:' + tids[i] + ':postcount');+ locked.push('tid:' + tids[i] + ':locked');+ deleted.push('tid:' + tids[i] + ':deleted');+ pinned.push('tid:' + tids[i] + ':pinned');+ }++ var multi = RDB.multi()+ .get('cid:' + category_id + ':name');++ if (tids.length > 0) {+ multi+ .mget(title)+ .mget(uid)+ .mget(timestamp)+ .mget(slug)+ .mget(postcount)+ .mget(locked)+ .mget(deleted)+ .mget(pinned)+ }+++ multi.exec(function(err, replies) {+ category_name = replies[0];+ var topics = [];++ if (tids.length > 0) {+ title = replies[1];+ uid = replies[2];+ timestamp = replies[3];+ slug = replies[4];+ postcount = replies[5];+ locked = replies[6];+ deleted = replies[7];+ pinned = replies[8];++ user.get_usernames_by_uids(uid, function(userNames) {++ for (var i=0, ii=title.length; i<ii; i++) {++ topics.push({+ 'title' : title[i],+ 'uid' : uid[i],+ 'username': userNames[i],+ 'timestamp' : timestamp[i],+ 'relativeTime': utils.relativeTime(timestamp[i]),+ 'slug' : slug[i],+ 'post_count' : postcount[i],+ 'lock-icon': locked[i] === '1' ? 'icon-lock' : 'none',+ 'deleted': deleted[i],+ 'pinned': parseInt(pinned[i] || 0), // For sorting purposes+ 'pin-icon': pinned[i] === '1' ? 'icon-pushpin' : 'none'+ });+ }++ // Float pinned topics to the top+ topics = topics.sort(function(a, b) {+ return b.pinned - a.pinned;+ });++ callback({+ 'category_name' : category_id ? category_name : 'Recent',+ 'show_topic_button' : category_id ? 'show' : 'hidden',+ 'category_id': category_id || 0,+ 'topics': topics+ });++ });+ }+ else {+ callback({+ 'category_name' : category_id ? category_name : 'Recent',+ 'show_topic_button' : category_id ? 'show' : 'hidden',+ 'category_id': category_id || 0,+ 'topics': []+ });+ }++++ });+ });+ }++ Topics.post = function(socket, uid, title, content, category_id) {+ if (!category_id) throw new Error('Attempted to post without a category_id');++ if (uid === 0) {+ socket.emit('event:alert', {+ title: 'Thank you for posting',+ message: 'Since you are unregistered, your post is awaiting approval. Click here to register now.',+ type: 'warning',+ timeout: 7500,+ clickfn: function() {+ ajaxify.go('register');+ }+ });+ return; // for now, until anon code is written.+ }++ RDB.incr('global:next_topic_id', function(err, tid) {+ RDB.handle(err);++ // Global Topics+ if (uid == null) uid = 0;+ if (uid !== null) {+ RDB.sadd('topics:tid', tid);+ } else {+ // need to add some unique key sent by client so we can update this with the real uid later+ RDB.lpush('topics:queued:tid', tid);+ }++ var slug = tid + '/' + utils.slugify(title);++ // Topic Info+ RDB.set('tid:' + tid + ':title', title);+ RDB.set('tid:' + tid + ':uid', uid);+ RDB.set('tid:' + tid + ':slug', slug);+ RDB.set('tid:' + tid + ':timestamp', new Date().getTime());+++ RDB.set('topic:slug:' + slug + ':tid', tid);++ // Posts+ posts.create(uid, tid, content, function(pid) {+ if (pid > 0) RDB.lpush('tid:' + tid + ':posts', pid);+ });+++ // User Details - move this out later+ RDB.lpush('uid:' + uid + ':topics', tid);++ socket.emit('event:alert', {+ title: 'Thank you for posting',+ message: 'You have successfully posted. Click here to view your post.',+ type: 'notify',+ timeout: 2000+ });+++ // in future it may be possible to add topics to several categories, so leaving the door open here.+ RDB.sadd('categories:' + category_id + ':tid', tid);+ RDB.set('tid:' + tid + ':cid', category_id);+ categories.get_category([category_id], function(data) {+ RDB.set('tid:' + tid + ':category_name', data.categories[0].name);+ RDB.set('tid:' + tid + ':category_slug', data.categories[0].slug);+ });++ });+ };++ Topics.lock = function(tid, uid, socket) {+ user.getUserField(uid, 'reputation', function(rep) {+ if (rep >= configs.privilege_thresholds.manage_thread) {+ // Mark thread as locked+ RDB.set('tid:' + tid + ':locked', 1);++ if (socket) {+ io.sockets.in('topic_' + tid).emit('event:topic_locked', {+ tid: tid,+ status: 'ok'+ });+ }+ }+ });+ }++ Topics.unlock = function(tid, uid, socket) {+ user.getUserField(uid, 'reputation', function(rep) {+ if (rep >= configs.privilege_thresholds.manage_thread) {+ // Mark thread as locked+ RDB.del('tid:' + tid + ':locked');++ if (socket) {+ io.sockets.in('topic_' + tid).emit('event:topic_unlocked', {+ tid: tid,+ status: 'ok'+ });+ }+ }+ });+ }++ Topics.delete = function(tid, uid, socket) {+ user.getUserField(uid, 'reputation', function(rep) {+ if (rep >= configs.privilege_thresholds.manage_thread) {+ // Mark thread as deleted+ RDB.set('tid:' + tid + ':deleted', 1);+ Topics.lock(tid, uid);++ if (socket) {+ io.sockets.in('topic_' + tid).emit('event:topic_deleted', {+ tid: tid,+ status: 'ok'+ });+ }+ }+ });+ }++ Topics.restore = function(tid, uid, socket) {+ user.getUserField(uid, 'reputation', function(rep) {+ if (rep >= configs.privilege_thresholds.manage_thread) {+ // Mark thread as deleted+ RDB.del('tid:' + tid + ':deleted');+ Topics.unlock(tid, uid);++ if (socket) {+ io.sockets.in('topic_' + tid).emit('event:topic_restored', {+ tid: tid,+ status: 'ok'+ });+ }+ }+ });+ }++ Topics.pin = function(tid, uid, socket) {+ user.getUserField(uid, 'reputation', function(rep) {+ if (rep >= configs.privilege_thresholds.manage_thread) {+ // Mark thread as deleted+ RDB.set('tid:' + tid + ':pinned', 1);++ if (socket) {+ io.sockets.in('topic_' + tid).emit('event:topic_pinned', {+ tid: tid,+ status: 'ok'+ });+ }+ }+ });+ }++ Topics.unpin = function(tid, uid, socket) {+ user.getUserField(uid, 'reputation', function(rep) {+ if (rep >= configs.privilege_thresholds.manage_thread) {+ // Mark thread as deleted+ RDB.del('tid:' + tid + ':pinned');++ if (socket) {+ io.sockets.in('topic_' + tid).emit('event:topic_unpinned', {+ tid: tid,+ status: 'ok'+ });+ }+ }+ });+ }++ Topics.move = function(tid, cid, socket) {+ RDB.get('tid:' + tid + ':cid', function(err, oldCid) {+ RDB.handle(err);++ RDB.smove('categories:' + oldCid + ':tid', 'categories:' + cid + ':tid', tid, function(err, result) {+ if (!err && result === 1) {+ RDB.set('tid:' + tid + ':cid', cid);+ categories.get_category([cid], function(data) {+ RDB.set('tid:' + tid + ':category_name', data.categories[0].name);+ RDB.set('tid:' + tid + ':category_slug', data.categories[0].slug);+ });+ socket.emit('api:topic.move', { status: 'ok' });+ io.sockets.in('topic_' + tid).emit('event:topic_moved', { tid: tid });+ } else {+ socket.emit('api:topic.move', { status: 'error' });+ }+ });+ });+ }}(exports));\ No newline at end of filediff --git a/src/user.js b/src/user.jsindex 99aa738703..d7d81e1bf5 100644--- a/src/user.js+++ b/src/user.js@@ -1,587 +1,630 @@-var config = require('../config.js'),- utils = require('./utils.js'),- RDB = require('./redis.js'),- crypto = require('crypto'),- emailjs = require('emailjs'),- emailjsServer = emailjs.server.connect(config.mailer),- bcrypt = require('bcrypt');--(function(User) {--- User.getUserField = function(uid, field, callback) {- RDB.db.hget('user:'+uid, field, function(err, data){- if(err === null)- callback(data);- else- console.log(err);- });- }-- User.getUserFields = function(uid, fields, callback) {- RDB.db.hmget('user:'+uid, fields, function(err, data){- if(err === null) {- var returnData = {};-- for(var i=0, ii=fields.length; i<ii; ++i) {- returnData[fields[i]] = data[i];- }-- callback(returnData);- }- else- console.log(err);- });- }-- // a function I feel should be built in user not sure how baris is tackling this so oppa chicken wrapper here- User.getMultipleUserFields = function(uids, fields, callback) {- var uuids = uids.filter(function(value, index, self) {- return self.indexOf(value) === index;- });-- var data = {},- loaded = 0;--- for (var i=0, ii=uuids.length; i<ii; i++) {- (function(user_id) {- User.getUserFields(user_id, fields, function(user_data){- data[user_id] = user_data;- loaded ++;- if (loaded == uuids.length) callback(data);- });- }(uuids[i]))- }- }-- User.getUserData = function(uid, callback) {-- RDB.db.hgetall('user:'+uid, function(err, data){- if(err === null)- {- if(data && data['password'])- delete data['password'];- callback(data);- }- else- console.log(err);- });- }-- User.updateUserFields = function(uid, data) {-- for(var key in data) {- User.setUserField(uid, key, data[key]);- }- }-- User.setUserField = function(uid, field, value) {- RDB.db.hset('user:'+uid, field, value);- }-- User.incrementUserFieldBy = function(uid, field, value) {- RDB.db.hincrby('user:'+uid, field, value);- }-- User.getUserList = function(callback){- var data = [];-- RDB.db.keys('user:*', function(err, userkeys){-- for(var i=0,ii=userkeys.length; i<ii; ++i) {-- RDB.db.hgetall(userkeys[i], function(err, userdata) {-- if(userdata && userdata.password)- delete userdata.password;-- data.push(userdata);-- if(data.length == userkeys.length)- callback(data);- });- }-- });- }-- User.loginViaLocal = function(username, password, next) {-- if (!username || !password) {- return next({- status: 'error',- message: 'invalid-user'- });- } else {- RDB.get('username:' + username + ':uid', function(uid) {- if (uid == null) {- return next({- status: 'error',- message: 'invalid-user'- });- }-- User.getUserField(uid, 'password', function(user_password) {- bcrypt.compare(password, user_password, function(err, res) {- if (res === true) {- next({- status: "ok",- user: {- uid: uid- }- });- } else {- next({- status: 'error',- message: 'invalid-password'- });- }- });- });- });- }- }-- User.loginViaTwitter = function(twid, handle, callback) {- User.get_uid_by_twitter_id(twid, function(uid) {- if (uid !== null) {- // Existing User- callback(null, {- uid: uid- });- } else {- // New User- User.create(handle, null, null, function(err, uid) {- if (err !== null) {- callback(err);- } else {- // Save twitter-specific information to the user- RDB.set('uid:' + uid + ':twid', twid);- RDB.set('twid:' + twid + ':uid', uid);- callback(null, {- uid: uid- });- }- });- }- });- }-- User.loginViaGoogle = function(gplusid, handle, email, callback) {- User.get_uid_by_google_id(gplusid, function(uid) {- if (uid !== null) {- // Existing User- callback(null, {- uid: uid- });- } else {- // New User- User.create(handle, null, email, function(err, uid) {- if (err !== null) {- callback(err);- } else {- // Save twitter-specific information to the user- RDB.set('uid:' + uid + ':gplusid', gplusid);- RDB.set('gplusid:' + gplusid + ':uid', uid);- callback(null, {- uid: uid- });- }- });- }- });- }-- User.loginViaFacebook = function(fbid, name, email, callback) {- User.get_uid_by_fbid(fbid, function(uid) {- if (uid !== null) {- // Existing User- callback(null, {- uid: uid- });- } else {- // New User- User.create(name, null, email, function(err, uid) {- if (err !== null) {- callback(err);- } else {- // Save twitter-specific information to the user- RDB.set('uid:' + uid + ':fbid', fbid);- RDB.set('fbid:' + fbid + ':uid', uid);- callback(null, {- uid: uid- });- }- });- }- });- }-- User.logout = function(sessionID, callback) {- User.get_uid_by_session(sessionID, function(uid) {- if (uid) {- RDB.del('sess:' + sessionID + ':uid');- RDB.del('uid:' + uid + ':session');- callback(true);- } else callback(false);- });- }-- User.create = function(username, password, email, callback) {-- if(!username) {- console.log("invalid registration data! username ["+username+"], password ["+password+"], email ["+email+"]");- return;- }-- // TODO : check if username email is unique!! -baris--- RDB.incr('global:next_user_id', function(uid) {-- console.log("Registering uid : " + uid);-- User.hashPassword(password, function(hash) {-- RDB.db.hmset('user:'+uid, {- 'username' : username,- 'fullname': '',- 'location':'',- 'birthday':'',- 'website':'',- 'email' : email,- 'joindate' : new Date().getTime(),- 'password' : hash,- 'picture' : User.createGravatarURLFromEmail(email),- 'reputation': 0,- 'postcount': 0- });-- RDB.set('username:' + username + ':uid', uid);- RDB.set('email:' + email +':uid', uid);-- if(email)- User.sendConfirmationEmail(email);-- RDB.incr('usercount', function(count) {- io.sockets.emit('user.count', {count: count});- });-- RDB.lpush('userlist', username);- io.sockets.emit('user.latest', {username: username});-- callback(null, uid);-- });-- });-- };-- User.createGravatarURLFromEmail = function(email) {- if(email) {- var md5sum = crypto.createHash('md5');- md5sum.update((email || '').toLowerCase());- var gravatarURL = 'http://www.gravatar.com/avatar/' + md5sum.digest('hex');- return gravatarURL;- }- else {- return "http://www.gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e";- }- }-- User.hashPassword = function(password, callback) {- if(!password) {- callback(password);- return;- }-- bcrypt.genSalt(10, function(err, salt) {- bcrypt.hash(password, salt, function(err, hash) {- callback(hash);- });- });- }-- User.sendConfirmationEmail = function (email) {- var confirm_code = utils.generateUUID(),- confirm_link = config.url + 'confirm/' + confirm_code,- confirm_email = global.templates['emails/header'] + global.templates['emails/email_confirm'].parse({'CONFIRM_LINK': confirm_link}) + global.templates['emails/footer'],- confirm_email_plaintext = global.templates['emails/email_confirm_plaintext'].parse({ 'CONFIRM_LINK': confirm_link });-- // Email confirmation code- RDB.set('email:' + email + ':confirm', confirm_code, 60*60*2);- RDB.set('confirm:' + confirm_code + ':email', email, 60*60*2); // Expire after 2 hours-- // Send intro email w/ confirm code- var message = emailjs.message.create({- text: confirm_email_plaintext,- from: config.mailer.from,- to: email,- subject: '[NodeBB] Registration Email Verification',- attachment: [- {- data: confirm_email,- alternative: true- }- ]- });-- emailjsServer.send(message, function(err, success) {- if (err)- console.log(err);- });- }--- User.exists = function(username, callback) {- User.get_uid_by_username(username, function(exists) {- exists = !!exists;-- if (callback)- callback(exists);- });- };-- User.count = function(socket) {- RDB.get('usercount', function(count) {- socket.emit('user.count', {count: (count === null) ? 0 : count});- });- };-- User.latest = function(socket) {- RDB.lrange('userlist', 0, 0, function(username) {- socket.emit('user.latest', {username: username});- });- }-- User.get_uid_by_username = function(username, callback) {- RDB.get('username:' + username + ':uid', callback);- };-- User.get_usernames_by_uids = function(uids, callback) {-- var usernames = [];-- for(var i=0, ii=uids.length; i<ii; ++i) {-- User.getUserField(uids[i],'username', function(username){-- usernames.push(username);-- if(usernames.length >= uids.length)- callback(usernames);- });- }- };-- User.get_uid_by_email = function(email, callback) {- RDB.get('email:' + email + ':uid', callback)- };-- User.get_uid_by_session = function(session, callback) {- RDB.get('sess:' + session + ':uid', callback);- };-- User.get_uid_by_twitter_id = function(twid, callback) {- RDB.get('twid:' + twid + ':uid', function(uid) {- callback(uid);- });- }-- User.get_uid_by_google_id = function(gplusid, callback) {- RDB.get('gplusid:' + gplusid + ':uid', function(uid) {- callback(uid);- });- }-- User.get_uid_by_fbid = function(fbid, callback) {- RDB.get('fbid:' + fbid + ':uid', function(uid) {- callback(uid);- });- }-- User.session_ping = function(sessionID, uid) {- // Start, replace, or extend a session- RDB.get('sess:' + sessionID, function(session) {- RDB.set('sess:' + sessionID + ':uid', uid, 60*60*24*14); // Login valid for two weeks- RDB.set('uid:' + uid + ':session', sessionID, 60*60*24*14);- });- }-- User.reset = {- validate: function(socket, code, callback) {- if (typeof callback !== 'function') callback = undefined;-- RDB.get('reset:' + code + ':uid', function(uid) {- if (uid !== null) {- RDB.get('reset:' + code + ':expiry', function(expiry) {- if (expiry >= +new Date()/1000|0) {- if (!callback) socket.emit('user:reset.valid', { valid: true });- else callback(true);- } else {- // Expired, delete from db- RDB.del('reset:' + code + ':uid');- RDB.del('reset:' + code + ':expiry');- if (!callback) socket.emit('user:reset.valid', { valid: false });- else callback(false);- }- });- } else {- if (!callback) socket.emit('user:reset.valid', { valid: false });- else callback(false);- }- });- },- send: function(socket, email) {- User.get_uid_by_email(email, function(uid) {- if (uid !== null) {- // Generate a new reset code- var reset_code = utils.generateUUID();- RDB.set('reset:' + reset_code + ':uid', uid);- RDB.set('reset:' + reset_code + ':expiry', (60*60)+new Date()/1000|0); // Active for one hour-- var reset_link = config.url + 'reset/' + reset_code,- reset_email = global.templates['emails/reset'].parse({'RESET_LINK': reset_link}),- reset_email_plaintext = global.templates['emails/reset_plaintext'].parse({ 'RESET_LINK': reset_link });-- var message = emailjs.message.create({- text: reset_email_plaintext,- from: config.mailer.from,- to: email,- subject: 'Password Reset Requested',- attachment: [- {- data: reset_email,- alternative: true- }- ]- });-- emailjsServer.send(message, function(err, success) {- if (err === null) {- socket.emit('user.send_reset', {- status: "ok",- message: "code-sent",- email: email- });- } else {- socket.emit('user.send_reset', {- status: "error",- message: "send-failed"- });- throw new Error(err);- }- });- } else {- socket.emit('user.send_reset', {- status: "error",- message: "invalid-email",- email: email- });- }- });- },- commit: function(socket, code, password) {- this.validate(code, function(validated) {- if (validated) {- RDB.get('reset:' + code + ':uid', function(uid) {-- User.setUserField(uid, 'password', password);- RDB.del('reset:' + code + ':uid');- RDB.del('reset:' + code + ':expiry');-- socket.emit('user:reset.commit', { status: 'ok' });- });- }- });- }- }-- User.email = {- exists: function(socket, email, callback) {- User.get_uid_by_email(email, function(exists) {- exists = !!exists;- if (typeof callback !== 'function') socket.emit('user.email.exists', { exists: exists });- else callback(exists);- });- },- confirm: function(code, callback) {- RDB.get('confirm:' + code + ':email', function(email) {- if (email !== null) {- RDB.set('email:' + email + ':confirm', true);- RDB.del('confirm:' + code + ':email');- callback({- status: 'ok'- });- } else {- callback({- status: 'not_ok'- });- }- });- }- }-- User.active = {- get_record : function(socket) {- RDB.mget(['global:active_user_record', 'global:active_user_record_date'], function(data) {- socket.emit('api:user.active.get_record', {record: data[0], timestamp: data[1]});- });- },-- get: function(callback) {- function user_record(total) {- RDB.get('global:active_user_record', function(record) {- if (total > record) {- RDB.set('global:active_user_record', total);- RDB.set('global:active_user_record_date', new Date().getTime());- }- });- }-- RDB.keys('active:*', function(active) {- var returnObj = {- users: 0,- anon: 0,- uids: []- },- keys = [];-- if (active.length > 0) {- for(var a in active) {- keys.push('sess:' + active[a].split(':')[1] + ':uid');- }-- RDB.mget(keys, function(uids) {- for(var u in uids) {- if (uids[u] !== null) {- if (returnObj.uids.indexOf(uids[u]) === -1) {- returnObj.users++;- returnObj.uids.push(uids[u]);- }- } else {- returnObj.anon++;- }- }-- user_record(returnObj.anon + returnObj.users);-- if (callback === undefined) {- io.sockets.emit('api:user.active.get', returnObj)- } else {- callback(returnObj);- }- });- } else {- io.sockets.emit('api:user.active.get', returnObj)- }- });- },- register: function(sessionID) {- RDB.set('active:' + sessionID, '', 60*10); // Active state persists for 10 minutes- this.get();- }- }+var config = require('../config.js'),+ utils = require('./utils.js'),+ RDB = require('./redis.js'),+ crypto = require('crypto'),+ emailjs = require('emailjs'),+ emailjsServer = emailjs.server.connect(config.mailer),+ bcrypt = require('bcrypt');++(function(User) {+++ User.getUserField = function(uid, field, callback) {+ RDB.hget('user:'+uid, field, function(err, data){+ if(err === null)+ callback(data);+ else+ console.log(err);+ });+ }++ User.getUserFields = function(uid, fields, callback) {+ RDB.hmget('user:'+uid, fields, function(err, data){+ if(err === null) {+ var returnData = {};++ for(var i=0, ii=fields.length; i<ii; ++i) {+ returnData[fields[i]] = data[i];+ }++ callback(returnData);+ }+ else+ console.log(err);+ });+ }++ // a function I feel should be built in user not sure how baris is tackling this so oppa chicken wrapper here+ User.getMultipleUserFields = function(uids, fields, callback) {+ var uuids = uids.filter(function(value, index, self) {+ return self.indexOf(value) === index;+ });++ var data = {},+ loaded = 0;+++ for (var i=0, ii=uuids.length; i<ii; i++) {+ (function(user_id) {+ User.getUserFields(user_id, fields, function(user_data){+ data[user_id] = user_data;+ loaded ++;+ if (loaded == uuids.length) callback(data);+ });+ }(uuids[i]))+ }+ }++ User.getUserData = function(uid, callback) {++ RDB.hgetall('user:'+uid, function(err, data){+ if(err === null)+ {+ if(data && data['password'])+ delete data['password'];+ callback(data);+ }+ else+ console.log(err);+ });+ }++ User.updateUserFields = function(uid, data) {++ for(var key in data) {+ User.setUserField(uid, key, data[key]);+ }+ }++ User.setUserField = function(uid, field, value) {+ RDB.hset('user:'+uid, field, value);+ }++ User.incrementUserFieldBy = function(uid, field, value) {+ RDB.hincrby('user:'+uid, field, value);+ }++ User.getUserList = function(callback){+ var data = [];++ RDB.keys('user:*', function(err, userkeys){++ for(var i=0,ii=userkeys.length; i<ii; ++i) {++ RDB.hgetall(userkeys[i], function(err, userdata) {++ if(userdata && userdata.password)+ delete userdata.password;++ data.push(userdata);++ if(data.length == userkeys.length)+ callback(data);+ });+ }++ });+ }++ User.loginViaLocal = function(username, password, next) {++ if (!username || !password) {+ return next({+ status: 'error',+ message: 'invalid-user'+ });+ } else {+ RDB.get('username:' + username + ':uid', function(err, uid) {+ RDB.handle(err);++ if (uid == null) {+ return next({+ status: 'error',+ message: 'invalid-user'+ });+ }++ User.getUserField(uid, 'password', function(user_password) {+ bcrypt.compare(password, user_password, function(err, res) {+ if (res === true) {+ next({+ status: "ok",+ user: {+ uid: uid+ }+ });+ } else {+ next({+ status: 'error',+ message: 'invalid-password'+ });+ }+ });+ });+ });+ }+ }++ User.loginViaTwitter = function(twid, handle, callback) {+ User.get_uid_by_twitter_id(twid, function(uid) {+ if (uid !== null) {+ // Existing User+ callback(null, {+ uid: uid+ });+ } else {+ // New User+ User.create(handle, null, null, function(err, uid) {+ if (err !== null) {+ callback(err);+ } else {+ // Save twitter-specific information to the user+ RDB.set('uid:' + uid + ':twid', twid);+ RDB.set('twid:' + twid + ':uid', uid);+ callback(null, {+ uid: uid+ });+ }+ });+ }+ });+ }++ User.loginViaGoogle = function(gplusid, handle, email, callback) {+ User.get_uid_by_google_id(gplusid, function(uid) {+ if (uid !== null) {+ // Existing User+ callback(null, {+ uid: uid+ });+ } else {+ // New User+ User.create(handle, null, email, function(err, uid) {+ if (err !== null) {+ callback(err);+ } else {+ // Save twitter-specific information to the user+ RDB.set('uid:' + uid + ':gplusid', gplusid);+ RDB.set('gplusid:' + gplusid + ':uid', uid);+ callback(null, {+ uid: uid+ });+ }+ });+ }+ });+ }++ User.loginViaFacebook = function(fbid, name, email, callback) {+ User.get_uid_by_fbid(fbid, function(uid) {+ if (uid !== null) {+ // Existing User+ callback(null, {+ uid: uid+ });+ } else {+ // New User+ User.create(name, null, email, function(err, uid) {+ if (err !== null) {+ callback(err);+ } else {+ // Save twitter-specific information to the user+ RDB.set('uid:' + uid + ':fbid', fbid);+ RDB.set('fbid:' + fbid + ':uid', uid);+ callback(null, {+ uid: uid+ });+ }+ });+ }+ });+ }++ User.logout = function(sessionID, callback) {+ User.get_uid_by_session(sessionID, function(uid) {+ if (uid) {+ RDB.del('sess:' + sessionID + ':uid');+ RDB.del('uid:' + uid + ':session');+ callback(true);+ } else callback(false);+ });+ }++ User.create = function(username, password, email, callback) {++ if(!username) {+ console.log("invalid registration data! username ["+username+"], password ["+password+"], email ["+email+"]");+ return;+ }++ // TODO : check if username email is unique!! -baris+++ RDB.incr('global:next_user_id', function(err, uid) {+ RDB.handle(err);++ console.log("Registering uid : " + uid);++ User.hashPassword(password, function(hash) {++ RDB.hmset('user:'+uid, {+ 'username' : username,+ 'fullname': '',+ 'location':'',+ 'birthday':'',+ 'website':'',+ 'email' : email,+ 'joindate' : new Date().getTime(),+ 'password' : hash,+ 'picture' : User.createGravatarURLFromEmail(email),+ 'reputation': 0,+ 'postcount': 0+ });++ RDB.set('username:' + username + ':uid', uid);+ RDB.set('email:' + email +':uid', uid);++ if(email)+ User.sendConfirmationEmail(email);++ RDB.incr('usercount', function(err, count) {+ RDB.handle(err);++ io.sockets.emit('user.count', {count: count});+ });++ RDB.lpush('userlist', username);+ io.sockets.emit('user.latest', {username: username});++ callback(null, uid);++ });++ });++ };++ User.createGravatarURLFromEmail = function(email) {+ if(email) {+ var md5sum = crypto.createHash('md5');+ md5sum.update((email || '').toLowerCase());+ var gravatarURL = 'http://www.gravatar.com/avatar/' + md5sum.digest('hex');+ return gravatarURL;+ }+ else {+ return "http://www.gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e";+ }+ }++ User.hashPassword = function(password, callback) {+ if(!password) {+ callback(password);+ return;+ }++ bcrypt.genSalt(10, function(err, salt) {+ bcrypt.hash(password, salt, function(err, hash) {+ callback(hash);+ });+ });+ }++ User.sendConfirmationEmail = function (email) {+ var confirm_code = utils.generateUUID(),+ confirm_link = config.url + 'confirm/' + confirm_code,+ confirm_email = global.templates['emails/header'] + global.templates['emails/email_confirm'].parse({'CONFIRM_LINK': confirm_link}) + global.templates['emails/footer'],+ confirm_email_plaintext = global.templates['emails/email_confirm_plaintext'].parse({ 'CONFIRM_LINK': confirm_link });++ // Email confirmation code+ var expiry_time = 60*60*2, // Expire after 2 hours+ email_key = 'email:' + email + ':confirm',+ confirm_key = 'confirm:' + confirm_code + ':email';++ RDB.set(email_key, confirm_code);+ RDB.expire(email_key, expiry_time);+ RDB.set(confirm_key, email);+ RDB.expire(confirm_key, expiry_time);++ // Send intro email w/ confirm code+ var message = emailjs.message.create({+ text: confirm_email_plaintext,+ from: config.mailer.from,+ to: email,+ subject: '[NodeBB] Registration Email Verification',+ attachment: [+ {+ data: confirm_email,+ alternative: true+ }+ ]+ });++ emailjsServer.send(message, function(err, success) {+ if (err)+ console.log(err);+ });+ }+++ User.exists = function(username, callback) {+ User.get_uid_by_username(username, function(exists) {+ exists = !!exists;++ if (callback)+ callback(exists);+ });+ };++ User.count = function(socket) {+ RDB.get('usercount', function(err, count) {+ RDB.handle(err);+ socket.emit('user.count', {count: (count === null) ? 0 : count});+ });+ };++ User.latest = function(socket) {+ RDB.lrange('userlist', 0, 0, function(err, username) {+ RDB.handle(err);+ socket.emit('user.latest', {username: username});+ });+ }++ User.get_uid_by_username = function(username, callback) {+ RDB.get('username:' + username + ':uid', function(err, data) {+ RDB.handle(err);+ callback(data);+ });+ };++ User.get_usernames_by_uids = function(uids, callback) {++ var usernames = [];++ for(var i=0, ii=uids.length; i<ii; ++i) {++ User.getUserField(uids[i],'username', function(username){++ usernames.push(username);++ if(usernames.length >= uids.length)+ callback(usernames);+ });+ }+ };++ User.get_uid_by_email = function(email, callback) {+ RDB.get('email:' + email + ':uid', function(err, data) {+ RDB.handle(err);+ callback(data);+ });+ };++ User.get_uid_by_session = function(session, callback) {+ RDB.get('sess:' + session + ':uid', function(err, data) {+ RDB.handle(err);+ callback(data);+ });+ };++ User.get_uid_by_twitter_id = function(twid, callback) {+ RDB.get('twid:' + twid + ':uid', function(err, uid) {+ RDB.handle(err);+ callback(uid);+ });+ }++ User.get_uid_by_google_id = function(gplusid, callback) {+ RDB.get('gplusid:' + gplusid + ':uid', function(err, uid) {+ RDB.handle(err);+ callback(uid);+ });+ }++ User.get_uid_by_fbid = function(fbid, callback) {+ RDB.get('fbid:' + fbid + ':uid', function(err, uid) {+ RDB.handle(err);+ callback(uid);+ });+ }++ User.session_ping = function(sessionID, uid) {+ // Start, replace, or extend a session+ RDB.get('sess:' + sessionID, function(err, session) {+ RDB.handle(err);+ RDB.set('sess:' + sessionID + ':uid', uid, 60*60*24*14); // Login valid for two weeks+ RDB.set('uid:' + uid + ':session', sessionID, 60*60*24*14);+ });+ }++ User.reset = {+ validate: function(socket, code, callback) {+ if (typeof callback !== 'function') callback = undefined;++ RDB.get('reset:' + code + ':uid', function(err, uid) {+ RDB.handle(err);++ if (uid !== null) {+ RDB.get('reset:' + code + ':expiry', function(err, expiry) {+ RDB.handle(err);++ if (expiry >= +new Date()/1000|0) {+ if (!callback) socket.emit('user:reset.valid', { valid: true });+ else callback(true);+ } else {+ // Expired, delete from db+ RDB.del('reset:' + code + ':uid');+ RDB.del('reset:' + code + ':expiry');+ if (!callback) socket.emit('user:reset.valid', { valid: false });+ else callback(false);+ }+ });+ } else {+ if (!callback) socket.emit('user:reset.valid', { valid: false });+ else callback(false);+ }+ });+ },+ send: function(socket, email) {+ User.get_uid_by_email(email, function(uid) {+ if (uid !== null) {+ // Generate a new reset code+ var reset_code = utils.generateUUID();+ RDB.set('reset:' + reset_code + ':uid', uid);+ RDB.set('reset:' + reset_code + ':expiry', (60*60)+new Date()/1000|0); // Active for one hour++ var reset_link = config.url + 'reset/' + reset_code,+ reset_email = global.templates['emails/reset'].parse({'RESET_LINK': reset_link}),+ reset_email_plaintext = global.templates['emails/reset_plaintext'].parse({ 'RESET_LINK': reset_link });++ var message = emailjs.message.create({+ text: reset_email_plaintext,+ from: config.mailer.from,+ to: email,+ subject: 'Password Reset Requested',+ attachment: [+ {+ data: reset_email,+ alternative: true+ }+ ]+ });++ emailjsServer.send(message, function(err, success) {+ if (err === null) {+ socket.emit('user.send_reset', {+ status: "ok",+ message: "code-sent",+ email: email+ });+ } else {+ socket.emit('user.send_reset', {+ status: "error",+ message: "send-failed"+ });+ throw new Error(err);+ }+ });+ } else {+ socket.emit('user.send_reset', {+ status: "error",+ message: "invalid-email",+ email: email+ });+ }+ });+ },+ commit: function(socket, code, password) {+ this.validate(code, function(validated) {+ if (validated) {+ RDB.get('reset:' + code + ':uid', function(err, uid) {+ RDB.handle(err);++ User.setUserField(uid, 'password', password);+ RDB.del('reset:' + code + ':uid');+ RDB.del('reset:' + code + ':expiry');++ socket.emit('user:reset.commit', { status: 'ok' });+ });+ }+ });+ }+ }++ User.email = {+ exists: function(socket, email, callback) {+ User.get_uid_by_email(email, function(exists) {+ exists = !!exists;+ if (typeof callback !== 'function') socket.emit('user.email.exists', { exists: exists });+ else callback(exists);+ });+ },+ confirm: function(code, callback) {+ RDB.get('confirm:' + code + ':email', function(err, email) {+ RDB.handle(err);++ if (email !== null) {+ RDB.set('email:' + email + ':confirm', true);+ RDB.del('confirm:' + code + ':email');+ callback({+ status: 'ok'+ });+ } else {+ callback({+ status: 'not_ok'+ });+ }+ });+ }+ }++ User.active = {+ get_record : function(socket) {+ RDB.mget(['global:active_user_record', 'global:active_user_record_date'], function(err, data) {+ RDB.handle(err);+ socket.emit('api:user.active.get_record', {record: data[0], timestamp: data[1]});+ });+ },++ get: function(callback) {+ function user_record(total) {+ RDB.get('global:active_user_record', function(err, record) {+ RDB.handle(err);++ if (total > record) {+ RDB.set('global:active_user_record', total);+ RDB.set('global:active_user_record_date', new Date().getTime());+ }+ });+ }++ RDB.keys('active:*', function(err, active) {+ RDB.handle(err);++ var returnObj = {+ users: 0,+ anon: 0,+ uids: []+ },+ keys = [];++ if (active.length > 0) {+ for(var a in active) {+ keys.push('sess:' + active[a].split(':')[1] + ':uid');+ }++ RDB.mget(keys, function(err, uids) {+ RDB.handle(err);++ for(var u in uids) {+ if (uids[u] !== null) {+ if (returnObj.uids.indexOf(uids[u]) === -1) {+ returnObj.users++;+ returnObj.uids.push(uids[u]);+ }+ } else {+ returnObj.anon++;+ }+ }++ user_record(returnObj.anon + returnObj.users);++ if (callback === undefined) {+ io.sockets.emit('api:user.active.get', returnObj)+ } else {+ callback(returnObj);+ }+ });+ } else {+ io.sockets.emit('api:user.active.get', returnObj)+ }+ });+ },+ register: function(sessionID) {+ // Active state persists for 10 minutes+ var active_session = 'active:' + sessionID;+ RDB.set(active_session, '');+ RDB.expire(active_session, 60*10)+ this.get();+ }+ }}(exports));\ No newline at end of file