File size: 6,964 Bytes
cbc76af | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | /**
* This file/module controllers the the routes relating to the graph.
* These are /plot/*
*/
var url = require( 'url' );
var GraphJob = require( root + '/src/GraphJob' );
var domain = require('domain');
var tmp = require('tmp');
var request = require('request');
var archiver = require('archiver');
var path = require('path');
var Lateral = require('lateral').Lateral;
var Increment = require("incr");
module.exports = graphController;
function graphController(){};
/**
* Handlers the creation of new graphs.
* Expects a graph request. See example folder for
* graph request examples.
*
* @return JSON Returns JSON string with the id of the job
*/
graphController.create = function( req, res, next ){
var request = req.param( 'request' );
var job = new GraphJob().graphRequest( request );
manager.addJob( job );
// Return details about the job
res.json({
'job_id': job.id()
});
};
/**
* Returns the current status of a job you requested.
* With throw 404 if the job id doesnt exist.
* Jobs can throw a 404 is the server restarted.
*
* @return {JSON} Status of the job you requested
*/
graphController.status = function( req, res, next ){
var job = manager.getJob( req.param( 'id' ).input );
if( ! job ){
return res.send(404, {
'status' : 'error',
'messsage': 'This job id has not been found on the server.'
});
}
var status = job.status();
status.job_id = job.id();
res.json( status );
};
/**
* Returns the data of the job in the requested format.
* Correct headers are sent to match the content type.
* Relevant types:
* interactive : Used for the popup to load the graph, sidebar,etc
* data : Returns the JSON needed to display the graph. Used by
* interactive but could be used by anything.
* png : A PNG of the graph, requirments differ depending on graph type
* svg : Same as above, paramaters need to complete the request
* will depend on graph type
*
*
* @return {Binary} Returns data that suits the Job type
*/
graphController.show = function( req, res, next ){
// Find the job of throw 404
var job = manager.getJob( req.param( 'id' ).input );
if( !job )
return res.send( 404, "Job not found" );
var graph = job._graph;
// Get the rquest show format
var returnType = req.param( 'returnType' ).input;
logger.log('info', 'Serving graph in format ' + returnType , { job_id : job.id(), return_type : returnType });
// Create a domain in case it errors
var d = domain.create();
d.on('error', next);
d.run(function(){
// Find the correct show format
switch( returnType ){
case "interactive":
res.render( 'graphs/' + graph.type(),{
plotId: job.id()
});
break;
case "data":
res.json( graph.json() );
break;
case "png":
graph.png( req.query, function( err, pngBuffer ){
if( err )
return next( err );
res.setHeader('Content-Type', 'image/png' );
res.send( pngBuffer );
});
break;
case "svg":
graph.svg( req.query, function( err, svgBuffer ){
if( err )
return next( err );
res.setHeader('Content-Type', 'image/svg+xml' );
res.send( svgBuffer );
});
break;
}
});
};
/**
* Will return a zip of the request graph type.
* This expects an array of the download formats needed
* Also expects the SVG posted used to generate the PNG
* and to return in the zip
*
* @return {Binary} The zip file
*/
graphController.download = function( req, res, expressNext ){
// Pre the graph related resources needed
var job = manager.getJob( req.param( 'id' ).input );
if( !job )
return res.send( 404, "Job not found" );
var graph = job._graph;
// Get formats the user wants to download
var formats = req.param( 'formats' );
if( ! ( formats instanceof Array ) )
next( new Error( 'No valid resources where requested.' ) );
// Get the built SVG, swap this out for server side recreation
var svg = req.param( 'svg' );
//Send the ZIP headers
res.setHeader('Content-Disposition', 'attachment; filename=package.zip' );
res.setHeader('Accept-Ranges', 'bytes' );
res.setHeader('Content-Type', 'application/zip, application/octet-stream' );
// Get a zip file ready
var archive = archiver( 'zip' );
archive.on( 'error', expressNext );
archive.pipe( res );
// Use lateral to run multiple things asynchronously
var lateral = Lateral.create(runResourceFunction, 5);
// Helper to allow the running/adding of single
// items at a time
lateral.push = function( item ){
this.add( [item] );
};
// Helper function for latteral that allows use
// to just que up functions for completion
function runResourceFunction( complete, item, i ){
item( complete, item, i );
}
// Place to store errors and return them
// in the zip later if they occur
var errorLog = [];
// Add the PNG if asked for
if( formats.indexOf( "png" ) > -1 ){
// Wrap function runnable by lateral
var addPng = function( complete, _, i ){
// Paramaters for the request
var pngParamaters = {
method: 'POST',
url: loopback + '/svg-to/png',
form: { svg: svg },
encoding: null // tells request to return a Buffer as body
};
// Callback to the add the png to the archive
var pngCallback = function( err, httpResponse, body ){
if( err ){
errorLog.push( "PNG failed to be created - " + err );
}else{
archive.append( body , { name: 'image-png.png' })
}
complete();
};
request( pngParamaters, pngCallback );
}
// Add the function to the lateral que
lateral.push( addPng );
};
// Add the SVG is asked for
if( formats.indexOf( "svg" ) > -1 ){
archive.append( svg , { name: 'image-svg.svg' })
}
// Pass everything else to the source handles
graph.sourceHandlers().forEach( getSourceHandlerResources );
function getSourceHandlerResources( sourceHandler ){
lateral.push(function( complete, _, i ){
// Request the source handler for the needed format
sourceHandler.addResourcesToArchive( formats, archive, complete );
});
}
/**
* Once all the files are downloaded save the error log
* to the zip and export the zip to the browser
*/
lateral.then(finish);
function finish(){
if( errorLog.length > 0 )
archive.append( errorLog.join("\n") , { name: 'errors.txt' })
archive.finalize();
}
};
|