Skip to content

Instantly share code, notes, and snippets.

@mostafiz57
Created April 16, 2014 13:20
Show Gist options
  • Save mostafiz57/10873906 to your computer and use it in GitHub Desktop.
Save mostafiz57/10873906 to your computer and use it in GitHub Desktop.
Couch Doc --Using for node.js proect
exports.initDB = initDB;
exports.setLogging = setLogging;
exports.readDocument = readDocument;
exports.readDesign = readDesign;
exports.saveDocument = saveDocument;
var idsArray = [];
exports.idsArray = idsArray;
idsServicesObject = [];
exports.idsServicesObject = idsServicesObject;
var mappedServiceUpOnStartUp = [];
exports.mappedServiceUpOnStartUp = mappedServiceUpOnStartUp;
exports.getIDSService = getIDSService;
exports.getMediaType = getMediaType;
exports.getIDSMapTable = getIDSMapTable;
exports.setIDSMapTable = setIDSMapTable;
exports.getAllRevisionDoc = getAllRevisionDoc;
exports.readDocumentWithRev = readDocumentWithRev;
exports.readDocucumentByRev = readDocucumentByRev;
exports.setRevsLimit = setRevsLimit;
exports.removeJob = removeJob;
exports.saveDigitalPrint = saveDigitalPrint;
exports.getAllDigitalPrint = getAllDigitalPrint;
exports.getDigitalPrintImage = getDigitalPrintImage;
exports.saveDigitalPrintReport = saveDigitalPrintReport;
exports.getAllDigitalPrintReport = getAllDigitalPrintReport;
var couchdb = require('felix-couchdb');
var flatiron = require('flatiron');
var winston = require('winston');
var fs = require('fs');
var mime = require('mime');
var tcp_app = require('../tcp');
var client;
var db;
var output = "";
var a = 0;
var a2 = -1;
var gaugesPanelhtml = '';
var chartdata = [];
var color = '';
var ServoStationNameArray = '';
var ServoNameArray = '';
var dbName;
var dbPort;
var dbHost;
var isFinished;
var initDBCallback = null
var createDBInterval = null
var createRemoteDBInterval= null;
var isDBCreated = false;
var isDBLoaded = false;
var isLoadJobs=false;
var isResourceDbSet = false;
var defaultStationColor = '#FF5B5B';
var fs = require('fs');
var async = require('async');
String.prototype.beginsWith = function(string) {
return(this.indexOf(string) === 0);
};
function updateDocuments(callback) {
var fileDir = 'couchDocuments/';
var files = fs.readdirSync(fileDir);
var count = files.length;
var callbackCount = 0;
for (indexer = 0; indexer < count; indexer++) {
file = files[indexer];
// winston.info(file);
var data = fs.readFileSync(fileDir + file, 'utf8');
jsonData = JSON.parse(data);
//console.log("\nExecuting: ", jsonData._id, jsonData._attachments);
// We will look for attachements in the parsed JSON data
var queryForAttachments = "_attachments";
var keys = [];
for (var key in jsonData) {
keys.push(key);
}
var allFileAttachments = {};
if (keys.indexOf(queryForAttachments) > -1) {
// We will look for _attachments key and when found, process futher
var partialsDir = 'views/partials';
var myPartials = fs.readdirSync(partialsDir);
myPartials.forEach(function(partialFile) {
if (partialFile.beginsWith(file)) {
var partialFilePath = partialsDir + '/' + partialFile;
// To add an attachment to a doc, we need the mime type and base64 encoded data
var fileAttachment = {};
fileAttachment.content_type = mime.lookup(partialFilePath);
fileAttachment.data = fs.readFileSync(partialFilePath, 'base64');
// Add fileAttachment object to file name
allFileAttachments[partialFile] = fileAttachment;
}
});
var printJobDir = 'views/images/printjob';
var smallImagesDir = printJobDir+'/small';
//var mediumImagesDir = printJobDir+'/medium';
var largeImagesDir = printJobDir+'/large';
var smallImages = fs.readdirSync(smallImagesDir);
// var mediumImages = fs.readdirSync(mediumImagesDir);
var largeImages = fs.readdirSync(largeImagesDir);
//console.log("Small Images : ",smallImages);
jsonData.hasThumbnailImage = false;
smallImages.forEach(function(smallImageFile) {
if (smallImageFile.beginsWith(file)) {
var imageFilePath = smallImagesDir + '/' + smallImageFile;
// To add an attachment to a doc, we need the mime type and base64 encoded data
var fileAttachment = {};
fileAttachment.content_type = mime.lookup(imageFilePath);
fileAttachment.data = fs.readFileSync(imageFilePath, 'base64');
// Add fileAttachment object to file name
allFileAttachments[smallImageFile] = fileAttachment;
}
if(allFileAttachments[smallImageFile]){
jsonData.hasThumbnailImage = true;
}else{
// jsonData.hasThumbnailImage = false;
}
});
//console.log("Large Images : ",largeImages);
jsonData.hasLargerImage = false;
largeImages.forEach(function(largeImageFile) {
if (largeImageFile.beginsWith(file)) {
var imageFilePath = largeImagesDir + '/' + largeImageFile;
// To add an attachment to a doc, we need the mime type and base64 encoded data
var fileAttachment = {};
fileAttachment.content_type = mime.lookup(imageFilePath);
fileAttachment.data = fs.readFileSync(imageFilePath, 'base64');
// Add fileAttachment object to file name
allFileAttachments[largeImageFile] = fileAttachment;
}
if(allFileAttachments[largeImageFile]){
jsonData.hasLargerImage = true;
}else{
// jsonData.hasLargerImage = false;
}
});
}
// Finally add the attachment object to jsonData
jsonData._attachments = allFileAttachments;
delete jsonData["_rev"];
db.saveDoc(jsonData, function(error, doc) {
if (error) {
console.log("\nError: ", error, jsonData._id, jsonData._attachments);
}
callbackCount++;
if (callbackCount == (count - 1)) {
callback();
}
});
}
}
function updateDesignDocRemote(callback) {
var file = 'couchDocuments/_design_digitalPrint';
var data = fs.readFileSync(file, 'utf8');
jsonData = JSON.parse(data);
delete jsonData["_rev"];
db.saveDoc(jsonData, function(error, doc) {
if (error) {
winston.error('Error in uploading ' + jsonData._id + ' to remote database ' + dbName);
process.exit(-1);
} else {
winston.info('Successfully uploaded ' + jsonData._id + ' to remote database ' + dbName);
callback();
}
});
}
function dbCreateCallback(err, data) {
if (!isDBCreated && err == null && data && data.ok == true) {
isDBCreated = true;
clearInterval(createDBInterval);
updateDocuments(initDBCallback);
} else if (err && err.error && err.error == "file_exists") {
clearInterval(createDBInterval);
checkMapTable(initDBCallback);
} else {
winston.debug("Unable to reach CouchDB, attempting again");
}
}
function checkMapTable(callBack){
db.getDoc('MapTable', function(err, doc) {
if (err) {
winston.error('MapTable not found in DB ' + dbName + '. Trying upload...');
var file = 'couchDocuments/MapTable';
var data = fs.readFileSync(file, 'utf8');
jsonData = JSON.parse(data);
winston.log(jsonData);
delete jsonData["_rev"];
db.saveDoc(jsonData, function(error, doc) {
if (error) {
winston.error('Error uploading ' + jsonData._id + ' to database ' + dbName + '.');
} else {
winston.info('Successfully uploaded ' + jsonData._id + ' to database ' + dbName);
}
callBack();
});
} else {
callBack();
}
});
}
function updateSubstrate(callBack) {
var fileDir = 'couchDocuments/';
var files = fs.readdirSync(fileDir);
var count = files.length;
var callbackCount = 0;
for (indexer = 0; indexer < count; indexer++) {
var file = files[indexer];
// winston.info("----"+file);
var data = fs.readFileSync(fileDir + file, 'utf8');
var jsonData = JSON.parse(data);
callbackCount++;
// winston.info('count:'+count+" calbakccount:"+callbackCount);
if (jsonData._id !== "_design/substrates" && jsonData._id !== "_design/digitalPrint") {
// winston.info('---in continue---');
if(callbackCount == (count -1)){
setTimeout(callBack,1000);
}
continue;
}
delete jsonData["_rev"];
db.saveDoc(jsonData, function(error, doc) {
if (error) {
winston.error('Error in uploading ' + jsonData._id + ' to remote database ' + dbName);
} else {
winston.info('Successfully uploaded ' + jsonData._id + ' to remote database ' + dbName);
}
if ( callbackCount == (count -1)) {
callBack();
}
});
}
}
function remoteDBCreateCallback(err, data) {
if (!isDBCreated && err == null && data && data.ok == true) {
isDBCreated = true;
clearInterval(createRemoteDBInterval);
checkMapTable(function(){});
updateSubstrate(function(){initDBCallback();});
} else {
winston.debug("Unable to reach CouchDB, attempting again");
}
}
function initDB(host, hostPort, dbname, loadJobs, resourceDbName, callback) {
dbName = dbname;
dbPort = hostPort;
dbHost = host;
isLoadJobs=loadJobs;
isFinished = false;
initDBCallback = callback;
client = couchdb.createClient(host, hostPort);
db = client.db(dbname);
if(resourceDbName != null && resourceDbName != "undefined"){
clientResource = couchdb.createClient(host, hostPort);
dbResource = clientResource.db(resourceDbName);
isResourceDbSet = true;
}
if (!isLoadJobs) {
db.exists(function(err, exists) {
if(err){
winston.error('Error connecting '+dbHost+':'+dbPort+' database ' + dbName );
process.exit(-1);
//winston.info('Error in connecting remote database');
}
if (!exists) {
createRemoteDBInterval = setInterval(function() {
db.create(remoteDBCreateCallback);
}, 1000);
} else {
checkMapTable(function(){});
readDesign('digitalPrint', 'all', {}, function(err, doc) {
if (err) {
winston.debug('No digitalPrint type doc found in remote database. Trying upload...');
updateDesignDocRemote(function() {
isDBCreated = true;
winston.debug("Connected to remote database.");
});
} else {
// winston.info("Job Doc:"+JSON.stringify(doc));
if (doc.total_rows == 0) {
// winston.error('No jobs found in database ' + dbName);
// process.exit(-1);
}
isDBCreated = true;
winston.debug("Connected to remote database.");
}
isDBCreated = true;
updateSubstrate(function(){ initDBCallback();});
});
}
});
} else {
winston.debug("starting db create");
createDBInterval = setInterval(function() {
db.create(dbCreateCallback);
}, 1000);
}
}
function setLogging(logger) {
winston = logger;
}
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
function readDocument(doc_id, callback, getResource) {
if(isResourceDbSet == true && getResource != null && getResource != "undefined"){
dbResource.getDoc(doc_id, callback);
}else {
db.getDoc(doc_id, callback);
}
}
function readDesign(design, view, query, callback) {
db.view(design, view, query, callback);
}
function saveDocument(doc, callback) {
db.saveDoc(doc, callback);
}
function readDocumentWithRev(doc_id, rev, callback) {
db.getDoc(doc_id, rev, callback);
}
function getAllDocRevs(doc_id, callback) {
client.request({
path: '/' + databasename + '/' + doc_id,
query: {
revs_info: true
},
full: true
}, callback);
}
function command(cmd, callback) {
var exec = require('child_process').exec;
exec(cmd, {}, callback);
}
function setRevsLimit(limit) {
var cmd = 'curl -X PUT -d "' + limit + '" http://' + dbHost + ':' + dbPort + '/' + dbName + '/_revs_limit';
command(cmd, function(error, stdout, stderr) {
if (error !== null) {
console.log('Error setting revision limit. ' + error);
}
else {
winston.info('Revision limit set successfully ' + stdout);
}
});
}
function getAllRevisionDoc(req, res, doc_id, totalcount) {
getAllDocRevs(doc_id, function(err, resp) {
if (err) {
//console.log("Revs Error Response...", err);
} else {
console.log("Revs Response...");
if (resp.json._revs_info.length) {
var doc_id = resp.json._id;
var revs = [];
if (totalcount) {
if (resp.json._revs_info.length < totalcount) {
totalcount = resp.json._revs_info.length;
}
} else {
totalcount = resp.json._revs_info.length;
}
for (var i = 0; i < totalcount; i++) {
revs.push(resp.json._revs_info[i].rev);
}
var respJSON = {
_id: doc_id,
revs: revs
}
//console.log("REVS " + (i + 1) + " ::::::::::::::: ", respJSON);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(JSON.stringify(respJSON));
}
}
});
}
function readDocucumentByRev(req, res, doc_id, rev_id) {
var rev = [rev_id];
readDocumentWithRev(doc_id, rev, function(err, doc) {
if (err) {
console.log(err);
} else {
//console.log(doc);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(JSON.stringify(doc));
}
});
}
function getAllDigitalPrint(req, res){
var search = "";
if(req.query.search){
search = req.query.search;
}
var key = {};
if (search) {
//key = {"key": search};
}
//console.log("key : ", key)
readDesign('digitalPrint', 'all', key, function(err, doc){
if(err){
res.json(err);
}else{
var dbIP = dbHost;
if(dbHost == 'localhost'){
var os = require('os');
var interfaces = os.networkInterfaces();
var addresses = [];
for (k in interfaces) {
for (k2 in interfaces[k]) {
var address = interfaces[k][k2];
if (address.family == 'IPv4' && !address.internal) {
addresses.push(address.address)
}
}
}
//console.log("IPS: ",addresses)
if(addresses && addresses[0]){
dbIP = addresses[0];
}
}
var matches = [];
if (search) {
doc.rows.forEach(function (row) {
if (row.key.toLowerCase().indexOf(search.toLowerCase()) > -1) {
for(var key in row.value._attachments){
var fileURL = 'http://' + dbIP + ':' + dbPort + '/' + dbName + '/' + row.id + '/' + key;
//var fileURL = row.id + '/' + key;
if(key.indexOf('_small') > 0){
row.value.image_small = fileURL;
}
if(key.indexOf('_large') > 0){
row.value.image_large = fileURL;
}
}
matches.push(row);
}
});
} else {
//matches = doc.rows;
doc.rows.forEach(function (row) {
for(var key in row.value._attachments){
var fileURL = 'http://' + dbIP + ':' + dbPort + '/' + dbName + '/' + row.id + '/' + key;
//var fileURL = row.id + '/' + key;
// console.log(fileURL);
if(key.indexOf('_small') > 0){
row.value.image_small = fileURL;
}
if(key.indexOf('_large') > 0){
row.value.image_large = fileURL;
}
}
matches.push(row);
});
}
if(typeof req.query.jsoncallback !== 'undefined'){
res.end(req.query.jsoncallback + '(' +JSON.stringify(matches)+ ');');
} else{
res.end(JSON.stringify(matches));
}
}
});
}
function saveDigitalPrint(req, res){
var reqData = req.query.data;
db.getDoc(doc_id, function (err, body) {
if (err) { // if _rev don' exist
var mydata = {};
mydata.docType = reqData.docType;
mydata.imageLink = reqData.imageLink;
mydata.createDate = Number(new Date().getTime());
//console.log("Data to save : ", mydata);
db.saveDoc(mydata, function (error, doc) {
if (error) {
res.json(error);
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(doc));
}
});
} else { // if _rev exist
mydata.imageLink = reqData.imageLink;
db.saveDoc(body, function (error, doc) {
if (error) {
res.json(error);
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(doc));
}
});
}
});
}
function removeJob(req, res){
var doc_id = req.query.jobid;
db.getDoc(doc_id, function (err, body) {
if (err) {
res.json(err);
}else{
db.removeDoc(body._id, body._rev, function (error, result) {
if (error) {
if(typeof req.query.jsoncallback !== 'undefined'){
res.end(req.query.jsoncallback + '(' +JSON.stringify(error)+ ');');
} else{
res.end(JSON.stringify(error));
}
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
if(typeof req.query.jsoncallback !== 'undefined'){
res.end(req.query.jsoncallback + '(' +JSON.stringify(result)+ ');');
} else{
res.end(JSON.stringify(result));
}
}
});
}
});
}
function getIDSService(req, res){
// winston.info('-------idsArray:'+JSON.stringify(idsArray));
//winston.info('-------mappedServiceUpOnStartUp:'+JSON.stringify(mappedServiceUpOnStartUp));
var callbackFunc = (typeof req.query.jsoncallback !== 'undefined') ? req.query.jsoncallback : '';
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(callbackFunc + '(' + JSON.stringify({'idsArray':idsArray,'idsStatus':tcp_app.upService}) + ');');
}
function getMediaType(req, res){
var callbackFunc = (typeof req.query.jsoncallback !== 'undefined') ? req.query.jsoncallback : '';
readDesign('substrates', 'allSubstrates', {}, function(err, doc){
if(err){
}else{
// winston.info('-------Substrates doc:'+JSON.stringify(doc));
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(callbackFunc + '(' + JSON.stringify({'Substrates': doc}) + ');');
}
});
}
function getIDSMapTable(req, res) {
var callbackFunc = (typeof req.query.jsoncallback !== 'undefined') ? req.query.jsoncallback : '';
db.getDoc('MapTable', function(err, doc) {
if (err) {
res.json(err);
} else {
// winston.info('-------Maptable doc:'+JSON.stringify(doc));
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(callbackFunc + '(' + JSON.stringify({'MapTable': doc}) + ');');
}
});
}
function setIDSMapTable(req, res) {
var callbackFunc = (typeof req.query.jsoncallback !== 'undefined') ? req.query.jsoncallback : '';
db.getDoc('MapTable', function(err, doc) {
if (err) {
res.json(err);
} else {
doc.services = req.query.data;
db.saveDoc(doc, function (error, doc) {
if (error) {
res.json(error);
} else {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(callbackFunc + '(' + JSON.stringify(doc) + ');');
var ids_index = Number(req.query.change.index);
// var idsNo;
if(req.query.change.deleted != null && req.query.change.deleted != 'undefined'){
// tcp_app.deleteIDSService('IDS'+req.query.change.deleted);
//idsNo = req.query.change.deleted;
// winston.info('deleted idsArray:'+idsArray+' typeof idsArray[0]:'+typeof idsArray[0]+' ids_index:'+ids_index);
idsServicesObject[ids_index] = req.query.data[ids_index];
// idsArray[ids_index] = 0;
//winston.info('ids_index:'+ids_index);
winston.info('idsServicesObject deleted:'+JSON.stringify(idsServicesObject));
}
if(req.query.change.added != null && req.query.change.added != 'undefined'){
tcp_app.initiateService('IDS'+req.query.change.added);
//idsNo = req.query.change.added;
//var ids_index = idsArray.indexOf(idsNo);
// winston.info('added idsArray:'+idsArray+' typeof idsArray[0]:'+typeof idsArray[0]+' ids_index:'+ids_index);
idsServicesObject[ids_index] = req.query.data[ids_index];
winston.info('idsServicesObject added:'+JSON.stringify(idsServicesObject));
}
if(ids_index != 'undefined' && ids_index != null && ids_index != -1){
if( req.query.data[ids_index].available.toString().toLowerCase() == 'true'){
idsArray[ids_index] = req.query.change.added.toString();
}else {
idsArray[ids_index] = 0;
}
}
}
});
}
});
}
function getAllDigitalPrintReport(req, res){
var search = "";
if(req.query.search){
search = req.query.search;
}
var key = {};
if (search === "") {
search = null;
}
//console.log("search : ", search, "\n\n", key)
readDesign('getAllDigitalPrintReport', 'all', key, function(err, doc){
if(err){
res.json(err);
}else{
var matches = [];
if (search) {
doc.rows.forEach(function (row) {
if (row.key.toLowerCase().indexOf(search.toLowerCase()) > -1) {
matches.push(row);
}
});
} else {
matches = doc.rows;
}
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(matches));
}
});
}
function getDigitalPrintImage(req, res){
var jobid = "";
if(req.query.jobid){
jobid = req.query.jobid;
}
var type = "small";
if(req.query.type){
type = req.query.type;
}
db.getDoc(jobid, function (error, body) {
if (body) {
var fileName = body._id+'_'+type;
var contentType = "";
for(var key in body._attachments){
if(key.indexOf(fileName) > -1){
contentType = body._attachments[key].content_type;
fileName = key;
}
}
var imageURL = 'http://' + dbHost + ':' + dbPort + '/' + dbName + '/' + jobid + '/' + fileName;
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(imageURL);
/*console.log(fileName, contentType);
var imageFileName = fileName;
db.getAttachment(jobid, imageFileName, function (err, data) {
if(data){
res.writeHead(200, { 'Content-Type': contentType });
//res.end(data);
res.end("<img src='"+data+"' alt='"+fileName+"' />");
}else{
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.json(error);
}
});*/
//res.writeHead(200, { 'Content-Type': 'text/html' });
//res.writeHead(200, {'Content-Type': 'image/jpeg'});
//res.end("<img src='"+imageURL+"' alt='"+fileName+"' />");
/*var fileParts = fileName.split('.');
var contentType = 'image/'+fileParts[(fileParts.length - 1)];
contentType = "text/html";
console.log('content type : '+contentType)
res.writeHead(200, {'Content-Type': contentType});
res.end("<img src='"+imageURL+"' alt='"+fileName+"' />");*/
//fs.readFile(imageURL, function(err, data) {
// res.end(data);
//});
}else{
res.json(error);
}
});
}
function saveDigitalPrintReport(req, res){
var reqData = req.query.data;
db.getDoc(doc_id, function (err, body) {
if (err) { // if _rev don' exist
var mydata = {};
mydata.createDate = Number(new Date().getTime());
mydata.docType = reqData.docType;
mydata.digitalPrintId = reqData.digitalPrintId;
mydata.printMedia = reqData.printMedia;
mydata.totalPrint = parseInt(reqData.totalPrint, 10);
mydata.totalPrintSuccess = parseInt(reqData.docType, 10);
//console.log("Data to save : ", mydata);
db.saveDoc(mydata, function (error, doc) {
if (error) {
res.json(error);
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(doc));
}
});
} else { // if _rev exist
body.totalPrintSuccess = parseInt(body.docType, 10);
db.saveDoc(body, function (error, doc) {
if (error) {
res.json(error);
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(JSON.stringify(doc));
}
});
}
});
}
function landingPage(req, res, Plates){
var path = '/../views/dpm.html';
var template = fs.readFileSync(__dirname + path, "utf-8");
var rendered = Plates.bind(template);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(rendered);
}
exports.landingPage = landingPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment