From bb7adc0114623aa03df0b35b38b17c92e8fdb946 Mon Sep 17 00:00:00 2001 From: Micha Gorelick Date: Sat, 19 Sep 2015 13:47:10 -0400 Subject: [PATCH 1/6] added rethinkdb --- bootstrap.sh | 21 ++++++-- conf/oratory_rethinkdb.conf | 102 ++++++++++++++++++++++++++++++++++++ package.json | 2 +- 3 files changed, 120 insertions(+), 5 deletions(-) create mode 100644 conf/oratory_rethinkdb.conf diff --git a/bootstrap.sh b/bootstrap.sh index a86327e..f4ee5d5 100644 --- a/bootstrap.sh +++ b/bootstrap.sh @@ -3,11 +3,19 @@ cd /vagrant echo Provisioning system... echo Installing prereq packages... export DEBIAN_FRONTEND=noninteractive -# Mongo -sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 -echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list + +#rethinkdb +source /etc/lsb-release && echo "deb http://download.rethinkdb.com/apt $DISTRIB_CODENAME main" | sudo tee /etc/apt/sources.list.d/rethinkdb.list +wget -qO- http://download.rethinkdb.com/apt/pubkey.gpg | sudo apt-key add - + sudo apt-get update -sudo apt-get install -y python-software-properties gcc make build-essential mongodb-10gen imagemagick +sudo apt-get install -y \ + python-software-properties \ + gcc \ + make \ + build-essential \ + rethinkdb \ + imagemagick # Forget about apt packages for node, just grab a local copy of node nodeVersion=0.12.7 @@ -39,6 +47,11 @@ npm install iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 465 -j REDIRECT --to-port 55465 +sudo ln -sf /vagrant/conf/oratory_rethinkdb.conf /etc/rethinkdb/instances.d/oratory.conf +sudo mkdir /data +sudo chown -R rethinkdb:rethinkdb /data +sudo service rethinkdb start + #start the forever server sudo npm install -g forever touch users.js # this file must exist, but isn't checked in diff --git a/conf/oratory_rethinkdb.conf b/conf/oratory_rethinkdb.conf new file mode 100644 index 0000000..fcfd128 --- /dev/null +++ b/conf/oratory_rethinkdb.conf @@ -0,0 +1,102 @@ +# +# RethinkDB instance configuration sample +# +# - Give this file the extension .conf and put it in /etc/rethinkdb/instances.d in order to enable it. +# - See http://www.rethinkdb.com/docs/guides/startup/ for the complete documentation +# - Uncomment an option to change its value. +# + +############################### +## RethinkDB configuration +############################### + +### Process options + +## User and group used to run rethinkdb +## Command line default: do not change user or group +## Init script default: rethinkdb user and group +runuser=rethinkdb +rungroup=rethinkdb + +## Stash the pid in this file when the process is running +## Command line default: none +## Init script default: /var/run/rethinkdb//pid_file (where is the name of this config file without the extension) +# pid-file=/var/run/rethinkdb/rethinkdb.pid + +### File path options + +## Directory to store data and metadata +## Command line default: ./rethinkdb_data +## Init script default: /var/lib/rethinkdb// (where is the name of this file without the extension) +directory=/data/ + +## Log file options +## Default: /log_file +# log-file=/var/log/rethinkdb + +### Network options + +## Address of local interfaces to listen on when accepting connections +## May be 'all' or an IP address, loopback addresses are enabled by default +## Default: all local addresses +bind=127.0.0.1 + +## Address that other rethinkdb instances will use to connect to this server. +## It can be specified multiple times +# canonical-address= + +## The port for rethinkdb protocol for client drivers +## Default: 28015 + port-offset +# driver-port=28015 + +## The port for receiving connections from other nodes +## Default: 29015 + port-offset +# cluster-port=29015 + +## The host:port of a node that rethinkdb will connect to +## This option can be specified multiple times. +## Default: none +# join=example.com:29015 + +## All ports used locally will have this value added +## Default: 0 +# port-offset=0 + +## r.http(...) queries will use the given server as a web proxy +## Default: no proxy +# reql-http-proxy=socks5://example.com:1080 + +### Web options + +## Port for the http admin console +## Default: 8080 + port-offset +# http-port=8080 + +## Disable web administration console +# no-http-admin + +### CPU options + +## The number of cores to use +## Default: total number of cores of the CPU +# cores=2 + +### Memory options + +## Size of the cache in MB +## Default: Half of the available RAM on startup +# cache-size=1024 + +### Disk + +## How many simultaneous I/O operations can happen at the same time +# io-threads=64 + +## Enable direct I/O +# direct-io + +### Meta + +## The name for this server (as will appear in the metadata). +## If not specified, it will be randomly chosen from a short list of names. +server-name=oratory diff --git a/package.json b/package.json index f27da56..e02c407 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "lodash": "^2.4.1", "method-override": "^1.0.0", "moment": "*", - "mongojs": "*", + "rethinkdb": "*", "nodemailer": "*", "nodemailer-smtp-transport": "*", "q": "*", From a45eff30557ed53da1f42ae5501118f2c994b2b5 Mon Sep 17 00:00:00 2001 From: Micha Gorelick Date: Sat, 19 Sep 2015 16:20:37 -0400 Subject: [PATCH 2/6] first pass at rethinkdb --- api/items.js | 424 +++++++++++++++++++++++++--------------------- api/lock.js | 86 +++++----- api/proposals.js | 66 ++++---- database/utils.js | 42 +++-- server.js | 49 ++++-- 5 files changed, 376 insertions(+), 291 deletions(-) diff --git a/api/items.js b/api/items.js index 1f8ffcc..51ccecd 100644 --- a/api/items.js +++ b/api/items.js @@ -7,6 +7,7 @@ var globalState = require("../server"), * @desc various dependencies */ var q = require('q'); +var r = require('rethinkdb'); var _ = require('underscore'); var __ = require('lodash'); @@ -14,6 +15,22 @@ var dbInfo = require("../database/dbInfo"); var dbHelper = require("../database/utils"); __.assign(root, dbHelper); +/* UTILS */ +_.mixin({ + compactObject: function(o) { + _.each(o, function(v, k) { + if(!v) { + delete o[k]; + } + }); + return o; + } +}); +function isEmpty(obj) { + return Object.keys(obj).length === 0; +} + + /** * @api - get database * @desc grabs everything in the database (only used by humans to see the contents of the database) @@ -21,7 +38,10 @@ __.assign(root, dbHelper); * @return object - full database */ app.get('/api/getDatabase', function (req, res) { - db.itemdb.find(function (err, docs) { + r.expr({ + "items" : r.tables("items"), + "history" : r.tables("history"), + }).run(db, function(err, docs) { if(err){ console.log('(error getting database) '+err);}else { res.send(docs); } }); }); @@ -38,18 +58,20 @@ app.get('/api/getDatabase', function (req, res) { * @return object - array of "items" */ app.post('/api/getItems', express.json(), function (req, res) { - //if(!req.session.user){ - // res.send({}); - //} else { - var query = {}; - if (req.body.type) { query['type'] = req.body.type; } - if (req.body.forUID) { query['forUID'] = req.body.forUID; } - if (req.body.forOwner) { query['forOwner'] = req.body.forOwner; } - else { query = { $or:_(dbInfo.types).map(function(item){ return {'type':item.name}; }) }; } - db.itemdb.find(query,function (err, docs) { - if(err){ console.log('(error getting items) '+err); }else{ res.send(docs); } - }); - //} + var query = r.tables("items"), + fields = _.pick(req.body, 'type', 'forUID', 'forOwner').compactObject(); + + if (isEmpty(fields)) { + var keys = _(dbInfo.types).map(function(item){ + return item.name; + }); + query.getAll.apply(query, keys.concat({index:"type"})); + } else { + query.filter(fields); + } + query.run(db, function (err, docs) { + if(err){ console.log('(error getting items) '+err); }else{ res.send(docs); } + }); }); @@ -60,10 +82,11 @@ app.post('/api/getItems', express.json(), function (req, res) { * @return object - array of history objects */ app.post('/api/getItemHistory', express.json(), function (req, res) { - db.itemdb.find({type:'history', forUID:req.body.uid},function (err, docs) { - if(err){ console.log('(error getting item history) '+err); }else{ - res.send(docs); - } + r.tables('history') + .get_all(req.body.uid, index='forUID') + .run(db, function (err, docs) { + if(err){ console.log('(error getting item history) '+err); } + else{ res.send(docs); } }); }); @@ -75,9 +98,13 @@ app.post('/api/getItemHistory', express.json(), function (req, res) { * @return object - the item that you want */ app.post('/api/getItem', express.json(), function (req, res) { - db.itemdb.findOne(req.body, function (err, doc) { - if(err){ console.log('(error getting item) '+err); }else{ res.send(doc); } - }); + r.tables('items') + .get(req.body) + .run(db, + function (err, doc) { + if(err){ console.log('(error getting item) '+err); } + else{ res.send(doc); } + }) }); @@ -94,15 +121,16 @@ app.post('/api/saveItem', express.json({limit: '50mb'}), function (req, res) { } else { var syncItemPromise; if (req.body.item.uid) { - db.itemdb.find({uid:req.body.item.uid}, function (err, check) { - if (!check.length||check[0].uid!==req.body.item.uid) { - return res.send(500); - } - //it is there - - syncItemPromise=updateItem(req.body.item, check[0], req.body.unlock); - q.when(syncItemPromise).then(function(){ - res.send(200); + r.tables("items").get(req.body.item.uid) + .run(db, function (err, check) { + if (!check.length||check[0].uid!==req.body.item.uid) { + return res.send(500); + } + //it is there + + syncItemPromise=updateItem(req.body.item, check[0], req.body.unlock); + q.when(syncItemPromise).then(function(){ + res.send(200); }); }); } else { @@ -128,19 +156,20 @@ app.post('/api/pushToItem', express.json({limit: '50mb'}), function (req, res) { } else { var syncItemPromise; if (req.body.uid) { - db.itemdb.find({uid:req.body.uid}, function (err, check) { - if (!check.length||check[0].uid!==req.body.uid) { - return res.send(500); - } - //it is there - var extendedItem = __.cloneDeep(check[0]); - _.extend(extendedItem,req.body); - - syncItemPromise=updateItem(extendedItem, check[0]); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); - }); + r.tables("items").get(req.body.item.uid) + .run(db, function (err, check) { + if (!check.length||check[0].uid!==req.body.uid) { + return res.send(500); + } + //it is there + var extendedItem = __.cloneDeep(check[0]); + _.extend(extendedItem,req.body); + + syncItemPromise=updateItem(extendedItem, check[0]); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); + }); } else { res.send(500); } } }); @@ -180,15 +209,16 @@ app.post('/api/decision', express.json(), function (req, res){ console.log('more changes...'); } //update item - db.itemdb.find({uid:req.body.item.uid}, function (err, check1) { - if (!check1.length||check1[0].uid!==req.body.item.uid) { - return res.send(500); - } - //it is there - syncItemPromise=updateItem(req.body.item, check1[0], true); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); + r.tables("items").get(req.body.item.uid) + .run(db, function (err, check1) { + if (!check1.length||check1[0].uid!==req.body.item.uid) { + return res.send(500); + } + //it is there + syncItemPromise=updateItem(req.body.item, check1[0], true); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); }); }); }); @@ -209,15 +239,16 @@ app.post('/api/deleteItem', express.json(), function (req, res){ var syncItemPromise; req.body.oldType = req.body.type; req.body.type = 'deleted'; - db.itemdb.find({uid:req.body.uid}, function (err, check) { - if (!check.length||check[0].uid!==req.body.uid) { - return res.send(500); - } - //it is there - syncItemPromise=updateItem(req.body, check[0]); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); + r.tables("items").get(req.body.item.uid) + .run(db, function (err, check) { + if (!check.length||check[0].uid!==req.body.uid) { + return res.send(500); + } + //it is there + syncItemPromise=updateItem(req.body, check[0]); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); }); } @@ -233,83 +264,96 @@ app.post('/api/deleteItem', express.json(), function (req, res){ app.post('/api/stageItemChanges', express.json(), function (req, res) { var newItem=req.body; if (newItem.uid) { - db.itemdb.find({uid:newItem.uid}, function (err, check) { - if (!check.length||check[0].uid!==newItem.uid) { - return res.send(500); - } - //it is there - var originalItem=check[0]; - var proposer = newItem.proposedBy; - if(proposer){ - newKey=generateKey(); - delete newItem.proposedBy; - - var stagedChanges=[]; - - //save image if one - if (originalItem.imageURL!==newItem.imageURL){ - console.log('saving new item image') - var mediaUID = generateUID(); - saveImage(newItem.imageURL,mediaUID); - newItem.image = 'media/images/'+mediaUID+'/image.jpg'; - newItem.thumb = 'media/images/'+mediaUID+'/thumb.jpg'; - } - - var changeNumber = 0; - for (key in newItem){ - if (JSON.stringify(newItem[key])!==JSON.stringify(originalItem[key])){ - //console.log('difference in '+key+' is '+JSON.stringify(scope.changed[key])+' -- original:'+JSON.stringify(scope.original[key])); - if((key!=='lockChangedBy')&&(key!=='lockChangedAt')&&(key!=='edited')&&(key!=='editedBy')&&(key!=='image')&&(key!=='lock')&&(key!=='imageURL')&&(key!=='owners')) { - var aChange = {}; - aChange['what']=key; - aChange['value']=newItem[key]; - aChange['decision']=''; - if (key==='thumb'){ - aChange['image']=newItem['image']; - aChange['imageURL']=newItem['imageURL']; - } - stagedChanges[changeNumber]=aChange; - changeNumber++; - } - } - } - - var promises=[]; - if (stagedChanges.length!==0){ - //insert change for every owner to approve - _.each(originalItem.owners, function(owner) { - var insertFinished=q.defer(); - promises.push(insertFinished.promise); - db.itemdb.insert({type:'staged', forUID:newItem.uid, key:newKey, proposed:moment().format(), proposedBy:proposer, forOwner:owner, changes:stagedChanges}, function (err, doc) { - if(err){ - console.log('(error staging item changes) '+err); - insertFinished.reject(); - }else{ - originalItem.proposedChanges=true; - insertFinished.resolve(); - } - }); - });//end map - - q.all(promises).then(function(){ - db.itemdb.update({uid: newItem.uid}, {$set:{proposedChanges:true}}, function (err, doc2) { - if(err){ - console.log('(error setting staged changes flag on item) '+err); - } else { - //success - res.send(200); - io.emit('proposedChange',newItem.uid); - } - }); - }, function(error) { res.send('one of the promises fucked up'); }); - - } else { - //no mods - } - - } else { - //fail - no proposedBy - } + r.tables("items").get(newItem.uid) + .run(db, function (err, check) { + if (!check.length||check[0].uid!==newItem.uid) { + return res.send(500); + } + //it is there + var originalItem=check[0]; + var proposer = newItem.proposedBy; + if(proposer){ + newKey=generateKey(); + delete newItem.proposedBy; + + var stagedChanges=[]; + + //save image if one + if (originalItem.imageURL!==newItem.imageURL){ + console.log('saving new item image') + var mediaUID = generateUID(); + saveImage(newItem.imageURL,mediaUID); + newItem.image = 'media/images/'+mediaUID+'/image.jpg'; + newItem.thumb = 'media/images/'+mediaUID+'/thumb.jpg'; + } + + var changeNumber = 0; + for (key in newItem){ + if (JSON.stringify(newItem[key])!==JSON.stringify(originalItem[key])){ + //console.log('difference in '+key+' is '+JSON.stringify(scope.changed[key])+' -- original:'+JSON.stringify(scope.original[key])); + if((key!=='lockChangedBy')&&(key!=='lockChangedAt')&&(key!=='edited')&&(key!=='editedBy')&&(key!=='image')&&(key!=='lock')&&(key!=='imageURL')&&(key!=='owners')) { + var aChange = {}; + aChange['what']=key; + aChange['value']=newItem[key]; + aChange['decision']=''; + if (key==='thumb'){ + aChange['image']=newItem['image']; + aChange['imageURL']=newItem['imageURL']; + } + stagedChanges[changeNumber]=aChange; + changeNumber++; + } + } + } + + var promises=[]; + if (stagedChanges.length!==0){ + //insert change for every owner to approve + _.each(originalItem.owners, function(owner) { + var insertFinished=q.defer(); + promises.push(insertFinished.promise); + r.tables("history") + .insert({ + type:'staged', + forUID:newItem.uid, + key:newKey, + proposed:moment().format(), + proposedBy:proposer, + forOwner:owner, + changes:stagedChanges + }) + .run(db, function (err, doc) { + if(err){ + console.log('(error staging item changes) '+err); + insertFinished.reject(); + }else{ + originalItem.proposedChanges=true; + insertFinished.resolve(); + } + }); + });//end map + + q.all(promises).then(function(){ + r.tables("items").get(newItem.uid) + .update({proposedChanges:true}) + .run(db, function (err, doc2) { + if(err){ + console.log('(error setting staged changes flag on item) '+err); + } else { + //success + res.send(200); + io.emit('proposedChange',newItem.uid); + } + }); + }, function(error) { res.send('one of the promises fucked up'); }); + + } else { + //no mods + } + + } else { + //fail - no proposedBy + } }); } else { //no item found matching that uid @@ -328,43 +372,44 @@ app.post('/api/setPriority', express.json(), function (req, res){ res.send({}); } else { var currentPriority; - db.itemdb.findOne({uid:req.body.uid},function (err, doc) { - if(err){ console.log('(error finding item) '+err); } - else { - if (doc.priority){ - //exists - currentPriority=doc.priority; - } else { - currentPriority=[]; - } - //find if user already added - var userPriority = _.findWhere(currentPriority,{email:req.body.email}); - if (userPriority) { - var index = currentPriority.indexOf(userPriority); - var newPriority = currentPriority; - newPriority[index] = {email:req.body.email, value:req.body.value}; - } else { - //not added yet - var newPriority=currentPriority; - newPriority.push({email:req.body.email, value:req.body.value}); - } - - //add up all priorities: - var totalPriority = _.reduce(newPriority, function(memo,element){ return memo + element.value; },0); - - doc.totalPriority = totalPriority; - - if (newPriority){ - doc.priority=newPriority; - db.itemdb.update({uid:req.body.uid}, {$set:{priority:newPriority, totalPriority:totalPriority}}, function (err,doc2){ - if(err){ console.log('(error updating priority) '+err); }else{ - io.emit('priorityChange', doc); - res.send(doc); - } - }); - } - } - }); + r.tables("items").get(req.body.uid) + .run(db, function (err, doc) { + if(err){ console.log('(error finding item) '+err); } + else { + if (doc.priority){ + //exists + currentPriority=doc.priority; + } else { + currentPriority=[]; + } + //find if user already added + var userPriority = _.findWhere(currentPriority,{email:req.body.email}); + if (userPriority) { + var index = currentPriority.indexOf(userPriority); + var newPriority = currentPriority; + newPriority[index] = {email:req.body.email, value:req.body.value}; + } else { + //not added yet + var newPriority=currentPriority; + newPriority.push({email:req.body.email, value:req.body.value}); + } + + //add up all priorities: + var totalPriority = _.reduce(newPriority, function(memo,element){ return memo + element.value; },0); + + doc.totalPriority = totalPriority; + + if (newPriority){ + doc.priority=newPriority; + db.itemdb.update({uid:req.body.uid}, {$set:{priority:newPriority, totalPriority:totalPriority}}, function (err,doc2){ + if(err){ console.log('(error updating priority) '+err); }else{ + io.emit('priorityChange', doc); + res.send(doc); + } + }); + } + } + }); } }); @@ -378,24 +423,19 @@ app.post('/api/addComment', express.json(), function (req, res) { if(!req.session.user){ res.send({}); } else { - db.itemdb.findOne({uid:req.body.uid}, function (err, item){ - if(err){ console.log('(error finding item) '+err); } - else { - if(!item.comments) { item.comments = []; } - var timeTime = moment().format(); - item.comments.push({words:req.body.comment, by:req.body.email, time:timeTime}); - - var pushValue = {}; - pushValue.$set = {}; - pushValue.$set['comments'] = item.comments; - db.itemdb.update({uid: req.body.uid}, pushValue, function (err, doc) { - if(err){ console.log('(error updating comments) '+err); }else{ - io.emit('comment', item); - res.send(doc); - } - }); - } - }); + r.tables("items").get(reg.body.uid).update( + r.row('comments').append({ + words:req.body.comment, + by:req.body.email, + time:moment().format(), + }) + ).run(db, function (err, item){ + if(err){ console.log('(error updating comments) '+err); } + else{ + io.emit('comment', item); + res.send(doc); + } + }); } });//end add comment diff --git a/api/lock.js b/api/lock.js index 973f26a..31b1a78 100644 --- a/api/lock.js +++ b/api/lock.js @@ -7,6 +7,7 @@ var globalState = require("../server"), * @desc various dependencies */ var q = require('q'); +var r = require('rethinkdb'); var _ = require('underscore'); var __ = require('lodash'); @@ -28,23 +29,24 @@ app.post('/api/requestLock', express.json(), function (req, res){ res.send({}); } else { var syncLockPromise; - db.itemdb.findOne({uid:req.body.uid}, function (err, item){ - if(err||!item){ console.log('(error requesting lock on item) '+err); } - else { - if (item.lock){ - //already has a lock - console.log('we are here....') - res.send(item); - } else { - //does not have lock yet - syncLockPromise = changeLock(item,req.body.email, true); - q.when(syncLockPromise).then(function(){ - res.send(item); - }); - - } - } - }); + r.tables("items").get(req.body.uid) + .run(db, function (err, item){ + if(err||!item){ console.log('(error requesting lock on item) '+err); } + else { + if (item.lock){ + //already has a lock + console.log('we are here....') + res.send(item); + } else { + //does not have lock yet + syncLockPromise = changeLock(item,req.body.email, true); + q.when(syncLockPromise).then(function(){ + res.send(item); + }); + + } + } + }); } }); @@ -60,16 +62,17 @@ app.post('/api/removeLock', express.json(), function (req, res){ } else { var syncLockPromise; if (req.body.uid) { - console.log('removing lock for item: '+req.body.uid) - db.itemdb.findOne({uid:req.body.uid}, function (err, item){ - if(err||!item){ console.log('(error removing lock on item) '+err); } - else { - syncLockPromise = changeLock(item,req.body.email, false); - q.when(syncLockPromise).then(function(){ - res.send(item); - }); - } - }); + console.log('removing lock for item: '+req.body.uid); + r.tables("items").find(req.body.uid) + .run(db, function (err, item){ + if(err||!item){ console.log('(error removing lock on item) '+err); } + else { + syncLockPromise = changeLock(item,req.body.email, false); + q.when(syncLockPromise).then(function(){ + res.send(item); + }); + } + }); } } }); @@ -85,20 +88,21 @@ app.post('/api/pickLock', express.json(), function (req, res){ res.send({}); } else { var syncLockPromise; - console.log('breaking lock for item: '+req.body.uid) - db.itemdb.findOne({uid:req.body.uid}, function (err, item){ - if(err||!item){ console.log('(error removing lock on item) '+err); } - else { - if(_.contains(item.owners, req.body.email)){ - syncLockPromise = changeLock(item,req.body.email, false); - q.when(syncLockPromise).then(function(){ - res.send(item); - }); - } else { - //send the owner an email - } - } - }); + console.log('breaking lock for item: '+req.body.uid); + r.tables("items").get(req.body.uid) + .run(db, function (err, item){ + if(err||!item){ console.log('(error removing lock on item) '+err); } + else { + if(_.contains(item.owners, req.body.email)){ + syncLockPromise = changeLock(item,req.body.email, false); + q.when(syncLockPromise).then(function(){ + res.send(item); + }); + } else { + //send the owner an email + } + } + }); } }); diff --git a/api/proposals.js b/api/proposals.js index b632009..b94413c 100644 --- a/api/proposals.js +++ b/api/proposals.js @@ -7,6 +7,7 @@ var globalState = require("../server"), /** * @desc various dependencies */ +var r = require('rethinkdb'); var __ = require('lodash'); var dbInfo = require("../database/dbInfo"); @@ -30,7 +31,7 @@ app.post('/api/proposalResult', express.json(), function (req, res) { } }); if(theOne.key===req.body.key) { - db.itemdb.find({uid:req.body.uid}, function (err, check) { + r.tables("items").get(req.body.uid).run(db, function (err, check) { if (!check.length||check[0].uid!==req.body.uid) { return res.send(500); } @@ -52,7 +53,7 @@ app.post('/api/proposalResult', express.json(), function (req, res) { console.log("approval is currently: "+approved); if (approved){ //update the item - db.itemdb.find({uid:extendedItem.forUID}, function (err, check2){ + r.tables("items").get(extendedItem.forUID).run(db,function (err, check2){ if(err){ console.log('(error getting item) '+err); }else{ //clone and add approval var approvalItem = __.cloneDeep(check2[0]); @@ -91,39 +92,40 @@ app.post('/api/saveProposal', express.json(), function (req, res) { keys[member.name] = generateUID(); }); - db.itemdb.insert(req.body, function (err, doc) { - if(err){ - console.log('(error saving proposal) '+err); - }else{ - console.log('proposal: ' + doc.uid); - io.emit('newProposal', doc.uid); + r.tables("items").insert(req.body) + .run(db, function (err, doc) { + if(err){ + console.log('(error saving proposal) '+err); + }else{ + console.log('proposal: ' + doc.uid); + io.emit('newProposal', doc.uid); - //email all members - _(members).each(function(member){ - if (member.email){ - var key = keys[member.name]; - - console.log('trying to send email to ' + member.email); - smtpTrans.sendMail({ - from: 'Robot ', - to: member.email, - subject: 'new project proposal for colab', - text: 'text body', - html: "

Human,

A new proposal has been created. Please follow the link below to review everything, and fill in your decision and/or comments. The link was generated specifically for you so don't share. Please reply to me if you have any questions. I am a robot. Thank you.

"+member.name+"'s response" - }, function (err, doc){ - if(err){ console.log(err); }else{ - //email was sent! - proposalSecrets[req.body.uid].push({name:member.name,key:key}); - console.log('Message sent: ' + doc.response); - } - }); + //email all members + _(members).each(function(member){ + if (member.email){ + var key = keys[member.name]; + + console.log('trying to send email to ' + member.email); + smtpTrans.sendMail({ + from: 'Robot ', + to: member.email, + subject: 'new project proposal for colab', + text: 'text body', + html: "

Human,

A new proposal has been created. Please follow the link below to review everything, and fill in your decision and/or comments. The link was generated specifically for you so don't share. Please reply to me if you have any questions. I am a robot. Thank you.

"+member.name+"'s response" + }, function (err, doc){ + if(err){ console.log(err); }else{ + //email was sent! + proposalSecrets[req.body.uid].push({name:member.name,key:key}); + console.log('Message sent: ' + doc.response); + } + }); - } - }); + } + }); - res.send(doc.uid); - } - }); + res.send(doc.uid); + } + }); } }); diff --git a/database/utils.js b/database/utils.js index 8075ae9..c7943c5 100644 --- a/database/utils.js +++ b/database/utils.js @@ -1,4 +1,5 @@ var fs = require('fs'); +var r = require('rethinkdb'); var request = require('request'); var q = require('q'); var url = require('url'); @@ -116,15 +117,20 @@ module.exports = { historyItem.uid=generateUID(); historyItem.historical=true; historyItem.proposedChanges=false; + //update and store history - db.itemdb.insert({type:'history', forUID:newItem.uid, historyItem:historyItem }, function (err, doc) {}); + r.tables("history").insert({ + type:'history', + forUID:newItem.uid, + historyItem:historyItem + }).run(db, function (err, doc) {}); newItem.edited=moment().format(); if (unlock) { newItem.lock=false; } delete newItem._id; //check to see if new image was sent - db.itemdb.update({uid: newItem.uid}, newItem, function (err, doc) { + r.table("items").get(newItem.uid).update(newItem).run(db, function (err, doc) { if(err){ console.log('(error updating item) '+err); saveItemPromise.reject(); @@ -167,7 +173,7 @@ module.exports = { newItem.image = defaultImage; newItem.thumb = defaultImage; } - db.itemdb.insert(newItem, function (err, doc) { + r.tables("items").insert(newItem).run(db, function (err, doc) { if(err){ console.log('(error saving item) '+err); saveItemPromise.reject(); @@ -275,7 +281,11 @@ module.exports = { item.lockChangedBy=who; item.lockChangedAt=time; - db.itemdb.update({uid: item.uid}, {$set:{lock:value, lockChangedBy:who, lockChangedAt:time}}, function (err, doc) { + r.tables("items").get(item.uid).update({ + lock:value, + lockChangedBy:who, + lockChangedAt:time + }).run(db, function (err, doc) { if(err){ console.log('(error changing lock on item) '+err); changeLockPromise.reject(); @@ -297,23 +307,25 @@ module.exports = { if (change['what']===what){ staged.changes[i].decision=value; } }); - db.itemdb.update({key: staged.key}, {$set:{changes:staged.changes}}, function (err, doc) { - if(err){ - console.log('(error changing decisions on item) '+err); - changeDecisionPromise.reject(); - } else { - //success - io.emit('decisionChange',staged); - changeDecisionPromise.resolve(); - } - }); + // TODO: is this actually correct? + r.tables("items").find({key: staged.key}).update({changes:staged.changes}) + .run(db, function (err, doc) { + if(err){ + console.log('(error changing decisions on item) '+err); + changeDecisionPromise.reject(); + } else { + //success + io.emit('decisionChange',staged); + changeDecisionPromise.resolve(); + } + }); return changeDecisionPromise.promise; } , findItem : function(uid){ var p=q.defer(); - db.itemdb.findOne({uid:uid}, function (err, doc) { + r.tables("items").get(uid).run(db, function (err, doc) { if(err){ console.log('(error getting item) '+err); p.reject(err); }else{ p.resolve(doc); } }); return p.promise; diff --git a/server.js b/server.js index b369636..353095f 100644 --- a/server.js +++ b/server.js @@ -7,13 +7,46 @@ console.log('server running'); var users = require('./users'); /** - * @desc using mongo db and express for all the magic + * @desc using rethinkdb and express for all the magic */ -var mongojs = require('mongojs'); -var db = module.exports.db = mongojs('mongodb://localhost:27017/itemdb', ['itemdb']); +var r = require('rethinkdb', 'oratory'), + db = r.connect( + { host: 'localhost', port: 28015, } + ).then(function(err, conn) { + console.log("Connected to rethinkdb"); + if (err) { + throw(err); + } + db = conn; + r.tableCreate('items', {primaryKey: 'uid'}) + .run(conn, function(err, stat) { + r.tables("items").indexCreate("types") + .run(conn, function(err, stat) { if (err) {throw(err)} }); + }); + r.tableCreate('history', {primaryKey: 'key'}) + .run(conn, function(err, stat) { + r.tables("history").indexCreate("forUID") + .run(conn, function(err, stat) { if (err) {throw(err)} }); + }); + }); + //app engine -var express = module.exports.express = require('express'), - app = module.exports.app = express(); +var express = require('express'), + app = express(); + +/** + * @desc various dependencies +*/ +var http = require('http').Server(app); +var io = require('socket.io')(http); + + +module.exports = { + express: express, + app: app, + db: db, + io: io, +} //app configuration app.use(express.cookieParser()); @@ -23,12 +56,6 @@ app.use(express.static(__dirname + '/www')); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); -/** - * @desc various dependencies -*/ -var http = require('http').Server(app); -var io = module.exports.io = require('socket.io')(http); - //"schema" for database var dbInfo = require("./database/dbInfo"); From 52b1ef458c55745ad561b8da15a62eb45111e6d3 Mon Sep 17 00:00:00 2001 From: Micha Gorelick Date: Sat, 19 Sep 2015 17:12:26 -0400 Subject: [PATCH 3/6] zomg... where has all the python gone? --- api/items.js | 31 ++++++++++++++++--------------- api/lock.js | 6 +++--- api/proposals.js | 6 +++--- database/db.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ database/utils.js | 11 ++++++----- server.js | 25 ++++--------------------- 6 files changed, 77 insertions(+), 47 deletions(-) create mode 100644 database/db.js diff --git a/api/items.js b/api/items.js index 51ccecd..bbce7cb 100644 --- a/api/items.js +++ b/api/items.js @@ -39,8 +39,8 @@ function isEmpty(obj) { */ app.get('/api/getDatabase', function (req, res) { r.expr({ - "items" : r.tables("items"), - "history" : r.tables("history"), + "items" : r.table("items"), + "history" : r.table("history"), }).run(db, function(err, docs) { if(err){ console.log('(error getting database) '+err);}else { res.send(docs); } }); @@ -58,8 +58,9 @@ app.get('/api/getDatabase', function (req, res) { * @return object - array of "items" */ app.post('/api/getItems', express.json(), function (req, res) { - var query = r.tables("items"), - fields = _.pick(req.body, 'type', 'forUID', 'forOwner').compactObject(); + var query = r.table("items"); + //fields = _.pick(req.body, 'type', 'forUID', 'forOwner').compactObject(); + var fields = {}; if (isEmpty(fields)) { var keys = _(dbInfo.types).map(function(item){ @@ -82,7 +83,7 @@ app.post('/api/getItems', express.json(), function (req, res) { * @return object - array of history objects */ app.post('/api/getItemHistory', express.json(), function (req, res) { - r.tables('history') + r.table('history') .get_all(req.body.uid, index='forUID') .run(db, function (err, docs) { if(err){ console.log('(error getting item history) '+err); } @@ -98,7 +99,7 @@ app.post('/api/getItemHistory', express.json(), function (req, res) { * @return object - the item that you want */ app.post('/api/getItem', express.json(), function (req, res) { - r.tables('items') + r.table('items') .get(req.body) .run(db, function (err, doc) { @@ -121,7 +122,7 @@ app.post('/api/saveItem', express.json({limit: '50mb'}), function (req, res) { } else { var syncItemPromise; if (req.body.item.uid) { - r.tables("items").get(req.body.item.uid) + r.table("items").get(req.body.item.uid) .run(db, function (err, check) { if (!check.length||check[0].uid!==req.body.item.uid) { return res.send(500); @@ -156,7 +157,7 @@ app.post('/api/pushToItem', express.json({limit: '50mb'}), function (req, res) { } else { var syncItemPromise; if (req.body.uid) { - r.tables("items").get(req.body.item.uid) + r.table("items").get(req.body.item.uid) .run(db, function (err, check) { if (!check.length||check[0].uid!==req.body.uid) { return res.send(500); @@ -209,7 +210,7 @@ app.post('/api/decision', express.json(), function (req, res){ console.log('more changes...'); } //update item - r.tables("items").get(req.body.item.uid) + r.table("items").get(req.body.item.uid) .run(db, function (err, check1) { if (!check1.length||check1[0].uid!==req.body.item.uid) { return res.send(500); @@ -239,7 +240,7 @@ app.post('/api/deleteItem', express.json(), function (req, res){ var syncItemPromise; req.body.oldType = req.body.type; req.body.type = 'deleted'; - r.tables("items").get(req.body.item.uid) + r.table("items").get(req.body.item.uid) .run(db, function (err, check) { if (!check.length||check[0].uid!==req.body.uid) { return res.send(500); @@ -264,7 +265,7 @@ app.post('/api/deleteItem', express.json(), function (req, res){ app.post('/api/stageItemChanges', express.json(), function (req, res) { var newItem=req.body; if (newItem.uid) { - r.tables("items").get(newItem.uid) + r.table("items").get(newItem.uid) .run(db, function (err, check) { if (!check.length||check[0].uid!==newItem.uid) { return res.send(500); @@ -312,7 +313,7 @@ app.post('/api/stageItemChanges', express.json(), function (req, res) { _.each(originalItem.owners, function(owner) { var insertFinished=q.defer(); promises.push(insertFinished.promise); - r.tables("history") + r.table("history") .insert({ type:'staged', forUID:newItem.uid, @@ -334,7 +335,7 @@ app.post('/api/stageItemChanges', express.json(), function (req, res) { });//end map q.all(promises).then(function(){ - r.tables("items").get(newItem.uid) + r.table("items").get(newItem.uid) .update({proposedChanges:true}) .run(db, function (err, doc2) { if(err){ @@ -372,7 +373,7 @@ app.post('/api/setPriority', express.json(), function (req, res){ res.send({}); } else { var currentPriority; - r.tables("items").get(req.body.uid) + r.table("items").get(req.body.uid) .run(db, function (err, doc) { if(err){ console.log('(error finding item) '+err); } else { @@ -423,7 +424,7 @@ app.post('/api/addComment', express.json(), function (req, res) { if(!req.session.user){ res.send({}); } else { - r.tables("items").get(reg.body.uid).update( + r.table("items").get(reg.body.uid).update( r.row('comments').append({ words:req.body.comment, by:req.body.email, diff --git a/api/lock.js b/api/lock.js index 31b1a78..d52fc25 100644 --- a/api/lock.js +++ b/api/lock.js @@ -29,7 +29,7 @@ app.post('/api/requestLock', express.json(), function (req, res){ res.send({}); } else { var syncLockPromise; - r.tables("items").get(req.body.uid) + r.table("items").get(req.body.uid) .run(db, function (err, item){ if(err||!item){ console.log('(error requesting lock on item) '+err); } else { @@ -63,7 +63,7 @@ app.post('/api/removeLock', express.json(), function (req, res){ var syncLockPromise; if (req.body.uid) { console.log('removing lock for item: '+req.body.uid); - r.tables("items").find(req.body.uid) + r.table("items").find(req.body.uid) .run(db, function (err, item){ if(err||!item){ console.log('(error removing lock on item) '+err); } else { @@ -89,7 +89,7 @@ app.post('/api/pickLock', express.json(), function (req, res){ } else { var syncLockPromise; console.log('breaking lock for item: '+req.body.uid); - r.tables("items").get(req.body.uid) + r.table("items").get(req.body.uid) .run(db, function (err, item){ if(err||!item){ console.log('(error removing lock on item) '+err); } else { diff --git a/api/proposals.js b/api/proposals.js index b94413c..fed4d90 100644 --- a/api/proposals.js +++ b/api/proposals.js @@ -31,7 +31,7 @@ app.post('/api/proposalResult', express.json(), function (req, res) { } }); if(theOne.key===req.body.key) { - r.tables("items").get(req.body.uid).run(db, function (err, check) { + r.table("items").get(req.body.uid).run(db, function (err, check) { if (!check.length||check[0].uid!==req.body.uid) { return res.send(500); } @@ -53,7 +53,7 @@ app.post('/api/proposalResult', express.json(), function (req, res) { console.log("approval is currently: "+approved); if (approved){ //update the item - r.tables("items").get(extendedItem.forUID).run(db,function (err, check2){ + r.table("items").get(extendedItem.forUID).run(db,function (err, check2){ if(err){ console.log('(error getting item) '+err); }else{ //clone and add approval var approvalItem = __.cloneDeep(check2[0]); @@ -92,7 +92,7 @@ app.post('/api/saveProposal', express.json(), function (req, res) { keys[member.name] = generateUID(); }); - r.tables("items").insert(req.body) + r.table("items").insert(req.body) .run(db, function (err, doc) { if(err){ console.log('(error saving proposal) '+err); diff --git a/database/db.js b/database/db.js new file mode 100644 index 0000000..da49572 --- /dev/null +++ b/database/db.js @@ -0,0 +1,45 @@ +var r = require('rethinkdb', 'oratory'); + +// setup the database +r.connect( + { host: 'localhost', port: 28015} +).then(function(conn) { + console.log("Connected to rethinkdb"); + r.dbCreate("oratory").run(conn, function(err, status) { + r.tableCreate('items', {primaryKey: 'uid'}) + .run(conn, function(err, stat) { + r.table("items").indexCreate("types", {multi: true}) + .run(conn, function(err, stat) {}); + }); + r.tableCreate('history', {primaryKey: 'key'}) + .run(conn, function(err, stat) { + r.table("history").indexCreate("forUID", {multi: true}) + .run(conn, function(err, stat) {}); + }); + }); +}).error(function(error) { + console.log("CAN'T CONNECT TO RETHINK: " + error); + throw(error); +}); + +function handleError(res) { + return function(error) { + res.send(500, {error: error.message}); + } +} + +module.exports = { + createConnection : function(req, res, next) { + r.connect({ host: 'localhost', port: 28015, db: 'oratory'}).then(function(conn) { + // Save the connection in `req` + root.db = conn; + // Pass the current request to the next middleware + next(); + }).error(handleError(res)); + }, + + closeConnection : function(req, res, next) { + root.db.close(); + next(); + }, +} diff --git a/database/utils.js b/database/utils.js index c7943c5..08a568c 100644 --- a/database/utils.js +++ b/database/utils.js @@ -119,7 +119,7 @@ module.exports = { historyItem.proposedChanges=false; //update and store history - r.tables("history").insert({ + r.table("history").insert({ type:'history', forUID:newItem.uid, historyItem:historyItem @@ -173,7 +173,8 @@ module.exports = { newItem.image = defaultImage; newItem.thumb = defaultImage; } - r.tables("items").insert(newItem).run(db, function (err, doc) { + console.log(db); + r.table("items").insert(newItem).run(db, function (err, doc) { if(err){ console.log('(error saving item) '+err); saveItemPromise.reject(); @@ -281,7 +282,7 @@ module.exports = { item.lockChangedBy=who; item.lockChangedAt=time; - r.tables("items").get(item.uid).update({ + r.table("items").get(item.uid).update({ lock:value, lockChangedBy:who, lockChangedAt:time @@ -308,7 +309,7 @@ module.exports = { }); // TODO: is this actually correct? - r.tables("items").find({key: staged.key}).update({changes:staged.changes}) + r.table("items").find({key: staged.key}).update({changes:staged.changes}) .run(db, function (err, doc) { if(err){ console.log('(error changing decisions on item) '+err); @@ -325,7 +326,7 @@ module.exports = { findItem : function(uid){ var p=q.defer(); - r.tables("items").get(uid).run(db, function (err, doc) { + r.table("items").get(uid).run(db, function (err, doc) { if(err){ console.log('(error getting item) '+err); p.reject(err); }else{ p.resolve(doc); } }); return p.promise; diff --git a/server.js b/server.js index 353095f..5fe218b 100644 --- a/server.js +++ b/server.js @@ -9,26 +9,6 @@ var users = require('./users'); /** * @desc using rethinkdb and express for all the magic */ -var r = require('rethinkdb', 'oratory'), - db = r.connect( - { host: 'localhost', port: 28015, } - ).then(function(err, conn) { - console.log("Connected to rethinkdb"); - if (err) { - throw(err); - } - db = conn; - r.tableCreate('items', {primaryKey: 'uid'}) - .run(conn, function(err, stat) { - r.tables("items").indexCreate("types") - .run(conn, function(err, stat) { if (err) {throw(err)} }); - }); - r.tableCreate('history', {primaryKey: 'key'}) - .run(conn, function(err, stat) { - r.tables("history").indexCreate("forUID") - .run(conn, function(err, stat) { if (err) {throw(err)} }); - }); - }); //app engine var express = require('express'), @@ -39,21 +19,24 @@ var express = require('express'), */ var http = require('http').Server(app); var io = require('socket.io')(http); +var db = require("./database/db"); module.exports = { express: express, app: app, - db: db, io: io, + db: undefined, } //app configuration app.use(express.cookieParser()); app.use(express.session({secret: "This is a secret"})); +app.use(db.createConnection); app.use(app.router); app.use(express.static(__dirname + '/www')); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); +app.use(db.closeConnection); //"schema" for database From bf157fa005989e1993d8561e8c795c33a02d09fa Mon Sep 17 00:00:00 2001 From: Micha Gorelick Date: Sat, 19 Sep 2015 19:38:41 -0400 Subject: [PATCH 4/6] kinda works --- api/items.js | 535 +++++++++++++++++++++++----------------------- api/lock.js | 20 +- api/proposals.js | 22 +- database/db.js | 4 +- database/utils.js | 72 ++++--- server.js | 1 - 6 files changed, 332 insertions(+), 322 deletions(-) diff --git a/api/items.js b/api/items.js index bbce7cb..a4eab4e 100644 --- a/api/items.js +++ b/api/items.js @@ -1,7 +1,6 @@ var globalState = require("../server"), app = globalState.app, - express = globalState.express, - db = globalState.db; + express = globalState.express; /** * @desc various dependencies @@ -12,8 +11,7 @@ var _ = require('underscore'); var __ = require('lodash'); var dbInfo = require("../database/dbInfo"); -var dbHelper = require("../database/utils"); -__.assign(root, dbHelper); +var dbUtils = require("../database/utils"); /* UTILS */ _.mixin({ @@ -41,9 +39,9 @@ app.get('/api/getDatabase', function (req, res) { r.expr({ "items" : r.table("items"), "history" : r.table("history"), - }).run(db, function(err, docs) { - if(err){ console.log('(error getting database) '+err);}else { res.send(docs); } - }); + }).run(req.db, function(err, docs) { + if(err){ console.log('(error getting database) '+err);}else { res.send(docs.toArray()); } + }); }); @@ -53,26 +51,33 @@ app.get('/api/getDatabase', function (req, res) { * @desc grabs the "items" in the database based on the criteria defined with the parameters - if nothing is provided, it returns all * items of with the "types" defined in the dbInfo object (authentication commented out) - used to generate lists of "projects" or "books", etc. * @param string type - string forUID - string forOwner + string forUID + string forOwner * @return object - array of "items" */ app.post('/api/getItems', express.json(), function (req, res) { - var query = r.table("items"); - //fields = _.pick(req.body, 'type', 'forUID', 'forOwner').compactObject(); - var fields = {}; + var fields = _.compactObject(_.pick(req.body, 'type', 'forUID', 'forOwner')); if (isEmpty(fields)) { var keys = _(dbInfo.types).map(function(item){ return item.name; }); - query.getAll.apply(query, keys.concat({index:"type"})); + r.table("items") + .getAll('tool', 'resource', 'project', 'book', 'event', 'deleted', {index:"type"}) + .run(req.db, function (err, docs) { + if(err){ console.log('(error getting items) '+err); } + else{ dbUtils.respondCursor(res, docs) } + }); } else { - query.filter(fields); + r.table("items") + .filter(fields) + .run(req.db, function (err, docs) { + if(err){ console.log('(error getting items) '+err); }else{ dbUtils.respondCursor(res, docs) } + }); } - query.run(db, function (err, docs) { - if(err){ console.log('(error getting items) '+err); }else{ res.send(docs); } - }); + //query.run(req.db, function (err, docs) { + // if(err){ console.log('(error getting items) '+err); }else{ res.send(docs.toArray()); } + //}); }); @@ -83,12 +88,12 @@ app.post('/api/getItems', express.json(), function (req, res) { * @return object - array of history objects */ app.post('/api/getItemHistory', express.json(), function (req, res) { - r.table('history') + r.table('history') .get_all(req.body.uid, index='forUID') - .run(db, function (err, docs) { - if(err){ console.log('(error getting item history) '+err); } - else{ res.send(docs); } - }); + .run(req.db, function (err, docs) { + if(err){ console.log('(error getting item history) '+err); } + else{ dbUtils.respondCursor(res, docs); } + }); }); @@ -100,10 +105,10 @@ app.post('/api/getItemHistory', express.json(), function (req, res) { */ app.post('/api/getItem', express.json(), function (req, res) { r.table('items') - .get(req.body) - .run(db, + .get(req.body.uid) + .run(req.db, function (err, doc) { - if(err){ console.log('(error getting item) '+err); } + if(err){ console.log('(error getting item) '+err); } else{ res.send(doc); } }) }); @@ -117,32 +122,34 @@ app.post('/api/getItem', express.json(), function (req, res) { * @return int - 200 (ok) or 500 (error...) */ app.post('/api/saveItem', express.json({limit: '50mb'}), function (req, res) { - if(!req.session.user){ - res.send({}); - } else { - var syncItemPromise; - if (req.body.item.uid) { + if(!req.session.user){ + res.send({}); + } else { + var syncItemPromise; + if (req.body.item.uid) { + console.log("route1"); r.table("items").get(req.body.item.uid) - .run(db, function (err, check) { - if (!check.length||check[0].uid!==req.body.item.uid) { - return res.send(500); - } - //it is there - - syncItemPromise=updateItem(req.body.item, check[0], req.body.unlock); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); - }); - } else { - //brand new item!!! - syncItemPromise=newItem(req.body.item); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); - - } - } + .run(req.db, function (err, check) { + if (check.uid!==req.body.item.uid) { + return res.send(500); + } + //it is there + + syncItemPromise=dbUtils.updateItem(req.db, req.body.item, check, req.body.unlock); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); + }); + } else { + console.log("route2"); + //brand new item!!! + syncItemPromise=dbUtils.newItem(req.db, req.body.item); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); + + } + } }); /** @@ -152,27 +159,27 @@ app.post('/api/saveItem', express.json({limit: '50mb'}), function (req, res) { * @return int - 200 (ok) or 500 (error...) */ app.post('/api/pushToItem', express.json({limit: '50mb'}), function (req, res) { - if(!req.session.user){ - res.send({}); - } else { - var syncItemPromise; - if (req.body.uid) { + if(!req.session.user){ + res.send({}); + } else { + var syncItemPromise; + if (req.body.uid) { r.table("items").get(req.body.item.uid) - .run(db, function (err, check) { - if (!check.length||check[0].uid!==req.body.uid) { - return res.send(500); - } - //it is there - var extendedItem = __.cloneDeep(check[0]); - _.extend(extendedItem,req.body); - - syncItemPromise=updateItem(extendedItem, check[0]); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); - }); - } else { res.send(500); } - } + .run(req.db, function (err, check) { + if (check.uid!==req.body.uid) { + return res.send(500); + } + //it is there + var extendedItem = __.cloneDeep(check); + _.extend(extendedItem,req.body); + + syncItemPromise=dbUtils.updateItem(req.db, extendedItem, check); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); + }); + } else { res.send(500); } + } }); @@ -183,48 +190,48 @@ app.post('/api/pushToItem', express.json({limit: '50mb'}), function (req, res) { * @return int - 200 (ok) or 500 (error...) */ app.post('/api/decision', express.json(), function (req, res){ - if(!req.session.user){ - res.send({}); - } else { - var syncItemPromise; - db.itemdb.find({key:req.body.key, forOwner:req.body.email}, function (err, check) { - if (!check.length||check[0].key!==req.body.key) { - return res.send(500); - } - //it is there - syncItemPromise=changeDecision(check[0], req.body.email, req.body.field, req.body.decision); - q.when(syncItemPromise).then(function(){ - - //check if all decisions are made - db.itemdb.find({key:req.body.key}, function (err, check2) { - var done = true; - var allDec = check2[0].changes; - for (k in allDec) { - if (allDec[k].decision==='') { done=false; } - } - - if (done) { - console.log('all changes are complete'); - req.body.item.proposedChanges=false; - } else { - console.log('more changes...'); - } - //update item + if(!req.session.user){ + res.send({}); + } else { + var syncItemPromise; + req.db.itemdb.find({key:req.body.key, forOwner:req.body.email}, function (err, check) { + if (check.key!==req.body.key) { + return res.send(500); + } + //it is there + syncItemPromise=dbUtils.changeDecision(req.db, check, req.body.email, req.body.field, req.body.decision); + q.when(syncItemPromise).then(function(){ + + //check if all decisions are made + req.db.itemdb.find({key:req.body.key}, function (err, check2) { + var done = true; + var allDec = check2.changes; + for (k in allDec) { + if (allDec[k].decision==='') { done=false; } + } + + if (done) { + console.log('all changes are complete'); + req.body.item.proposedChanges=false; + } else { + console.log('more changes...'); + } + //update item r.table("items").get(req.body.item.uid) - .run(db, function (err, check1) { - if (!check1.length||check1[0].uid!==req.body.item.uid) { - return res.send(500); - } - //it is there - syncItemPromise=updateItem(req.body.item, check1[0], true); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); - }); - }); - }); - }); - } + .run(req.db, function (err, check1) { + if (check1.uid!==req.body.item.uid) { + return res.send(500); + } + //it is there + syncItemPromise=dbUtils.updateItem(req.db, req.body.item, check1, true); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); + }); + }); + }); + }); + } }); /** @@ -234,24 +241,24 @@ app.post('/api/decision', express.json(), function (req, res){ * @return int - 200 (ok) or 500 (error...) */ app.post('/api/deleteItem', express.json(), function (req, res){ - if(!req.session.user){ - res.send({}); - } else { - var syncItemPromise; - req.body.oldType = req.body.type; - req.body.type = 'deleted'; + if(!req.session.user){ + res.send({}); + } else { + var syncItemPromise; + req.body.oldType = req.body.type; + req.body.type = 'deleted'; r.table("items").get(req.body.item.uid) - .run(db, function (err, check) { - if (!check.length||check[0].uid!==req.body.uid) { - return res.send(500); - } - //it is there - syncItemPromise=updateItem(req.body, check[0]); - q.when(syncItemPromise).then(function(){ - res.send(200); - }); - }); - } + .run(req.db, function (err, check) { + if (check.uid!==req.body.uid) { + return res.send(500); + } + //it is there + syncItemPromise=dbUtils.updateItem(req.db, req.body, check); + q.when(syncItemPromise).then(function(){ + res.send(200); + }); + }); + } }); @@ -263,58 +270,58 @@ app.post('/api/deleteItem', express.json(), function (req, res){ * @return int - 200 (ok) or 500 (error...) */ app.post('/api/stageItemChanges', express.json(), function (req, res) { - var newItem=req.body; - if (newItem.uid) { + var newItem=req.body; + if (newItem.uid) { r.table("items").get(newItem.uid) - .run(db, function (err, check) { - if (!check.length||check[0].uid!==newItem.uid) { - return res.send(500); - } - //it is there - var originalItem=check[0]; - var proposer = newItem.proposedBy; - if(proposer){ - newKey=generateKey(); - delete newItem.proposedBy; - - var stagedChanges=[]; - - //save image if one - if (originalItem.imageURL!==newItem.imageURL){ - console.log('saving new item image') - var mediaUID = generateUID(); - saveImage(newItem.imageURL,mediaUID); - newItem.image = 'media/images/'+mediaUID+'/image.jpg'; - newItem.thumb = 'media/images/'+mediaUID+'/thumb.jpg'; - } - - var changeNumber = 0; - for (key in newItem){ - if (JSON.stringify(newItem[key])!==JSON.stringify(originalItem[key])){ - //console.log('difference in '+key+' is '+JSON.stringify(scope.changed[key])+' -- original:'+JSON.stringify(scope.original[key])); - if((key!=='lockChangedBy')&&(key!=='lockChangedAt')&&(key!=='edited')&&(key!=='editedBy')&&(key!=='image')&&(key!=='lock')&&(key!=='imageURL')&&(key!=='owners')) { - var aChange = {}; - aChange['what']=key; - aChange['value']=newItem[key]; - aChange['decision']=''; - if (key==='thumb'){ - aChange['image']=newItem['image']; - aChange['imageURL']=newItem['imageURL']; - } - stagedChanges[changeNumber]=aChange; - changeNumber++; - } - } - } - - var promises=[]; - if (stagedChanges.length!==0){ - //insert change for every owner to approve - _.each(originalItem.owners, function(owner) { - var insertFinished=q.defer(); - promises.push(insertFinished.promise); + .run(req.db, function (err, check) { + if (check.uid!==newItem.uid) { + return res.send(500); + } + //it is there + var originalItem=check; + var proposer = newItem.proposedBy; + if(proposer){ + newKey=dbUtils.generateKey(); + delete newItem.proposedBy; + + var stagedChanges=[]; + + //save image if one + if (originalItem.imageURL!==newItem.imageURL){ + console.log('saving new item image') + var mediaUID = dbUtils.generateUID(); + dbUtils.saveImage(newItem.imageURL,mediaUID); + newItem.image = 'media/images/'+mediaUID+'/image.jpg'; + newItem.thumb = 'media/images/'+mediaUID+'/thumb.jpg'; + } + + var changeNumber = 0; + for (key in newItem){ + if (JSON.stringify(newItem[key])!==JSON.stringify(originalItem[key])){ + //console.log('difference in '+key+' is '+JSON.stringify(scope.changed[key])+' -- original:'+JSON.stringify(scope.original[key])); + if((key!=='lockChangedBy')&&(key!=='lockChangedAt')&&(key!=='edited')&&(key!=='editedBy')&&(key!=='image')&&(key!=='lock')&&(key!=='imageURL')&&(key!=='owners')) { + var aChange = {}; + aChange['what']=key; + aChange['value']=newItem[key]; + aChange['decision']=''; + if (key==='thumb'){ + aChange['image']=newItem['image']; + aChange['imageURL']=newItem['imageURL']; + } + stagedChanges[changeNumber]=aChange; + changeNumber++; + } + } + } + + var promises=[]; + if (stagedChanges.length!==0){ + //insert change for every owner to approve + _.each(originalItem.owners, function(owner) { + var insertFinished=q.defer(); + promises.push(insertFinished.promise); r.table("history") - .insert({ + .insert({ type:'staged', forUID:newItem.uid, key:newKey, @@ -323,42 +330,42 @@ app.post('/api/stageItemChanges', express.json(), function (req, res) { forOwner:owner, changes:stagedChanges }) - .run(db, function (err, doc) { - if(err){ - console.log('(error staging item changes) '+err); - insertFinished.reject(); - }else{ - originalItem.proposedChanges=true; - insertFinished.resolve(); - } - }); - });//end map - - q.all(promises).then(function(){ + .run(req.db, function (err, doc) { + if(err){ + console.log('(error staging item changes) '+err); + insertFinished.reject(); + }else{ + originalItem.proposedChanges=true; + insertFinished.resolve(); + } + }); + });//end map + + q.all(promises).then(function(){ r.table("items").get(newItem.uid) .update({proposedChanges:true}) - .run(db, function (err, doc2) { - if(err){ - console.log('(error setting staged changes flag on item) '+err); - } else { - //success - res.send(200); - io.emit('proposedChange',newItem.uid); - } - }); - }, function(error) { res.send('one of the promises fucked up'); }); - - } else { - //no mods - } - - } else { - //fail - no proposedBy - } - }); - } else { - //no item found matching that uid - } + .run(req.db, function (err, doc2) { + if(err){ + console.log('(error setting staged changes flag on item) '+err); + } else { + //success + res.send(200); + io.emit('proposedChange',newItem.uid); + } + }); + }, function(error) { res.send('one of the promises fucked up'); }); + + } else { + //no mods + } + + } else { + //fail - no proposedBy + } + }); + } else { + //no item found matching that uid + } }); /** @@ -369,49 +376,49 @@ app.post('/api/stageItemChanges', express.json(), function (req, res) { * @return int - the item */ app.post('/api/setPriority', express.json(), function (req, res){ - if(!req.session.user){ - res.send({}); - } else { - var currentPriority; + if(!req.session.user){ + res.send({}); + } else { + var currentPriority; r.table("items").get(req.body.uid) - .run(db, function (err, doc) { - if(err){ console.log('(error finding item) '+err); } - else { - if (doc.priority){ - //exists - currentPriority=doc.priority; - } else { - currentPriority=[]; - } - //find if user already added - var userPriority = _.findWhere(currentPriority,{email:req.body.email}); - if (userPriority) { - var index = currentPriority.indexOf(userPriority); - var newPriority = currentPriority; - newPriority[index] = {email:req.body.email, value:req.body.value}; - } else { - //not added yet - var newPriority=currentPriority; - newPriority.push({email:req.body.email, value:req.body.value}); - } - - //add up all priorities: - var totalPriority = _.reduce(newPriority, function(memo,element){ return memo + element.value; },0); - - doc.totalPriority = totalPriority; - - if (newPriority){ - doc.priority=newPriority; - db.itemdb.update({uid:req.body.uid}, {$set:{priority:newPriority, totalPriority:totalPriority}}, function (err,doc2){ - if(err){ console.log('(error updating priority) '+err); }else{ - io.emit('priorityChange', doc); - res.send(doc); - } - }); - } - } - }); - } + .run(req.db, function (err, doc) { + if(err){ console.log('(error finding item) '+err); } + else { + if (doc.priority){ + //exists + currentPriority=doc.priority; + } else { + currentPriority=[]; + } + //find if user already added + var userPriority = _.findWhere(currentPriority,{email:req.body.email}); + if (userPriority) { + var index = currentPriority.indexOf(userPriority); + var newPriority = currentPriority; + newPriority[index] = {email:req.body.email, value:req.body.value}; + } else { + //not added yet + var newPriority=currentPriority; + newPriority.push({email:req.body.email, value:req.body.value}); + } + + //add up all priorities: + var totalPriority = _.reduce(newPriority, function(memo,element){ return memo + element.value; },0); + + doc.totalPriority = totalPriority; + + if (newPriority){ + doc.priority=newPriority; + req.db.itemdb.update({uid:req.body.uid}, {$set:{priority:newPriority, totalPriority:totalPriority}}, function (err,doc2){ + if(err){ console.log('(error updating priority) '+err); }else{ + io.emit('priorityChange', doc); + res.send(doc); + } + }); + } + } + }); + } }); /** @@ -421,23 +428,23 @@ app.post('/api/setPriority', express.json(), function (req, res){ * @return int - the item */ app.post('/api/addComment', express.json(), function (req, res) { - if(!req.session.user){ - res.send({}); - } else { + if(!req.session.user){ + res.send({}); + } else { r.table("items").get(reg.body.uid).update( r.row('comments').append({ words:req.body.comment, by:req.body.email, time:moment().format(), }) - ).run(db, function (err, item){ - if(err){ console.log('(error updating comments) '+err); } + ).run(req.db, function (err, item){ + if(err){ console.log('(error updating comments) '+err); } else{ - io.emit('comment', item); - res.send(doc); - } - }); - } + io.emit('comment', item); + res.send(doc); + } + }); + } });//end add comment diff --git a/api/lock.js b/api/lock.js index d52fc25..9da55ea 100644 --- a/api/lock.js +++ b/api/lock.js @@ -1,7 +1,6 @@ var globalState = require("../server"), app = globalState.app, - express = globalState.express, - db = globalState.db; + express = globalState.express; /** * @desc various dependencies @@ -12,8 +11,7 @@ var _ = require('underscore'); var __ = require('lodash'); var dbInfo = require("../database/dbInfo"); -var dbHelper = require("../database/utils"); -__.assign(root, dbHelper); +var dbUtils = require("../database/utils"); /** @@ -30,7 +28,7 @@ app.post('/api/requestLock', express.json(), function (req, res){ } else { var syncLockPromise; r.table("items").get(req.body.uid) - .run(db, function (err, item){ + .run(req.db, function (err, item){ if(err||!item){ console.log('(error requesting lock on item) '+err); } else { if (item.lock){ @@ -39,7 +37,7 @@ app.post('/api/requestLock', express.json(), function (req, res){ res.send(item); } else { //does not have lock yet - syncLockPromise = changeLock(item,req.body.email, true); + syncLockPromise = dbUtils.changeLock(req.db, item,req.body.email, true); q.when(syncLockPromise).then(function(){ res.send(item); }); @@ -63,11 +61,11 @@ app.post('/api/removeLock', express.json(), function (req, res){ var syncLockPromise; if (req.body.uid) { console.log('removing lock for item: '+req.body.uid); - r.table("items").find(req.body.uid) - .run(db, function (err, item){ + r.table("items").get(req.body.uid) + .run(req.db, function (err, item){ if(err||!item){ console.log('(error removing lock on item) '+err); } else { - syncLockPromise = changeLock(item,req.body.email, false); + syncLockPromise = dbUtils.changeLock(req.db, item,req.body.email, false); q.when(syncLockPromise).then(function(){ res.send(item); }); @@ -90,11 +88,11 @@ app.post('/api/pickLock', express.json(), function (req, res){ var syncLockPromise; console.log('breaking lock for item: '+req.body.uid); r.table("items").get(req.body.uid) - .run(db, function (err, item){ + .run(req.db, function (err, item){ if(err||!item){ console.log('(error removing lock on item) '+err); } else { if(_.contains(item.owners, req.body.email)){ - syncLockPromise = changeLock(item,req.body.email, false); + syncLockPromise = dbUtils.changeLock(req.db, item,req.body.email, false); q.when(syncLockPromise).then(function(){ res.send(item); }); diff --git a/api/proposals.js b/api/proposals.js index fed4d90..2894b9f 100644 --- a/api/proposals.js +++ b/api/proposals.js @@ -1,7 +1,6 @@ var globalState = require("../server"), app = globalState.app, express = globalState.express, - db = globalState.db, io = globalState.io; /** @@ -12,7 +11,6 @@ var __ = require('lodash'); var dbInfo = require("../database/dbInfo"); var dbHelper = require("../database/utils"); -__.assign(root, dbHelper); /** * @api - proposal result @@ -31,8 +29,8 @@ app.post('/api/proposalResult', express.json(), function (req, res) { } }); if(theOne.key===req.body.key) { - r.table("items").get(req.body.uid).run(db, function (err, check) { - if (!check.length||check[0].uid!==req.body.uid) { + r.table("items").get(req.body.uid).run(req.db, function (err, check) { + if (check.uid!==req.body.uid) { return res.send(500); } //it is there @@ -40,10 +38,10 @@ app.post('/api/proposalResult', express.json(), function (req, res) { pushStuff.uid=req.body.uid; pushStuff[req.body.who]=req.body[req.body.who]; - var extendedItem = __.cloneDeep(check[0]); + var extendedItem = __.cloneDeep(check); _.extend(extendedItem,pushStuff); - syncItemPromise=updateItem(extendedItem, check[0]); + syncItemPromise=dbUtils.updateItem(req.db, extendedItem, check); q.when(syncItemPromise).then(function(){ //check if the project has been approved by everyone var approved = true; @@ -53,13 +51,13 @@ app.post('/api/proposalResult', express.json(), function (req, res) { console.log("approval is currently: "+approved); if (approved){ //update the item - r.table("items").get(extendedItem.forUID).run(db,function (err, check2){ + r.table("items").get(extendedItem.forUID).run(req.db,function (err, check2){ if(err){ console.log('(error getting item) '+err); }else{ //clone and add approval - var approvalItem = __.cloneDeep(check2[0]); + var approvalItem = __.cloneDeep(check2); _.extend(approvalItem,{approval:true}); console.log('approval item: '+approvalItem); - updateItem(approvalItem, check2[0]); + dbUtils.updateItem(req.db, approvalItem, check2); } }); } @@ -81,7 +79,7 @@ app.post('/api/saveProposal', express.json(), function (req, res) { if(!req.session.user){ res.send({}); } else { - req.body.uid=generateUID(); + req.body.uid = dbUtils.generateUID(); proposalSecrets[req.body.uid]=[]; var keys={}; @@ -89,11 +87,11 @@ app.post('/api/saveProposal', express.json(), function (req, res) { _(members).each(function(member){ req.body[member.name]={}; req.body[member.name].who = member.name; - keys[member.name] = generateUID(); + keys[member.name] = dbUtils.generateUID(); }); r.table("items").insert(req.body) - .run(db, function (err, doc) { + .run(req.db, function (err, doc) { if(err){ console.log('(error saving proposal) '+err); }else{ diff --git a/database/db.js b/database/db.js index da49572..6271ed4 100644 --- a/database/db.js +++ b/database/db.js @@ -8,7 +8,7 @@ r.connect( r.dbCreate("oratory").run(conn, function(err, status) { r.tableCreate('items', {primaryKey: 'uid'}) .run(conn, function(err, stat) { - r.table("items").indexCreate("types", {multi: true}) + r.table("items").indexCreate("type", {multi: true}) .run(conn, function(err, stat) {}); }); r.tableCreate('history', {primaryKey: 'key'}) @@ -32,7 +32,7 @@ module.exports = { createConnection : function(req, res, next) { r.connect({ host: 'localhost', port: 28015, db: 'oratory'}).then(function(conn) { // Save the connection in `req` - root.db = conn; + req.db = conn; // Pass the current request to the next middleware next(); }).error(handleError(res)); diff --git a/database/utils.js b/database/utils.js index 08a568c..1333a35 100644 --- a/database/utils.js +++ b/database/utils.js @@ -9,7 +9,6 @@ var moment = require('moment'); var gm = require('gm').subClass({ imageMagick: true }); var globalState = require("../server"), - db = globalState.db, io = globalState.io; /** @@ -22,10 +21,28 @@ if (!fs.existsSync('/vagrant/www/media/images')) { //default item image: var defaultImage = 'images/default.jpg'; +function generateUID() { + return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); + return v.toString(16); + }); +} + +function generateKey() { + return 'xxxxxxxxxxxx-4xxxyxxxxxx99xx-xxxxx00xxxx'.replace(/[xy]/g, function(c) { + var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); + return v.toString(16); + }); +} module.exports = { + respondCursor : function(res, cursor) { + cursor.toArray(function(err, docs) { + res.send(docs); + }); + }, //ITEMS -------------------------------- - updateItem : function(newItem, oldItem, unlock){ + updateItem : function(db, newItem, oldItem, unlock){ //returns a promise var saveItemPromise = q.defer(); var syncImagePromise; @@ -35,7 +52,7 @@ module.exports = { if (oldItem.imageURL!==newItem.imageURL){ console.log('saving new item image') var mediaUID = generateUID(); - syncImagePromise = saveImage(newItem.imageURL,mediaUID); + syncImagePromise = saveImage(db, newItem.imageURL,mediaUID); newItem.image = 'media/images/'+mediaUID+'/image.jpg'; newItem.thumb = 'media/images/'+mediaUID+'/thumb.jpg'; } @@ -49,7 +66,7 @@ module.exports = { console.log('saving new media image') var mediaImageUID=generateUID(); - syncMediaImagePromise = saveMediaImage(newMediaImage.rawImage, mediaImageUID); + syncMediaImagePromise = saveMediaImage(db, newMediaImage.rawImage, mediaImageUID); _.each(newItem.media, function (data,index){ //find the index and replace with new data if (_.has(data,'rawImage')) { @@ -70,19 +87,19 @@ module.exports = { console.log('remove: '+JSON.stringify(removeLoopUids)+' add: '+JSON.stringify(addLoopUids)); _.each(removeLoopUids, function(uid){ - findItem(uid).then(function(item){ + findItem(db, uid).then(function(item){ var itemCopy = __.cloneDeep(item); itemCopy.parents = _(itemCopy.parents).without(newItem.uid); - updateItem(itemCopy,item); + updateItem(db, itemCopy,item); }); }); _.each(addLoopUids, function(uid){ - findItem(uid).then(function(item){ + findItem(db, uid).then(function(item){ var itemCopy = __.cloneDeep(item); itemCopy.parents = itemCopy.parents || []; itemCopy.parents.push(newItem.uid); - updateItem(itemCopy,item); + updateItem(db, itemCopy,item); }); }); } @@ -95,19 +112,19 @@ module.exports = { console.log('remove: '+JSON.stringify(removeLoopUids)+' add: '+JSON.stringify(addLoopUids)); _.each(removeLoopUids, function(uid){ - findItem(uid).then(function(item){ + findItem(db, uid).then(function(item){ var itemCopy = __.cloneDeep(item); itemCopy.parents = _(itemCopy.parents).without(newItem.uid); - updateItem(itemCopy,item); + updateItem(db, itemCopy,item); }); }); _.each(addLoopUids, function(uid){ - findItem(uid).then(function(item){ + findItem(db, uid).then(function(item){ var itemCopy = __.cloneDeep(item); itemCopy.parents = itemCopy.parents || []; itemCopy.parents.push(newItem.uid); - updateItem(itemCopy,item); + updateItem(db, itemCopy,item); }); }); } @@ -118,6 +135,7 @@ module.exports = { historyItem.historical=true; historyItem.proposedChanges=false; + console.log("updating history"); //update and store history r.table("history").insert({ type:'history', @@ -130,6 +148,7 @@ module.exports = { delete newItem._id; //check to see if new image was sent + console.log("updating item"); r.table("items").get(newItem.uid).update(newItem).run(db, function (err, doc) { if(err){ console.log('(error updating item) '+err); @@ -149,7 +168,7 @@ module.exports = { return saveItemPromise.promise; }, - newItem : function(newItem){ + newItem : function(db, newItem){ //returns a promise var saveItemPromise = q.defer(); var syncImagePromise; @@ -165,7 +184,7 @@ module.exports = { if (newItem.imageURL) { //image url provided var mediaUID = generateUID(); - syncImagePromise = saveImage(newItem.imageURL,mediaUID); + syncImagePromise = saveImage(db, newItem.imageURL,mediaUID); newItem.image = 'media/images/'+mediaUID+'/image.jpg'; newItem.thumb = 'media/images/'+mediaUID+'/thumb.jpg'; }else{ @@ -173,7 +192,6 @@ module.exports = { newItem.image = defaultImage; newItem.thumb = defaultImage; } - console.log(db); r.table("items").insert(newItem).run(db, function (err, doc) { if(err){ console.log('(error saving item) '+err); @@ -192,7 +210,7 @@ module.exports = { //IMAGES -------------------------------- //takes a where (url), a uid to use, and who (opt - used for user added) - saveImage : function(where,theUID,who) { + saveImage : function(db, where,theUID,who) { //returns a promise var saveImagePromise = q.defer(); request.get({url: url.parse(where), encoding: 'binary'}, function (err, response, body) { @@ -230,7 +248,7 @@ module.exports = { return saveImagePromise.promise; }, - saveMediaImage : function(rawImage, uid) { + saveMediaImage : function(db, rawImage, uid) { var saveMediaImagePromise = q.defer(); var matches = rawImage.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/); var image = {}; @@ -275,7 +293,7 @@ module.exports = { }, //LOCKS -------------------------------- - changeLock : function(item,who,value){ + changeLock : function(db,item,who,value){ var changeLockPromise = q.defer(); var time = moment().format(); item.lock=value; @@ -300,7 +318,7 @@ module.exports = { return changeLockPromise.promise; }, - changeDecision : function(staged, who, what, value){ + changeDecision : function(db, staged, who, what, value){ var changeDecisionPromise = q.defer(); var time = moment().format(); @@ -324,7 +342,7 @@ module.exports = { return changeDecisionPromise.promise; } , - findItem : function(uid){ + findItem : function(db, uid){ var p=q.defer(); r.table("items").get(uid).run(db, function (err, doc) { if(err){ console.log('(error getting item) '+err); p.reject(err); }else{ p.resolve(doc); } @@ -332,17 +350,7 @@ module.exports = { return p.promise; }, - generateUID : function() { - return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) { - var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); - return v.toString(16); - }); - }, + generateUID : generateUID, - generateKey : function() { - return 'xxxxxxxxxxxx-4xxxyxxxxxx99xx-xxxxx00xxxx'.replace(/[xy]/g, function(c) { - var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); - return v.toString(16); - }); - }, + generateKey : generateKey, } diff --git a/server.js b/server.js index 5fe218b..1ac69d5 100644 --- a/server.js +++ b/server.js @@ -26,7 +26,6 @@ module.exports = { express: express, app: app, io: io, - db: undefined, } //app configuration From 6a9930904756bc384a477098c661ea8adf8420b3 Mon Sep 17 00:00:00 2001 From: Micha Gorelick Date: Sat, 19 Sep 2015 19:56:52 -0400 Subject: [PATCH 5/6] fixed getDatabase --- api/items.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/api/items.js b/api/items.js index a4eab4e..2818a88 100644 --- a/api/items.js +++ b/api/items.js @@ -36,10 +36,11 @@ function isEmpty(obj) { * @return object - full database */ app.get('/api/getDatabase', function (req, res) { - r.expr({ - "items" : r.table("items"), - "history" : r.table("history"), - }).run(req.db, function(err, docs) { + r.map( + r.table("items"), + r.table("history"), + function (items, history) { return {items: items, history: history}; } + ).run(req.db, function(err, docs) { if(err){ console.log('(error getting database) '+err);}else { res.send(docs.toArray()); } }); }); From 96104a580505c37b4a7b7c8b9eca0edbb2a5bec2 Mon Sep 17 00:00:00 2001 From: Micha Gorelick Date: Mon, 21 Sep 2015 15:16:13 -0400 Subject: [PATCH 6/6] make sure we use the right DB --- database/db.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/database/db.js b/database/db.js index 6271ed4..629b2b6 100644 --- a/database/db.js +++ b/database/db.js @@ -6,13 +6,16 @@ r.connect( ).then(function(conn) { console.log("Connected to rethinkdb"); r.dbCreate("oratory").run(conn, function(err, status) { + conn.use("oratory"); r.tableCreate('items', {primaryKey: 'uid'}) .run(conn, function(err, stat) { + console.log("Created items: " + err); r.table("items").indexCreate("type", {multi: true}) .run(conn, function(err, stat) {}); }); r.tableCreate('history', {primaryKey: 'key'}) .run(conn, function(err, stat) { + console.log("Created history: " + err); r.table("history").indexCreate("forUID", {multi: true}) .run(conn, function(err, stat) {}); });