refactored

This commit is contained in:
coderaiser 2013-02-05 09:46:50 -05:00
parent 74c3b30f2f
commit f2a893efb8
7 changed files with 205 additions and 209 deletions

View file

@ -15,7 +15,7 @@
Util = main.util,
update = main.update,
server = main.server,
server = main.librequire('server'),
Minify = main.minify,
Config = main.config,
@ -186,13 +186,13 @@
'-> auth');
pParams.name = main.HTMLDIR + lName + '.html';
lRet = server.sendFile(pParams);
lRet = main.sendFile(pParams);
}else if( Util.strCmp(lName, '/auth/github') ){
Util.log('* Routing' +
'-> github');
pParams.name = main.HTMLDIR + lName + '.html';
lRet = server.sendFile(pParams);
lRet = main.sendFile(pParams);
}else if( Util.isContainStr(lName, CloudFunc.FS) ||
Util.isContainStr(lName, CloudFunc.NO_JS ) ||
Util.strCmp(lName, '/') ||

View file

@ -2,7 +2,7 @@
"api_url" : "/api/v1",
"appcache" : false,
"minification" : {
"js" : false,
"js" : true,
"css" : true,
"html" : true,
"img" : true

View file

@ -31,15 +31,9 @@
Socket = main.socket,
http = main.http,
zlib = main.zlib,
fs = main.fs,
Util = main.util,
ext = main.ext,
Server, Rest, Route, Minimize, Port, IP,
OK = 200,
FILE_NOT_FOUND = 404;
Server, Rest, Route, Minimize, Port, IP;
/* базовая инициализация */
function init(pAppCachProcessing){
@ -111,7 +105,7 @@
}
}else
Util.log('Cloud Commander testing mode');
};
}
/**
@ -168,7 +162,7 @@
function(pParams){
var lSendName = pParams && pParams.name || lName;
sendFile({
main.sendFile({
name : lSendName,
request : pReq,
response : pRes
@ -183,99 +177,7 @@
}
}
/**
* Функция создаёт заголовки файлов
* в зависимости от расширения файла
* перед отправкой их клиенту
* @param pName - имя файла
* @param pGzip - данные сжаты gzip'ом
*/
function generateHeaders(pName, pGzip, pQuery){
var lRet,
lType = '',
lContentEncoding = '',
lCacheControl = 0,
lExt = Util.getExtension(pName);
if( Util.strCmp(lExt, '.appcache') )
lCacheControl = 1;
lType = ext[lExt] || 'text/plain';
if( !Util.isContainStr(lType, 'img') )
lContentEncoding = '; charset=UTF-8';
if(Util.strCmp(pQuery, 'download') )
lType = 'application/octet-stream';
if(!lCacheControl)
lCacheControl = 31337 * 21;
lRet = {
/* if type of file any, but img -
* then we shoud specify charset
*/
'Content-Type': lType + lContentEncoding,
'cache-control': 'max-age=' + lCacheControl,
'last-modified': new Date().toString(),
/* https://developers.google.com/speed/docs/best-practices
/caching?hl=ru#LeverageProxyCaching */
'Vary': 'Accept-Encoding'
};
if(pGzip)
lRet['content-encoding'] = 'gzip';
return lRet;
}
/**
* send file to client thru pipe
* and gzip it if client support
*
* @param pName - имя файла
* @param pGzip - данные сжаты gzip'ом
*/
function sendFile(pParams){
var lRet,
lName, lReq, lRes;
if(pParams){
lName = pParams.name,
lReq = pParams.request,
lRes = pParams.response;
}
if(lName && lRes && lReq){
var lEnc = lReq.headers['accept-encoding'] || '',
lGzip = lEnc.match(/\bgzip\b/),
lReadStream = fs.createReadStream(lName, {
'bufferSize': 4 * 1024
});
lReadStream.on('error', function(pError){
lRes.writeHead(FILE_NOT_FOUND, 'OK');
lRes.end(String(pError));
});
lRes.writeHead(OK, generateHeaders(lName, lGzip) );
if (lGzip)
lReadStream = lReadStream.pipe( zlib.createGzip() );
lReadStream.pipe(lRes);
lRet = true;
}
return lRet;
}
exports.generateHeaders = generateHeaders;
exports.sendFile = sendFile;
exports.start = start;
})();

View file

@ -12,17 +12,16 @@
var main = global.cloudcmd.main,
fs = main.fs,
zlib = main.zlib,
url = main.url,
querystring = main.querystring,
CloudFunc = main.cloudfunc,
DIR = main.DIR,
LIBDIR = main.LIBDIR,
HTMLDIR = main.HTMLDIR,
Util = main.util,
server = main.server,
url = main.url,
querystring = main.querystring,
zlib = main.zlib,
NOT_FOUND = 404,
FILE_NOT_FOUND = 404,
OK = 200,
FS = CloudFunc.FS,
@ -52,15 +51,15 @@
if(pStat.isDirectory())
fs.readdir(lPath, Util.call(readDir, pParams) );
else
server.sendFile({
main.sendFile({
name : lPath,
request : p.request,
response : p.response
});
else
sendResponse({
status : NOT_FOUND,
data : pError.toString(),
status : FILE_NOT_FOUND,
data : pError.toString(),
request : p.request,
response : p.response
});
@ -132,7 +131,7 @@
}
else
sendResponse({
status : NOT_FOUND,
status : FILE_NOT_FOUND,
data : lError.toString(),
request : lReq,
response: lRes
@ -294,15 +293,58 @@
Util.log('file ' + c.name + ' readed');
}
else{
lParams.status = NOT_FOUND;
lParams.status = FILE_NOT_FOUND;
lParams.data = p.error.toString();
}
sendResponse(lParams);
}
}
/**
* Функция высылает ответ серверу
* @param pHead - заголовок
* @param Data - данные
* @param pName - имя отсылаемого файла
*/
function sendResponse(pParams){
var lRet = Util.checkObjTrue(pParams,
['name', 'data', REQUEST, RESPONSE]);
if(lRet){
var p = pParams;
var lPath = p.name || getCleanPath(p.request),
lQuery = getQuery(p.request),
/* download, json */
lGzip = isGZIP(p.request),
lHead = main.generateHeaders(lPath, lGzip, lQuery);
/* если браузер поддерживает gzip-сжатие - сжимаем данные*/
Util.ifExec(!lGzip,
function(pParams){
var lRet = Util.checkObj(pParams, ['data']);
if(lRet){
p.status = pParams.status;
p.data = pParams.data;
}
p.response.writeHead(p.status || OK, lHead);
p.response.end(p.data);
Util.log(lPath + ' sended');
Util.log( p.status === FILE_NOT_FOUND && p.data );
},
function(pCallBack){
zlib.gzip (p.data, Util.call(gzipData, {
callback : pCallBack
}));
});
}
}
/**
/**
* Функция получает сжатые данные
* @param pHeader - заголовок файла
* @pName
@ -323,7 +365,7 @@
if(!p.error)
lParams.data = p.data;
else{
lParams.status = NOT_FOUND;
lParams.status = FILE_NOT_FOUND;
lParams.data = p.error.toString();
}
@ -384,48 +426,4 @@
return lGZIP;
}
/**
* Функция высылает ответ серверу
* @param pHead - заголовок
* @param Data - данные
* @param pName - имя отсылаемого файла
*/
function sendResponse(pParams){
var lRet = Util.checkObjTrue(pParams,
['name', 'data', REQUEST, RESPONSE]);
if(lRet){
var p = pParams;
var lPath = p.name || getCleanPath(p.request),
lQuery = getQuery(p.request),
/* download, json */
lGzip = isGZIP(p.request),
lHead = server.generateHeaders(lPath, lGzip, lQuery);
/* если браузер поддерживает gzip-сжатие - сжимаем данные*/
Util.ifExec(!lGzip,
function(pParams){
var lRet = Util.checkObj(pParams, ['data']);
if(lRet){
p.status = pParams.status;
p.data = pParams.data;
}
p.response.writeHead(p.status || OK, lHead);
p.response.end(p.data);
Util.log(lPath + ' sended');
Util.log( p.status === NOT_FOUND && p.data );
},
function(pCallBack){
zlib.gzip (p.data, Util.call(gzipData, {
callback : pCallBack
}));
});
}
}
})();

View file

@ -12,49 +12,56 @@
SLASH,
ISWIN32,
ext,
path,
fs,
zlib,
path;
OK = 200,
FILE_NOT_FOUND = 404;
/* Native Modules*/
exports.crypto = require('crypto'),
exports.child_process = require('child_process'),
exports.fs = require('fs'),
exports.http = require('http'),
exports.https = require('https'),
exports.path = path = require('path'),
exports.url = require('url'),
exports.querystring = require('querystring'),
exports.crypto = require('crypto'),
exports.child_process = require('child_process'),
exports.fs = fs = require('fs'),
exports.http = require('http'),
exports.https = require('https'),
exports.path = path = require('path'),
exports.url = require('url'),
exports.querystring = require('querystring'),
/* Constants */
/* current dir + 2 levels up */
exports.WIN32 = ISWIN32 = isWin32();
exports.SLASH = SLASH = ISWIN32 ? '\\' : '/',
exports.WIN32 = ISWIN32 = isWin32();
exports.SLASH = SLASH = ISWIN32 ? '\\' : '/',
exports.SRVDIR = SRVDIR = __dirname + SLASH,
exports.LIBDIR = LIBDIR = path.normalize(SRVDIR + '../'),
exports.DIR = DIR = path.normalize(LIBDIR + '../'),
exports.HTMLDIR = DIR + 'html/',
exports.JSONDIR = JSONDIR = DIR + 'json/',
exports.SRVDIR = SRVDIR = __dirname + SLASH,
exports.LIBDIR = LIBDIR = path.normalize(SRVDIR + '../'),
exports.DIR = DIR = path.normalize(LIBDIR + '../'),
exports.HTMLDIR = DIR + 'html/',
exports.JSONDIR = JSONDIR = DIR + 'json/',
/* Functions */
exports.require = mrequire,
exports.librequire = librequire,
exports.srvrequire = srvrequire,
exports.rootrequire = rootrequire,
exports.require = mrequire,
exports.librequire = librequire,
exports.srvrequire = srvrequire,
exports.rootrequire = rootrequire,
exports.generateHeaders = generateHeaders,
exports.sendFile = sendFile,
/* compitability with old versions of node */
exports.fs.exists = exports.fs.exists || exports.path.exists;
exports.fs.exists = exports.fs.exists || exports.path.exists;
/* Needed Modules */
exports.util = Util = require(LIBDIR + 'util'),
exports.util = Util = require(LIBDIR + 'util'),
exports.zlib = mrequire('zlib'),
exports.zlib = zlib = mrequire('zlib'),
/* Main Information */
exports.config = jsonrequire('config');
exports.modules = jsonrequire('modules');
exports.ext = jsonrequire('ext');
exports.mainpackage = rootrequire('package');
exports.config = jsonrequire('config');
exports.modules = jsonrequire('modules');
exports.ext = ext = jsonrequire('ext');
exports.mainpackage = rootrequire('package');
/*
@ -63,22 +70,21 @@
* moudles do not depends on each other all needed information
* for all modules is initialized hear.
*/
global.cloudcmd.main = exports;
global.cloudcmd.main = exports;
exports.VOLUMES = getVolumes(),
exports.VOLUMES = getVolumes(),
/* Additional Modules */
exports.minify = srvrequire('minify').Minify;
exports.socket = srvrequire('socket'),
exports.server = librequire('server'),
exports.auth = srvrequire('auth').auth,
exports.appcache = srvrequire('appcache'),
exports.cache = srvrequire('cache').Cache,
exports.cloudfunc = librequire('cloudfunc'),
exports.rest = srvrequire('rest').api,
exports.update = srvrequire('update'),
exports.ischanged = srvrequire('ischanged');
exports.commander = srvrequire('commander');
exports.socket = srvrequire('socket'),
exports.auth = srvrequire('auth').auth,
exports.appcache = srvrequire('appcache'),
exports.cache = srvrequire('cache').Cache,
exports.cloudfunc = librequire('cloudfunc'),
exports.rest = srvrequire('rest').api,
exports.update = srvrequire('update'),
exports.ischanged = srvrequire('ischanged');
exports.commander = srvrequire('commander');
exports.minify = srvrequire('minify').Minify;
/*
* second initializing after all modules load, so global var is
* totally filled of all information that should know all modules
@ -113,7 +119,6 @@
*/
function isWin32(){ return process.platform === 'win32'; }
/**
* get volumes if win32 or get nothing if nix
*/
@ -128,4 +133,97 @@
return lRet;
}
/**
* Функция создаёт заголовки файлов
* в зависимости от расширения файла
* перед отправкой их клиенту
* @param pName - имя файла
* @param pGzip - данные сжаты gzip'ом
*/
function generateHeaders(pName, pGzip, pQuery){
var lRet,
lType = '',
lContentEncoding = '',
lCacheControl = 0,
lExt = Util.getExtension(pName);
if( Util.strCmp(lExt, '.appcache') )
lCacheControl = 1;
lType = ext[lExt] || 'text/plain';
if( !Util.isContainStr(lType, 'img') )
lContentEncoding = '; charset=UTF-8';
if(Util.strCmp(pQuery, 'download') )
lType = 'application/octet-stream';
if(!lCacheControl)
lCacheControl = 31337 * 21;
lRet = {
/* if type of file any, but img -
* then we shoud specify charset
*/
'Content-Type': lType + lContentEncoding,
'cache-control': 'max-age=' + lCacheControl,
'last-modified': new Date().toString(),
/* https://developers.google.com/speed/docs/best-practices
/caching?hl=ru#LeverageProxyCaching */
'Vary': 'Accept-Encoding'
};
if(pGzip)
lRet['content-encoding'] = 'gzip';
return lRet;
}
/**
* send file to client thru pipe
* and gzip it if client support
*
* @param pName - имя файла
* @param pGzip - данные сжаты gzip'ом
*/
function sendFile(pParams){
var lRet,
lName, lReq, lRes;
if(pParams){
lName = pParams.name,
lReq = pParams.request,
lRes = pParams.response;
}
if(lName && lRes && lReq){
var lEnc = lReq.headers['accept-encoding'] || '',
lGzip = lEnc.match(/\bgzip\b/),
lReadStream = fs.createReadStream(lName, {
'bufferSize': 4 * 1024
});
lReadStream.on('error', function(pError){
lRes.writeHead(FILE_NOT_FOUND, 'OK');
lRes.end(String(pError));
});
lRes.writeHead(OK, generateHeaders(lName, lGzip) );
if (lGzip)
lReadStream = lReadStream.pipe( zlib.createGzip() );
lReadStream.pipe(lRes);
lRet = true;
}
return lRet;
}
})();

View file

@ -19,8 +19,7 @@
LIBDIR = main.LIBDIR,
HTMLDIR = main.HTMLDIR,
Util = main.util,
Minify = main.minify,
server = main.server,
Minify = main.require('minify'),
IsChanged = main.ischanged,
COULD_NOT_MINIFY = 'Could not minify without minify module\n' +
@ -73,7 +72,7 @@
if(pChanged)
Minify.optimize(pName, pParams);
else
server.sendFile(pParams);
main.sendFile(pParams);
});
}
else{

View file

@ -16,10 +16,9 @@
var main = global.cloudcmd.main,
Util = main.util,
Config = main.config,
server = main.server,
APIURL = Config.api_url,
OK = 200,
Header = server.generateHeaders('api.json', false);
Header = main.generateHeaders('api.json', false);
/**
* rest interface
@ -154,7 +153,7 @@
if( Util.isString(lFiles) ){
pParams.name = lFiles;
server.sendFile(pParams);
main.sendFile(pParams);
lResult = null;
}