cloudRequire renamed to require and moved to module srvfunc.js

This commit is contained in:
coderaiser 2012-10-29 06:12:59 -04:00
parent a4f71aca2b
commit d0ce7b27f5
7 changed files with 136 additions and 186 deletions

View file

@ -1,12 +1,15 @@
"use strict";
var LIBDIRSERVER = './lib/server/',
Server = cloudRequire('./server'),
path = cloudRequire('path'),
fs = cloudRequire('fs'),
update = cloudRequire(LIBDIRSERVER + 'update');
var Config = readConfig();
var DIR = process.cwd() + '/',
SRVDIR = DIR + 'lib/server/',
srvfunc = require(SRVDIR + 'srvfunc'),
path = require('path'),
fs = require('fs'),
Server = srvfunc.require(DIR + 'server'),
update = srvfunc.require(SRVDIR + 'update'),
Config = readConfig();
Server.start(Config);
@ -32,7 +35,7 @@ function readConfig(){
console.log('server dir: ' + lServerDir);
console.log('reading configuretion file config.json...');
var lConfig = cloudRequire('./config');
var lConfig = srvfunc.require(DIR + 'config');
if(lConfig){
console.log('config.json readed');
@ -68,16 +71,3 @@ function writeLogsToFile(){
};
})(process.stdout.write);
}
/**
* function do safe require of needed module
* @param pModule
*/
function cloudRequire(pModule){
try{
return require(pModule);
}
catch(pError){
return false;
}
}

View file

@ -1,19 +1,22 @@
var fs = require('fs');
var fs = require('fs'),
DIR = process.cwd(),
SRVDIR = DIR + '/lib/server/',
srvfunc = require(SRVDIR + 'srvfunc'),
/* varible contain all watched file names
* {name: true}
*/
var FileNames = {},
FileNames = {},
NamesList_s = '',
FallBack_s = '';
FallBack_s = '',
/* function thet use for crossplatform
* access to fs.watch or fs.watchFile function
*/
var fs_watch = null;
var on_fs_watch = null;
var firstFileRead_b = true;
var Manifest = '';
fs_watch = null,
on_fs_watch = null,
firstFileRead_b = true,
Manifest = '';
setWatachFunctions();
@ -43,7 +46,7 @@ exports.addFiles = function(pFileNames){
exports.createManifest = function(){
var lAllNames = cloudRequire(process.cwd() + '/hashes');
var lAllNames = srvfunc(DIR + '/hashes');
if(lAllNames)
for(var lName in lAllNames){
if(lName.indexOf('min') > 0)
@ -62,9 +65,12 @@ exports.watch = function(pFileName){
/* adding try...catch
* if watched files would be more then system limit
*/
var lWatch_f = tryCatch(function(){
var lWatch_f = function(){
srvfunc.tryCatch(function(){
fs_watch(pFileName, on_fs_watch(pFileName));
});
};
/* if file.exists function exist and
* file actually exists
*/
@ -125,32 +131,4 @@ function processManifest(){
fs.writeFile('cloudcmd.appcache', Manifest, function(){
console.log('cloudcmd.appcache refreshed');
});
}
/* function do safe require of needed module */
function cloudRequire(pModule){
try{
return require(pModule);
}
catch(pError){
return false;
}
}
/**
* function execute param function in
* try...catch block
*
* @param pFunction_f
*/
function tryCatch(pFunction_f){
return function(){
var lRet = true;
try{
pFunction_f();
}
catch(pError){lRet = pError;}
return lRet;
};
}

View file

@ -1,84 +1,57 @@
/* https://github.com/prose/gatekeeper */
var https = require('https'),
fs = require('fs'),
qs = require('querystring'),
Config;
exports.auth = function(pCode, pCallBack){
fs.readFile(process.cwd() + 'tokens.json', function(pErr, pData){
pCode = pCode.replace('code=','');
DIR = process.cwd(),
SRVDIR = DIR + '/lib/server/',
srvfunc = require(SRVDIR + 'srvfunc'),
Config = srvfunc.require(DIR + '/auth'),
GithubAuth = {
host: "github.com",
port: 443,
path: "/login/oauth/access_token",
method: "POST"
};
console.log('d');
var TokensFile = {};
if(!pErr && pData){
TokensFile = JSON.parse(pData);
}
if( !TokensFile[pCode] )
readConfig(pCode, pCallBack);
else
pCallBack();
exports.auth = function(pCode, pCallBack){
pCode = pCode.replace('code=','');
console.log(pCode);
authenticate(pCode, function(token) {
var result = { "token": token };
console.log(result);
pCallBack();
srvfunc.exec(pCallBack);
});
};
function readConfig(pCode, pCallBack){
Config = require(process.cwd() + '/auth');
for (var i in Config)
Config[i] = process.env[i.toUpperCase()] || Config[i];
console.log('Configuration');
console.log(Config);
authenticate(pCode, function(err, token) {
var result = { "token": token };
fs.createWriteStream('tokens.json',{'flags': 'a'})
.end('{' + pCode + ':' + token + '}\n');
console.log(result);
console.log(err);
});
if(typeof pCallBack === 'function')
pCallBack();
}
/* Load config defaults from JSON file.
* Environment variables override defaults.
/**
* function do authentication
* @param pCode
* @param pCallBack
*/
function authenticate(pCode, cb) {
function authenticate(pCode, pCallBack) {
var data = qs.stringify({
client_id : Config.oauth_client_id,
client_secret : Config.oauth_client_secret,
code : pCode
});
var reqOptions = {
host: "github.com",
port: 443,
path: "/login/oauth/access_token",
method: "POST",
headers : { 'content-length': data.length }
};
var body = "";
var req = https.request(reqOptions, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) { body += chunk; });
res.on('end', function() {
cb(null, qs.parse(body).access_token);
GithubAuth.headers = { 'content-length': data.length };
var body = "",
req = https.request(GithubAuth, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) { body += chunk; });
res.on('end', function() {
pCallBack(qs.parse(body).access_token);
});
});
});
req.write(data);
req.end();
req.on('error', function(e) { cb(e.message); });
req.on('error', function(e) { pCallBack(e.message); });
}

View file

@ -5,6 +5,11 @@
* - Minify
*/
var DIR = process.cwd(),
SRVDIR = DIR + '/lib/server/',
srvfunc = require(SRVDIR + '/srvfunc');
/*
* Обьект для работы с кэшем
* аналог клиентского обьекта
@ -159,7 +164,7 @@ exports.Minify = {
if(this._allowed.css ||
this._allowed.js ||
this._allowed.html){
var lMinify = cloudRequire('minify');
var lMinify = srvfunc.require('minify');
if(lMinify)
lMinify.optimize(pName, pParams);
@ -180,24 +185,4 @@ exports.Minify = {
/* minification folder name */
MinFolder : '',
Cache : {}
};
/* Обьект проверяет изменился ли файл */
exports.IsFileChanged = function(pFileName, pData, pOverWrite_b){
var lCheck = cloudRequire('is-file-changed');
if(lCheck){
return lCheck.IsFileChanged(pFileName, pData, pOverWrite_b);
}else
return true;
};
/* function do safe require of needed module */
function cloudRequire(pModule){
try{
return require(pModule);
}
catch(pError){
return false;
}
}
};

View file

@ -1,9 +1,14 @@
/* module make possible connectoin thrue socket.io on a server */
var LIBDIRSERVER = './lib/server/',
io = require('socket.io'),
var DIR = process.cwd(),
SRVDIR = DIR + '/lib/server/',
srvfunc = require(SRVDIR + '/srvfunc'),
io = srvfunc.require('socket.io'),
exec = require('child_process').exec,
update = cloudRequire(LIBDIRSERVER + 'update'),
update = srvfunc.require(SRVDIR + 'update'),
ClientFuncs = [],
OnMessageFuncs = [],
Win32_b = process.platform === 'win32';
@ -129,17 +134,4 @@ var Win32Commands = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
'VER', 'VERIFY', 'VOL', 'XCOPY'];
/**
* function do safe require of needed module
* @param pModule
*/
function cloudRequire(pModule){
try{
return require(pModule);
}
catch(pError){
return false;
}
}
'VER', 'VERIFY', 'VOL', 'XCOPY'];

42
lib/server/srvfunc.js Normal file
View file

@ -0,0 +1,42 @@
"strict mode";
/**
* function do save exec
*/
exports.exec = function(pCallBackk){
if( typeof pCallBackk === 'function')
pCallBackk();
else console.log('error in ' + pCallBackk);
};
/**
* function do safe require of needed module
* @param pModule
*/
exports.require = function(pSrc){
var lModule,
lError = exports.tryCatch(function(){
lModule = require(pSrc);
});
if(lError)
console.log(lError);
return lModule;
};
/**
* function execute param function in
* try...catch block
*
* @param pCallBack
*/
exports.tryCatch = function(pCallBack){
var lRet;
try{
pCallBack();
}
catch(pError){lRet = pError;}
return lRet;
};

View file

@ -80,7 +80,7 @@ var CloudServer = {
/* КОНСТАНТЫ */
INDEX : 'index.html',
LIBDIR : './lib/',
LIBDIRSERVER : './lib/server/',
SRVDIR : './lib/server/',
Extensions :{
'.css' : 'text/css',
'.js' : 'text/javascript',
@ -95,27 +95,30 @@ var CloudServer = {
DirPath = '/',
DIR = process.cwd() + '/',
LIBDIR = DIR + 'lib/',
SRVDIR = LIBDIR + 'server/',
/* модуль для работы с путями*/
Path = cloudRequire('path'),
Fs = cloudRequire('fs'), /* модуль для работы с файловой системой*/
Querystring = cloudRequire('querystring'),
Path = require('path'),
Fs = require('fs'), /* модуль для работы с файловой системой*/
Querystring = require('querystring'),
srvfunc = require(SRVDIR + 'srvfunc'),
/* node v0.4 not contains zlib */
Zlib = cloudRequire('zlib'); /* модуль для сжатия данных gzip-ом*/
Zlib = srvfunc.require('zlib'); /* модуль для сжатия данных gzip-ом*/
if(!Zlib)
console.log('to use gzip-commpression' +
'you should use newer node version\n');
/* добавляем модуль с функциями */
var CloudFunc = cloudRequire(CloudServer.LIBDIR +
'cloudfunc');
CloudServer.AppCache = cloudRequire(CloudServer.LIBDIRSERVER +
'appcache');
CloudServer.Socket = cloudRequire(CloudServer.LIBDIRSERVER +
'socket');
var CloudFunc = srvfunc.require(LIBDIR + 'cloudfunc');
CloudServer.AppCache = srvfunc.require(SRVDIR + 'appcache');
CloudServer.Socket = srvfunc.require(SRVDIR + 'socket');
CloudServer.Obj = cloudRequire(CloudServer.LIBDIRSERVER +
'object');
CloudServer.Obj = srvfunc.require(SRVDIR + 'object');
if(CloudServer.Obj){
CloudServer.Cache = CloudServer.Obj.Cache;
CloudServer.Minify = CloudServer.Obj.Minify;
@ -457,7 +460,7 @@ CloudServer._controller = function(pReq, pRes)
/* читаем основные данные о файле */
if( lQuery && lQuery.indexOf('code=') === 0){
var lAuth = cloudRequire(CloudServer.LIBDIRSERVER + 'auth');
var lAuth = srvfunc.require(SRVDIR + 'auth');
if(lAuth) lAuth.auth(lQuery, function(){
Fs.stat(DirPath, CloudServer._stated);
@ -838,19 +841,6 @@ CloudServer.sendResponse = function(pHead, pData, pName){
}
};
/**
* function do safe require of needed module
* @param pModule
*/
function cloudRequire(pModule){
try{
return require(pModule);
}
catch(pError){
return false;
}
}
exports.start = function(pConfig){
CloudServer.start(pConfig);
};