Created
June 6, 2015 18:40
-
-
Save forsythetony/9bae806a7f0c6594917c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dbName = "photoArchiving", | |
collectionName = "photos", | |
subfolderName = "mainPhotos/"; | |
var mongo = require('mongodb'), | |
sprintf = require('sprintf').sprintf, | |
fs = require('fs'), | |
moment = require('moment'), | |
aws = require('../awsConnections/awsTest.js'); | |
var Server = mongo.Server, | |
Db = mongo.Db, | |
BSON = mongo.BSONPure; | |
var server = new Server( "127.0.0.1", | |
27017, | |
{auto_reconnect: true} | |
); | |
var db = new Db(dbName, server); | |
db.open(function(err, db) { | |
if(!err) { | |
console.log(sprintf("Connected to the %s database.", dbName.toString())); | |
db.collection(collectionName, {strict:true}, function(err, collection) { | |
if (err) { | |
console.log(sprintf("The %s collection does not exist.", collectionName)); | |
db.createCollection(collectionName, function(err, result) { | |
if (err) { | |
console.log("The collection could not be created."); | |
} | |
else { | |
console.log(sprintf("The collection %s was successfully created!", collectionName)); | |
} | |
}); | |
} | |
}); | |
} | |
else { | |
console.log("There was an error connecting to the database."); | |
} | |
}); | |
exports.findById = function(req, res) { | |
var id = req.params.id; | |
var clearStoriesFlag = req.query['clearStories']; | |
var storyIDToDelete = req.query['deleteStoryWithID']; | |
var updateFlag = req.query['updateFlag']; | |
if(updateFlag) | |
{ | |
if(updateFlag == "date") | |
{ | |
var newDate = req.query['newValue']; | |
db.collection(collectionName, function(err, collection) { | |
collection.update({'_id':new BSON.ObjectID(id)}, { $set: { "imageInformation.dateTaken.dateString" : newDate }}, function(err, result) { | |
if (err) { | |
var errorMessage = ("Error setting Date" + err); | |
console.log(errorMessage); | |
res.send( 500 , errorMessage); | |
} else { | |
var successMessage = "Date set."; | |
res.send( 200 , successMessage); | |
} | |
}); | |
}); | |
} | |
} | |
else if(clearStoriesFlag == 'true') | |
{ | |
console.log("Clearing Stories"); | |
db.collection(collectionName, function(err, collection) { | |
collection.update({'_id':new BSON.ObjectID(id)}, { $set: { "Stories" : [] }}, function(err, result) { | |
if (err) { | |
var errorMessage = ("Error reseting stories." + err); | |
console.log(errorMessage); | |
res.send( 500 , errorMessage); | |
} else { | |
var successMessage = "Reset Stories"; | |
res.send( 200 , successMessage); | |
} | |
}); | |
}); | |
} | |
else if( storyIDToDelete) | |
{ | |
console.log("Deleting Story with id" + storyIDToDelete); | |
db.collection(collectionName, function(err, collection) { | |
collection.update({'_id':new BSON.ObjectID(id)}, { $pull : { "Stories" : { "stringId" : storyIDToDelete }}}, function(err, result) { | |
if (err) { | |
var errorMessage = ("Error removing story." + err); | |
console.log(errorMessage); | |
res.send( 500 , errorMessage); | |
} else { | |
var successMessage = "Removed Story"; | |
res.send( 200 , successMessage); | |
} | |
}); | |
}); | |
} | |
else | |
{ | |
console.log('Retrieving photo: ' + id); | |
db.collection(collectionName, function(err, collection) { | |
collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) { | |
if (!err) { | |
res.send(200, item); | |
} | |
else { | |
res.send(404, err); | |
} | |
}); | |
}); | |
} | |
}; | |
exports.findAll = function(req, res) { | |
var cleanFlag = req.query['cleanFlag']; | |
if (cleanFlag == 'true') { | |
db.collection(collectionName, function(err, collection) { | |
collection.find({"imageData" : { $exists : true}}).toArray(function(err, items) { | |
if (items.length != 0) { | |
var removeMessage = sprintf("Removing the following...\n", items); | |
collection.remove({"imageData" : {$exists : true}}); | |
res.send(removeMessage); | |
} | |
else { | |
res.send(500, "The items could not be found."); | |
} | |
}); | |
}); | |
} | |
else { | |
if (!req.query['username']) { | |
db.collection(collectionName, function(err, collection) { | |
collection.find().toArray(function(err, items) { | |
res.send(items); | |
}); | |
}); | |
} | |
else | |
{ | |
var username = req.query['username']; | |
db.collection(collectionName, function(err, collection) { | |
collection.find({"uploadInformation" : {"uploader" : username}}).toArray(function(err, items) { | |
if (items.length != 0) { | |
res.send(200, items); | |
} | |
else { | |
res.send(500, "No documents could be found for the user."); | |
} | |
}); | |
}); | |
} | |
} | |
} | |
// This function expects to receive a JSON package in the following format | |
// { | |
// imageInformation : { | |
// title : "titleString" | |
// }, | |
// uploadInformation : { | |
// dateUploaded : "dateTime", | |
// uploader : "userNameString", | |
// }, | |
// imageData : "base64 encoded data string" | |
// } | |
exports.addPhoto = function(req, res) { | |
var photo = req.body; | |
validateData(photo, function(err, data) { | |
if (!err) { | |
console.log(data); | |
db.collection(collectionName, function(err, collection) { | |
collection.insert(data, function(err, result) { | |
if (!err) { | |
var imageData = new Buffer(data['imageData'], 'base64'); | |
if (data['thumbData']) { | |
var thumbData = new Buffer(data['thumbData'], 'base64'); | |
} | |
else { | |
var thumbData = null; | |
} | |
var imageDictionary = { "imageBuffer" : imageData, | |
"imageThumb" : thumbData, | |
"imageName" : fixTitleString(data['imageInformation']['title']), | |
"bucketName" : "node-photo-archive", | |
"collectionName": collection, | |
"userID" : data._id, | |
"contentType" : data['contentType']}; | |
uploadPhoto(imageDictionary, res, collection , function(err, result) { | |
if (!err) { | |
res.send(201, {"result" : "Photo was successfully added.", "updatedEntry" : result}); | |
} | |
else { | |
res.send(500, "Could not upload photo."); | |
} | |
}); | |
} | |
}); | |
}); | |
} | |
else { | |
res.send(400, {"errorMessage" : err}); | |
} | |
}); | |
} | |
exports.addPhotoWithURL = function(req, res) | |
{ | |
var photoData = req.body; | |
console.log(photoData); | |
db.collection(collectionName, function(err, collection) { | |
collection.insert(photoData, function(err, result) { | |
if (!err) { | |
res.send(200, "Complete"); | |
} | |
else | |
{ | |
res.send(500, "Error"); | |
} | |
}); | |
}); | |
} | |
exports.updatePhoto = function(req, res) { | |
var addStory = false; | |
if(req.params.addStory) | |
{ | |
if( req.params.addStory == "adding") | |
{ | |
var newStory = req.body; | |
db.collection(collectionName, function(err, collection) { | |
collection.update({'_id':new BSON.ObjectID(id)}, { $addToSet: { "Stories" : newStory }}, function(err, result) { | |
if (err) { | |
var errorMessage = ("Error adding story." + err); | |
console.log(errorMessage); | |
res.send( 500 , errorMessage); | |
} else { | |
collection.find({'_id':new BSON.ObjectID(id)}).toArray(function(err, docs) { | |
var entry = docs[0]; | |
res.send(201, { "responseSummary" : "Document was succesfully updated.", | |
"updatedEntry": user | |
}); | |
}); | |
} | |
}); | |
}); | |
} | |
} else | |
{ | |
var hardUpdate = false; | |
var id = req.params.id, | |
user = req.body; | |
console.log(sprintf("The data is %s", JSON.stringify(req.body) )); | |
if(req.query.updateType == "hard") { | |
console.log("You have chosen a hard update."); | |
hardUpdate = true; | |
} | |
console.log(sprintf("Update type chosen: %s", (hardUpdate ? "hard" : "soft"))); | |
console.log('Updating user: ' + id); | |
db.collection(collectionName, function(err, collection) { | |
collection.update({'_id':new BSON.ObjectID(id)}, { $addToSet: { "Stories" : user }}, function(err, result) { | |
if (err) { | |
console.log('Error updating user: ' + err); | |
res.send({'error':'An error has occurred'}); | |
} else { | |
collection.find({'_id':new BSON.ObjectID(id)}).toArray(function(err, docs) { | |
var entry = docs[0]; | |
res.send(201, { "responseSummary" : "Document was succesfully updated.", | |
"updatedEntry": user | |
}); | |
}); | |
} | |
}); | |
}); | |
} | |
} | |
exports.deletePhoto = function(req, res) { | |
var id = req.params.id; | |
console.log('Deleting photo: ' + id); | |
db.collection(collectionName, function(err, collection) { | |
collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) { | |
if (err) { | |
res.send({'error':'An error has occurred - ' + err}); | |
} else { | |
console.log('' + result + ' document(s) deleted'); | |
res.send(204, req.body); | |
} | |
}); | |
}); | |
} | |
function fixTitleString(title) | |
{ | |
if (!title) { | |
return null; | |
} | |
// Remove white space | |
var cleanTitle = title.replace(/ /g,"_"); | |
cleanTitle = cleanTitle.replace(/'/g,""); | |
var now = moment().toISOString(); | |
cleanNow = now.replace(".", "-"); | |
cleanNow = cleanNow.replace(":", "-"); | |
return sprintf("%s%s", cleanTitle, cleanNow); | |
} | |
function validateData(data, callback) { | |
// Make sure there is an image | |
console.log(data); | |
if (!data['imageData']) { | |
var error = "You did not provide an image to use."; | |
callback(error, null); | |
} | |
if (!data['imageInformation']['title']) { | |
data['imageInformation']['title'] = "untitled"; | |
} | |
if (!data['uploadInformation']) { | |
data['uploadInformation'] = { "dateUploaded" : moment().toISOString(), | |
"uploader" : "unknown" | |
}; | |
} | |
else { | |
if(!data['uploadInformation']['dateUploaded']) { | |
var currentTime = moment(); | |
var dateDictionary = { "ISODate" : currentTime.toISOString(), | |
"Unix" : currentTime.unix(), | |
"year" : currentTime.format('YYYY'), | |
"month" : currentTime.format('MM'), | |
"day" : currentTime.format('DD'), | |
"hour" : currentTime.format('H'), | |
"minute" : currentTime.format('m'), | |
"second" : currentTime.format('s') }; | |
data['uploadInformation']['dateUploaded'] = dateDictionary; | |
} | |
} | |
callback(null, data); | |
} | |
exports.addInformationToPhoto = function( req , res ) { | |
var addingStory = req.query['addStory']; | |
var id = req.params.id; | |
var newStory = req.body; | |
if( addingStory ) | |
{ | |
var newStory = req.body; | |
console.log(JSON.stringify( newStory )); | |
db.collection(collectionName, function(err, collection) { | |
collection.update({'_id':new BSON.ObjectID(id)}, { $addToSet: { "Stories" : newStory }}, function(err, result) { | |
if (err) { | |
var errorMessage = ("Error adding story." + err); | |
console.log(errorMessage); | |
res.send( 500 , errorMessage); | |
} | |
else | |
{ | |
collection.find({'_id':new BSON.ObjectID(id)}).toArray(function(err, docs) { | |
var entry = docs[0]; | |
res.send(201, { "responseSummary" : "Document was succesfully updated.", | |
"updatedEntry": newStory | |
}); | |
}); | |
} | |
}); | |
}); | |
} | |
else | |
{ | |
res.send( 500 , "I cant handle that right now." ); | |
} | |
} | |
function uploadPhoto(imageData, res, thecollection, callback) | |
{ | |
var bucketName = imageData["bucketName"]; | |
var imageName = sprintf("%s%s", subfolderName, imageData['imageName']); | |
var collection = imageData["collectionName"]; | |
var userID = imageData["userID"]; | |
var imageBuffer = imageData["imageBuffer"]; | |
var thumbData = imageData["imageThumb"]; | |
var contentType = imageData["contentType"]; | |
aws.addJpegtoBucket(bucketName, imageName, imageBuffer, contentType, thumbData, function(err, imageData) { | |
if (!err) { | |
var mainImageUrl = imageData["mainImage"]["url"]; | |
var thumbnailImageUrl = imageData["thumbnail"]["url"]; | |
var setDict = { | |
imageURL : mainImageUrl, | |
thumbnailURL : thumbnailImageUrl | |
}; | |
var unsetDict = { | |
imageData : 1, | |
thumbData : 1 | |
}; | |
thecollection.update({'_id':new BSON.ObjectID(userID)}, { $set : setDict, $unset : unsetDict}, function(err, result) { | |
if (!err) { | |
thecollection.find({'_id':new BSON.ObjectID(userID)}).toArray(function(err, docs) { | |
callback(null, docs[0]); | |
}); | |
} | |
else { | |
callback(err, null); | |
} | |
}); | |
} | |
else { | |
callback(err,null); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment