mirror of
https://github.com/alibaba/anyproxy.git
synced 2025-04-24 07:01:25 +00:00
optimize webServer, move it to /lib
This commit is contained in:
parent
db4ab7d2f9
commit
8e7aef70ae
@ -106,21 +106,22 @@ function Recorder(option){
|
||||
|
||||
if(!bodyContent){
|
||||
cb(null,result);
|
||||
}else{
|
||||
var record = doc[0],
|
||||
resHeader = record['resHeader'] || {};
|
||||
try{
|
||||
var charsetMatch = JSON.stringify(resHeader).match(/charset="?([a-zA-Z0-9\-]+)"?/);
|
||||
if(charsetMatch && charsetMatch.length > 1){
|
||||
var currentCharset = charsetMatch[1].toLowerCase();
|
||||
if(currentCharset != "utf-8" && iconv.encodingExists(currentCharset)){
|
||||
bodyContent = iconv.decode(bodyContent, currentCharset);
|
||||
}
|
||||
}
|
||||
}catch(e){}
|
||||
|
||||
cb(null,bodyContent.toString());
|
||||
}
|
||||
|
||||
var record = doc[0],
|
||||
resHeader = record['resHeader'] || {};
|
||||
try{
|
||||
var charsetMatch = JSON.stringify(resHeader).match(/charset="?([a-zA-Z0-9\-]+)"?/);
|
||||
if(charsetMatch && charsetMatch.length > 1){
|
||||
var currentCharset = charsetMatch[1].toLowerCase();
|
||||
if(currentCharset != "utf-8" && iconv.encodingExists(currentCharset)){
|
||||
bodyContent = iconv.decode(bodyContent, currentCharset);
|
||||
}
|
||||
}
|
||||
}catch(e){}
|
||||
|
||||
cb(null,bodyContent.toString());
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -61,17 +61,6 @@ module.exports = {
|
||||
//fetch entire traffic data
|
||||
fetchTrafficData: function(id,info){},
|
||||
|
||||
//[internal]
|
||||
customMenu:[
|
||||
{
|
||||
name :"test",
|
||||
handler :function(){}
|
||||
},{
|
||||
name :"second-test",
|
||||
handler :function(){}
|
||||
}
|
||||
],
|
||||
|
||||
setInterceptFlag:function(flag){
|
||||
interceptFlag = flag && isRootCAFileExists;
|
||||
}
|
||||
|
@ -1,26 +1,27 @@
|
||||
// var process = require("child_process")
|
||||
var express = require("express"),
|
||||
url = require('url'),
|
||||
fs = require("fs"),
|
||||
util = require("./lib/util"),
|
||||
certMgr = require("./lib/certMgr"),
|
||||
path = require("path"),
|
||||
events = require("events"),
|
||||
inherits = require("util").inherits,
|
||||
ent = require("ent"),
|
||||
qrCode = require('qrcode-npm'),
|
||||
logUtil = require("./lib/log");
|
||||
util = require("./util"),
|
||||
certMgr = require("./certMgr"),
|
||||
logUtil = require("./log");
|
||||
|
||||
function proxyWebServer(port,webSocketPort,proxyConfigPort,ruleSummary,ipAddress,menuListStr){
|
||||
|
||||
function webInterface(config){
|
||||
var port = config.port,
|
||||
wsPort = config.wsPort,
|
||||
ruleSummary = config.ruleSummary,
|
||||
ipAddress = config.ip;
|
||||
|
||||
var self = this,
|
||||
myAbsAddress = "http://" + ipAddress + ":" + port +"/",
|
||||
crtFilePath = certMgr.getRootCAFilePath();
|
||||
crtFilePath = certMgr.getRootCAFilePath(),
|
||||
staticDir = path.join(__dirname,'../web');
|
||||
|
||||
if(arguments.length < 3){
|
||||
throw new Error("please assign ports");
|
||||
}
|
||||
|
||||
//web interface
|
||||
var app = express();
|
||||
app.use(function(req, res, next) {
|
||||
res.setHeader("note", "THIS IS A REQUEST FROM ANYPROXY WEB INTERFACE");
|
||||
@ -79,46 +80,28 @@ function proxyWebServer(port,webSocketPort,proxyConfigPort,ruleSummary,ipAddress
|
||||
res.end(resDom);
|
||||
});
|
||||
|
||||
app.use(function(req,res,next){
|
||||
var indexHTML = fs.readFileSync(__dirname + "/web/index.html",{encoding:"utf8"});
|
||||
var indexTpl = fs.readFileSync(path.join(staticDir,"/index.html"),{encoding:"utf8"}),
|
||||
indexHTML = util.simpleRender(indexTpl, {
|
||||
rule : ruleSummary || "",
|
||||
wsPort : wsPort,
|
||||
ipAddress : ipAddress || "127.0.0.1"
|
||||
});
|
||||
|
||||
app.use(function(req,res,next){
|
||||
if(req.url == "/"){
|
||||
res.setHeader("Content-Type", "text/html");
|
||||
res.end(util.simpleRender(indexHTML, {
|
||||
rule : ruleSummary || "",
|
||||
webSocketPort : webSocketPort,
|
||||
proxyConfigPort : proxyConfigPort,
|
||||
ipAddress : ipAddress || "127.0.0.1",
|
||||
menu : menuListStr
|
||||
}));
|
||||
res.end(indexHTML);
|
||||
}else{
|
||||
next();
|
||||
}
|
||||
});
|
||||
|
||||
app.use(express.static(__dirname + '/web'));
|
||||
app.use(express.static(staticDir));
|
||||
app.listen(port);
|
||||
|
||||
self.app = app;
|
||||
}
|
||||
|
||||
inherits(proxyWebServer, events.EventEmitter);
|
||||
inherits(webInterface, events.EventEmitter);
|
||||
|
||||
var param = process.argv.slice(2),
|
||||
server = new proxyWebServer(param[0],param[1],param[2],param[3],param[4],param[5]),
|
||||
cbMap = {}, // id body cb
|
||||
lastestHeartbeat = new Date().getTime();
|
||||
|
||||
|
||||
//watch dog
|
||||
process.on("message",function(data){
|
||||
if(data.type == "watch"){
|
||||
lastestHeartbeat = new Date().getTime();
|
||||
}
|
||||
});
|
||||
|
||||
setInterval(function(){
|
||||
if(new Date().getTime() - lastestHeartbeat > 10 * 1000){
|
||||
process.exit();
|
||||
}
|
||||
},7000);
|
||||
module.exports = webInterface;
|
88
lib/wsServer.js
Normal file
88
lib/wsServer.js
Normal file
@ -0,0 +1,88 @@
|
||||
//websocket server manager
|
||||
|
||||
var WebSocketServer = require('ws').Server,
|
||||
logUtil = require("./log");
|
||||
|
||||
function resToMsg(msg,cb){
|
||||
var result = {},
|
||||
jsonData;
|
||||
|
||||
try{
|
||||
jsonData = JSON.parse(msg);
|
||||
}catch(e){
|
||||
result = {
|
||||
type : "error",
|
||||
error: "failed to parse your request : " + e.toString()
|
||||
};
|
||||
cb && cb(result);
|
||||
return;
|
||||
}
|
||||
|
||||
if(jsonData.reqRef){
|
||||
result.reqRef = jsonData.reqRef;
|
||||
}
|
||||
|
||||
if(jsonData.type == "reqBody" && jsonData.id){
|
||||
GLOBAL.recorder.getBodyUTF8(jsonData.id, function(err, data){
|
||||
if(err){
|
||||
result = {
|
||||
type : "body",
|
||||
content : {
|
||||
id : null,
|
||||
body : null,
|
||||
error : err.toString()
|
||||
}
|
||||
};
|
||||
}else{
|
||||
result = {
|
||||
type : "body",
|
||||
content : {
|
||||
id : jsonData.id,
|
||||
body : data
|
||||
}
|
||||
};
|
||||
}
|
||||
cb && cb(result);
|
||||
});
|
||||
}else{ // more req handler here
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//config.port
|
||||
function wsServer(config){
|
||||
//web socket interface
|
||||
var wss = new WebSocketServer({port: config.port});
|
||||
wss.broadcast = function(data) {
|
||||
if(typeof data == "object"){
|
||||
data = JSON.stringify(data);
|
||||
}
|
||||
|
||||
for(var i in this.clients){
|
||||
try{
|
||||
this.clients[i].send(data);
|
||||
}catch(e){
|
||||
logUtil.printLog("websocket failed to send data, " + e, logUtil.T_ERR);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
wss.on("connection",function(ws){
|
||||
ws.on("message",function(msg){
|
||||
resToMsg(msg,function(res){
|
||||
res && ws.send(JSON.stringify(res));
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
GLOBAL.recorder.on("update",function(data){
|
||||
wss && wss.broadcast({
|
||||
type : "update",
|
||||
content: data
|
||||
});
|
||||
});
|
||||
|
||||
return wss;
|
||||
}
|
||||
|
||||
module.exports = wsServer;
|
@ -11,7 +11,6 @@
|
||||
"async-task-mgr": ">=1.1.0",
|
||||
"colorful": "^2.1.0",
|
||||
"commander": "~2.3.0",
|
||||
"ent": "^2.2.0",
|
||||
"express": "^4.8.5",
|
||||
"iconv-lite": "^0.4.6",
|
||||
"ip": "^0.3.2",
|
||||
|
216
proxy.js
216
proxy.js
@ -14,6 +14,8 @@ var http = require('http'),
|
||||
requestHandler = require("./lib/requestHandler"),
|
||||
Recorder = require("./lib/recorder"),
|
||||
logUtil = require("./lib/log"),
|
||||
wsServer = require("./lib/wsServer"),
|
||||
webInterface = require("./lib/webInterface"),
|
||||
inherits = require("util").inherits,
|
||||
util = require("./lib/util"),
|
||||
path = require("path"),
|
||||
@ -21,11 +23,10 @@ var http = require('http'),
|
||||
events = require("events"),
|
||||
express = require("express"),
|
||||
ip = require("ip"),
|
||||
fork = require("child_process").fork,
|
||||
ent = require("ent"),
|
||||
ThrottleGroup = require("stream-throttle").ThrottleGroup,
|
||||
iconv = require('iconv-lite'),
|
||||
Buffer = require('buffer').Buffer,
|
||||
WebSocketServer = require('ws').Server;
|
||||
Buffer = require('buffer').Buffer;
|
||||
|
||||
|
||||
var T_TYPE_HTTP = 0,
|
||||
@ -84,8 +85,7 @@ function proxyServer(option){
|
||||
proxyConfigPort = option.webConfigPort || DEFAULT_CONFIG_PORT, //port to ui config server
|
||||
disableWebInterface = !!option.disableWebInterface,
|
||||
ifSilent = !!option.silent,
|
||||
wss,
|
||||
child_webServer;
|
||||
webServerInstance;
|
||||
|
||||
if(ifSilent){
|
||||
logUtil.setPrintStatus(false);
|
||||
@ -125,119 +125,43 @@ function proxyServer(option){
|
||||
callback(null);
|
||||
}
|
||||
});
|
||||
|
||||
}else{
|
||||
self.httpProxyServer = http.createServer(requestHandler.userRequestHandler);
|
||||
callback(null);
|
||||
}
|
||||
},
|
||||
|
||||
//handle CONNECT request for https over http
|
||||
function(callback){
|
||||
//listen CONNECT request for https over http
|
||||
self.httpProxyServer.on('connect',requestHandler.connectReqHandler);
|
||||
callback(null);
|
||||
},
|
||||
|
||||
//start proxy server
|
||||
//start proxy server
|
||||
function(callback){
|
||||
self.httpProxyServer.listen(proxyPort);
|
||||
callback(null);
|
||||
},
|
||||
|
||||
//start web socket service
|
||||
function(callback){
|
||||
var ws = new wsServer({port : socketPort});
|
||||
callback(null)
|
||||
},
|
||||
|
||||
//start web interface
|
||||
function(callback){
|
||||
if(disableWebInterface){
|
||||
logUtil.printLog('web interface is disabled');
|
||||
}else{
|
||||
//[beta] customMenu
|
||||
var customMenuConfig = proxyRules.customMenu,
|
||||
menuList = [],
|
||||
menuListStr;
|
||||
|
||||
if(customMenuConfig && customMenuConfig.length){
|
||||
for(var i = 0 ; i < customMenuConfig.length ; i++){
|
||||
menuList.push(customMenuConfig[i].name);
|
||||
}
|
||||
}
|
||||
menuListStr = menuList.join("@@@");
|
||||
|
||||
//web interface
|
||||
var args = [proxyWebPort, socketPort, proxyConfigPort, requestHandler.getRuleSummary(), ip.address(),menuListStr];
|
||||
child_webServer = fork(path.join(__dirname,"./webServer.js"),args);
|
||||
|
||||
//deal websocket data
|
||||
var wsDataDealer = function(){};
|
||||
inherits(wsDataDealer,events.EventEmitter);
|
||||
var dealer = new wsDataDealer();
|
||||
|
||||
GLOBAL.recorder.on("update",function(data){
|
||||
wss && wss.broadcast({
|
||||
type : "update",
|
||||
content: data
|
||||
});
|
||||
});
|
||||
|
||||
dealer.on("message",function(ws,jsonData){
|
||||
if(jsonData.type == "reqBody" && jsonData.id){
|
||||
GLOBAL.recorder.getBodyUTF8(jsonData.id, function(err, data){
|
||||
var result = {};
|
||||
|
||||
if(err){
|
||||
result = {
|
||||
type : "body",
|
||||
id : null,
|
||||
body : null,
|
||||
error: err.toString()
|
||||
};
|
||||
}else{
|
||||
result = {
|
||||
type : "body",
|
||||
id : data.id,
|
||||
body : data
|
||||
};
|
||||
}
|
||||
ws.send(JSON.stringify(result));
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
dealer.on("message",function(ws,jsonData){
|
||||
// another dealer here...
|
||||
});
|
||||
|
||||
//web socket interface
|
||||
wss = new WebSocketServer({port: socketPort});
|
||||
wss.on("connection",function(ws){
|
||||
ws.on("message",function(msg){
|
||||
try{
|
||||
var msgObj = JSON.parse(msg);
|
||||
dealer && dealer.emit("message",ws,msgObj);
|
||||
}catch(e){
|
||||
var result = {
|
||||
type : "error",
|
||||
error: "failed to parse your request : " + e.toString()
|
||||
};
|
||||
ws.send(JSON.stringify(result));
|
||||
}
|
||||
});
|
||||
});
|
||||
wss.broadcast = function(data) {
|
||||
if(typeof data == "object"){
|
||||
data = JSON.stringify(data);
|
||||
}
|
||||
|
||||
for(var i in this.clients){
|
||||
try{
|
||||
this.clients[i].send(data);
|
||||
}catch(e){
|
||||
logUtil.printLog("websocket failed to send data, " + e, logUtil.T_ERR);
|
||||
}
|
||||
}
|
||||
var config = {
|
||||
port : proxyWebPort,
|
||||
wsPort : socketPort,
|
||||
ruleSummaery : requestHandler.getRuleSummary(),
|
||||
ip : ip.address()
|
||||
};
|
||||
|
||||
//watch dog
|
||||
setInterval(function(argument) {
|
||||
child_webServer.send({
|
||||
type:"watch"
|
||||
});
|
||||
},5000);
|
||||
webServerInstance = new webInterface(config);
|
||||
}
|
||||
callback(null);
|
||||
},
|
||||
@ -247,24 +171,15 @@ function proxyServer(option){
|
||||
|
||||
//kill web server when father process exits
|
||||
process.on("exit",function(code){
|
||||
child_webServer.kill();
|
||||
logUtil.printLog('AnyProxy is about to exit with code: ' + code, logUtil.T_ERR);
|
||||
process.exit();
|
||||
});
|
||||
|
||||
process.on("uncaughtException",function(err){
|
||||
child_webServer.kill();
|
||||
logUtil.printLog('Caught exception: ' + err, logUtil.T_ERR);
|
||||
process.exit();
|
||||
});
|
||||
|
||||
var tipText,webUrl;
|
||||
webUrl = "http://" + ip.address() + ":" + proxyWebPort +"/";
|
||||
tipText = "GUI interface started at : " + webUrl;
|
||||
logUtil.printLog(color.green(tipText));
|
||||
|
||||
// tipText = "[alpha]qr code to for iOS client: " + webUrl + "qr";
|
||||
// logUtil.printLog(color.green(tipText));
|
||||
callback(null);
|
||||
}
|
||||
],
|
||||
@ -272,6 +187,11 @@ function proxyServer(option){
|
||||
//final callback
|
||||
function(err,result){
|
||||
if(!err){
|
||||
var webTip,webUrl;
|
||||
webUrl = "http://" + ip.address() + ":" + proxyWebPort +"/";
|
||||
webTip = "GUI interface started at : " + webUrl;
|
||||
logUtil.printLog(color.green(webTip));
|
||||
|
||||
var tipText = (proxyType == T_TYPE_HTTP ? "Http" : "Https") + " proxy started at " + color.bold(ip.address() + ":" + proxyPort);
|
||||
logUtil.printLog(color.green(tipText));
|
||||
}else{
|
||||
@ -288,88 +208,6 @@ function proxyServer(option){
|
||||
}
|
||||
}
|
||||
|
||||
// BETA : UIConfigServer
|
||||
function UIConfigServer(port){
|
||||
var self = this;
|
||||
|
||||
var app = express(),
|
||||
customerRule = {
|
||||
summary: function(){
|
||||
logUtil.printLog("replace some response with local response");
|
||||
return "replace some response with local response";
|
||||
}
|
||||
},
|
||||
userKey;
|
||||
|
||||
port = port || DEFAULT_CONFIG_PORT;
|
||||
|
||||
customerRule.shouldUseLocalResponse = function(req,reqBody){
|
||||
var url = req.url;
|
||||
if(userKey){
|
||||
var ifMatch = false;
|
||||
userKey.map(function(item){
|
||||
if(ifMatch) return;
|
||||
|
||||
var matchCount = 0;
|
||||
if( !item.urlKey && !item.reqBodyKey){
|
||||
ifMatch = false;
|
||||
return;
|
||||
}else{
|
||||
if(!item.urlKey || (item.urlKey && url.indexOf(item.urlKey) >= 0 ) ){
|
||||
++matchCount;
|
||||
}
|
||||
|
||||
if(!item.reqBodyKey || (item.reqBodyKey && reqBody.toString().indexOf(item.reqBodyKey) >= 0) ){
|
||||
++matchCount;
|
||||
}
|
||||
|
||||
ifMatch = (matchCount==2);
|
||||
if(ifMatch){
|
||||
req.willResponse = item.localResponse;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return ifMatch;
|
||||
}else{
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
customerRule.dealLocalResponse = function(req,reqBody,callback){
|
||||
callback(200,{"content-type":"text/html"},req.willResponse);
|
||||
return req.willResponse;
|
||||
};
|
||||
|
||||
app.post("/update",function(req,res){
|
||||
var data = "";
|
||||
req.on("data",function(chunk){
|
||||
data += chunk;
|
||||
});
|
||||
|
||||
req.on("end",function(){
|
||||
userKey = JSON.parse(data);
|
||||
|
||||
res.statusCode = 200;
|
||||
res.setHeader("Content-Type", "application/json;charset=UTF-8");
|
||||
res.end(JSON.stringify({success : true}));
|
||||
|
||||
requestHandler.setRules(customerRule);
|
||||
self.emit("rule_changed");
|
||||
});
|
||||
});
|
||||
|
||||
app.use(express.static(__dirname + "/web_uiconfig"));
|
||||
app.listen(port);
|
||||
|
||||
self.app = app;
|
||||
}
|
||||
|
||||
// var configServer = new UIConfigServer(proxyConfigPort);
|
||||
// configServer.on("rule_changed",function() {});
|
||||
// inherits(UIConfigServer, events.EventEmitter);
|
||||
|
||||
|
||||
module.exports.proxyServer = proxyServer;
|
||||
module.exports.generateRootCA = certMgr.generateRootCA;
|
||||
module.exports.isRootCAFileExists = certMgr.isRootCAFileExists;
|
||||
|
94
web/anyproxy_wsUtil.js
Normal file
94
web/anyproxy_wsUtil.js
Normal file
@ -0,0 +1,94 @@
|
||||
/*
|
||||
web socket util for AnyProxy
|
||||
https://github.com/alibaba/anyproxy
|
||||
*/
|
||||
|
||||
/*
|
||||
{
|
||||
baseUrl : ""
|
||||
}
|
||||
config
|
||||
config.baseUrl
|
||||
config.port
|
||||
config.onOpen
|
||||
config.onClose
|
||||
config.onError
|
||||
config.onGetData
|
||||
config.onGetUpdate
|
||||
config.onGetBody
|
||||
config.onError
|
||||
*/
|
||||
function anyproxy_wsUtil(config){
|
||||
config = config || {};
|
||||
if(!WebSocket){
|
||||
throw (new Error("webSocket is not available on this browser"));
|
||||
}
|
||||
|
||||
var self = this;
|
||||
var baseUrl = config.baseUrl || "127.0.0.1",
|
||||
socketPort = config.port || 8003;
|
||||
|
||||
var dataSocket = new WebSocket("ws://" + baseUrl + ":" + socketPort);
|
||||
|
||||
self.bodyCbMap = {};
|
||||
dataSocket.onmessage = function(event){
|
||||
config.onGetData && config.onGetData.call(self,event.data);
|
||||
|
||||
try{
|
||||
var data = JSON.parse(event.data),
|
||||
type = data.type,
|
||||
content = data.content,
|
||||
reqRef = data.reqRef;
|
||||
|
||||
if(type == "update"){
|
||||
config.onGetUpdate && config.onGetUpdate.call(self, content);
|
||||
|
||||
}else if(type == "body"){
|
||||
config.onGetBody && config.onGetBody.call(self, content, reqRef);
|
||||
|
||||
if(data.reqRef && self.bodyCbMap[reqRef]){
|
||||
self.bodyCbMap[reqRef].call(self,content);
|
||||
}
|
||||
}
|
||||
|
||||
}catch(e){
|
||||
config.onError && config.onError.call(self, new Error("failed to parse socket data - " + e.toString()) );
|
||||
}
|
||||
}
|
||||
|
||||
dataSocket.onopen = function(e){
|
||||
config.onOpen && config.onOpen.call(self,e);
|
||||
}
|
||||
dataSocket.onclose = function(e){
|
||||
config.onClose && config.onClose.call(self,e);
|
||||
}
|
||||
dataSocket.onerror = function(e){
|
||||
config.onError && config.onError.call(self,e);
|
||||
}
|
||||
|
||||
self.dataSocket = dataSocket;
|
||||
};
|
||||
|
||||
anyproxy_wsUtil.prototype.send = function(data){
|
||||
if(typeof data == "object"){
|
||||
data = JSON.stringify(data);
|
||||
}
|
||||
this.dataSocket.send(data);
|
||||
};
|
||||
|
||||
anyproxy_wsUtil.prototype.reqBody = function(id,callback){
|
||||
if(!id) return;
|
||||
|
||||
var payload = {
|
||||
type : "reqBody",
|
||||
id : id
|
||||
};
|
||||
if(!callback){
|
||||
this.send(payload);
|
||||
}else{
|
||||
var reqRef = "r_" + Math.random()*100 + "_" + (new Date().getTime());
|
||||
payload.reqRef = reqRef;
|
||||
this.bodyCbMap[reqRef] = callback;
|
||||
this.send(payload);
|
||||
}
|
||||
};
|
@ -40,26 +40,29 @@ define("./detail",['$', 'gallery/underscore/1.6.0/underscore.js'],function(requi
|
||||
' </section>'+
|
||||
' <% } %>';
|
||||
|
||||
var cbMap = {};
|
||||
|
||||
//data via web socket
|
||||
var socketPort = $("#socketPort").val(),
|
||||
baseUrl = $("#baseUrl").val(),
|
||||
dataSocket = new WebSocket("ws://" + baseUrl + ":" + socketPort);
|
||||
|
||||
function render(data,cb){
|
||||
var $baseTpl = $(_.template(tpl, data));
|
||||
|
||||
cb($baseTpl);
|
||||
|
||||
// if(data.statusCode){ //if finished
|
||||
// $.ajax({
|
||||
// url : "/body?id=" + data._id,
|
||||
// headers : {
|
||||
// anyproxy_web_req : true
|
||||
// },
|
||||
// type : "GET",
|
||||
// success : function(data){
|
||||
// $(".J_responseBody", $baseTpl).html(data);
|
||||
// cb($baseTpl);
|
||||
// }
|
||||
// });
|
||||
// }else{
|
||||
// cb($baseTpl);
|
||||
// }
|
||||
var resultEl = $(_.template(tpl, data)),
|
||||
id = data._id;
|
||||
try{
|
||||
//if finished
|
||||
var reqRef = "r" + Math.random() + "_" + new Date().getTime();
|
||||
if(data.statusCode){
|
||||
//fetch body
|
||||
ws.reqBody(id,function(content){
|
||||
$(".J_responseBody", resultEl).html(he.encode(content.body));
|
||||
cb(resultEl);
|
||||
});
|
||||
}
|
||||
}catch(e){
|
||||
cb(resultEl);
|
||||
};
|
||||
}
|
||||
|
||||
exports.render = render;
|
||||
|
@ -9,15 +9,12 @@
|
||||
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div class="topHead">
|
||||
<div class="logoWrapper">
|
||||
<h1>Anyproxy</h1>
|
||||
<img class="logo_bottom anim_rotation" id="J_indicator" src="./logo_bottom.png" width="50" height="50" style="visibility:hidden" />
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="ctrlWrapper">
|
||||
<a href="#" class="J_statusBtn"><span class="topBtn"><i class="uk-icon-stop"></i>Stop</span></a>
|
||||
<a href="#" class="J_statusBtn btn_disable"><span class="topBtn"><i class="uk-icon-play"></i>Resume</span></a>
|
||||
@ -27,7 +24,6 @@
|
||||
<a href="/qr_root" class="J_fetchRootQR" target="_blank"><span class="topBtn"><i class="uk-icon-certificate"></i>QRCode of rootCA.crt</span></a>
|
||||
<!-- <a href="#"><span class="topBtn"><i class="uk-icon-cog"></i>Others</span></a> -->
|
||||
|
||||
<!-- <a href="http://localhost:{{proxyConfigPort}}"><span class="topBtn"><i class="uk-icon-cog"></i>Config Local Response(beta)</span></a> -->
|
||||
<span class="sep">|</span>
|
||||
<a href="https://github.com/alibaba/anyproxy" target="_blank"><span class="topBtn"><i class="uk-icon-external-link-square"></i>Anyproxy(Github)</span></a>
|
||||
|
||||
@ -66,12 +62,10 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<input type="hidden" id="socketPort" value="{{webSocketPort}}" />
|
||||
<input type="hidden" id="socketPort" value="{{wsPort}}" />
|
||||
<input type="hidden" id="baseUrl" value="{{ipAddress}}" />
|
||||
<input type="hidden" id="customMenu" value="{{menu}}" />
|
||||
|
||||
|
||||
<script type="text/template" id="main_table_row">
|
||||
<td class="data_id"><%= _id %></td>
|
||||
<td><%= method %> <span class="protocol protocol_<%= protocol %>" title="https"><i class="iconfont">󰃉</i></span> </td>
|
||||
@ -83,6 +77,8 @@
|
||||
</script>
|
||||
|
||||
|
||||
<script src="/anyproxy_wsUtil.js"></script>
|
||||
<script src="/he.js"></script>
|
||||
<script src="/list.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
316
web/list.js
316
web/list.js
@ -14,180 +14,168 @@ seajs.use(['$', 'Underscore', 'Backbone',"Handlebars","Popup","./detail"], funct
|
||||
|
||||
var isInApp = window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.list;
|
||||
|
||||
$(function(){
|
||||
//record detail
|
||||
var DetailView = function(){
|
||||
var self = this,
|
||||
$detailEl = $(".J_recordDetailOverlay"),
|
||||
$mask;
|
||||
|
||||
//record detail
|
||||
var DetailView = function(){
|
||||
var self = this,
|
||||
$detailEl = $(".J_recordDetailOverlay"),
|
||||
$mask;
|
||||
//init mask
|
||||
$mask = $("<div></div>").addClass("overlay_mask").hide();
|
||||
$("body").append($mask);
|
||||
|
||||
//init mask
|
||||
$mask = $("<div></div>").addClass("overlay_mask").hide();
|
||||
$("body").append($mask);
|
||||
|
||||
//bind events
|
||||
$(document).on("keyup",function(e){
|
||||
if(e.keyCode == 27){ //ESC
|
||||
self.hideDetail();
|
||||
}
|
||||
});
|
||||
|
||||
$mask.on("click",function(e){
|
||||
//bind events
|
||||
$(document).on("keyup",function(e){
|
||||
if(e.keyCode == 27){ //ESC
|
||||
self.hideDetail();
|
||||
}
|
||||
});
|
||||
|
||||
$mask.on("click",function(e){
|
||||
self.hideDetail();
|
||||
});
|
||||
|
||||
$(".J_escBtn",$detailEl).on("click",function(e){
|
||||
self.hideDetail();
|
||||
});
|
||||
|
||||
self.showDetail = function(data){
|
||||
Detail.render(data,function(tpl){
|
||||
$(".J_recordDetailOverlayContent",$detailEl).html(tpl);
|
||||
$detailEl.show();
|
||||
$mask.show();
|
||||
});
|
||||
|
||||
$(".J_escBtn",$detailEl).on("click",function(e){
|
||||
self.hideDetail();
|
||||
});
|
||||
|
||||
self.showDetail = function(data){
|
||||
Detail.render(data,function(tpl){
|
||||
$(".J_recordDetailOverlayContent",$detailEl).html(tpl);
|
||||
$detailEl.show();
|
||||
$mask.show();
|
||||
});
|
||||
};
|
||||
|
||||
self.hideDetail = function(){
|
||||
$detailEl.hide();
|
||||
$mask.hide();
|
||||
};
|
||||
};
|
||||
var detailPanel = new DetailView();
|
||||
|
||||
//record list
|
||||
var RecordModel = Backbone.Model.extend({});
|
||||
var RecordList = Backbone.Collection.extend({
|
||||
initialize:function(){
|
||||
var self = this;
|
||||
self.hideDetail = function(){
|
||||
$detailEl.hide();
|
||||
$mask.hide();
|
||||
};
|
||||
};
|
||||
var detailPanel = new DetailView();
|
||||
|
||||
self.on("add",function(data){
|
||||
new RecordRowView({
|
||||
model:data,
|
||||
detailPanel : detailPanel
|
||||
});
|
||||
//record list
|
||||
var RecordModel = Backbone.Model.extend({});
|
||||
var RecordList = Backbone.Collection.extend({
|
||||
initialize:function(){
|
||||
var self = this;
|
||||
|
||||
self.on("add",function(data){
|
||||
new RecordRowView({
|
||||
model:data,
|
||||
detailPanel : detailPanel
|
||||
});
|
||||
});
|
||||
|
||||
self.on("reset",function(){
|
||||
$(".J_tableBody").empty();
|
||||
});
|
||||
}
|
||||
});
|
||||
self.on("reset",function(){
|
||||
$(".J_tableBody").empty();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
var RecordRowView = Backbone.View.extend({
|
||||
tagName : "tr",
|
||||
className:function(){
|
||||
return this.model.toJSON().id % 2 ? "row_odd" : "row_even";
|
||||
},
|
||||
tpl : $("#main_table_row").html(),
|
||||
initialize:function(data){
|
||||
var RecordRowView = Backbone.View.extend({
|
||||
tagName : "tr",
|
||||
className:function(){
|
||||
return this.model.toJSON().id % 2 ? "row_odd" : "row_even";
|
||||
},
|
||||
tpl : $("#main_table_row").html(),
|
||||
initialize:function(data){
|
||||
var self = this;
|
||||
self.model.on("change",self.render,self);
|
||||
self.addNewRecord();
|
||||
self.detailPanel = data.detailPanel;
|
||||
},
|
||||
events: {
|
||||
click: function(e){
|
||||
e.stopPropagation();
|
||||
var self = this;
|
||||
self.model.on("change",self.render,self);
|
||||
self.addNewRecord();
|
||||
self.detailPanel = data.detailPanel;
|
||||
},
|
||||
events: {
|
||||
click: function(e){
|
||||
e.stopPropagation();
|
||||
var self = this;
|
||||
var detailData = self.model.toJSON();
|
||||
if(!isInApp){
|
||||
self.detailPanel.showDetail(detailData);
|
||||
}else{
|
||||
window.webkit.messageHandlers.list.postMessage(JSON.stringify(detailData));
|
||||
}
|
||||
}
|
||||
},
|
||||
render: function(){
|
||||
var self = this,
|
||||
data = self.model.toJSON();
|
||||
if(!data.statusCode){
|
||||
data.statusCode = "-";
|
||||
var detailData = self.model.toJSON();
|
||||
if(!isInApp){
|
||||
self.detailPanel.showDetail(detailData);
|
||||
}else{
|
||||
self.$el.addClass("record_status_done")
|
||||
window.webkit.messageHandlers.list.postMessage(JSON.stringify(detailData));
|
||||
}
|
||||
|
||||
if(!data.mime){
|
||||
data.mime = "-";
|
||||
}
|
||||
|
||||
var html = _.template(self.tpl, data);
|
||||
self.$el.attr("recordId",data.id).empty().html(html);
|
||||
|
||||
return self;
|
||||
},
|
||||
addNewRecord:function(){
|
||||
$(".J_tableBody").prepend(this.render().$el);
|
||||
}
|
||||
});
|
||||
},
|
||||
render: function(){
|
||||
var self = this,
|
||||
data = self.model.toJSON();
|
||||
if(!data.statusCode){
|
||||
data.statusCode = "-";
|
||||
}else{
|
||||
self.$el.addClass("record_status_done")
|
||||
}
|
||||
|
||||
var recList = new RecordList();
|
||||
if(!data.mime){
|
||||
data.mime = "-";
|
||||
}
|
||||
|
||||
//other controllers
|
||||
$(".J_clearBtn").on("click",function(e){
|
||||
var html = _.template(self.tpl, data);
|
||||
self.$el.attr("recordId",data.id).empty().html(html);
|
||||
|
||||
return self;
|
||||
},
|
||||
addNewRecord:function(){
|
||||
$(".J_tableBody").prepend(this.render().$el);
|
||||
}
|
||||
});
|
||||
|
||||
var recList = new RecordList();
|
||||
|
||||
//other controllers
|
||||
$(".J_clearBtn").on("click",function(e){
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
clearLogs();
|
||||
});
|
||||
|
||||
$(document).on("keyup",function(e){
|
||||
if(e.keyCode == 88 && e.ctrlKey){ // ctrl + x
|
||||
clearLogs();
|
||||
}
|
||||
});
|
||||
|
||||
function clearLogs(){
|
||||
recList.reset();
|
||||
}
|
||||
|
||||
//pause btn
|
||||
var ifPause = false,
|
||||
indicatorEl = $("#J_indicator");
|
||||
(function(){
|
||||
var statusBtn = $(".J_statusBtn");
|
||||
statusBtn.on("click",function(e){
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
clearLogs();
|
||||
});
|
||||
$(".J_statusBtn").removeClass("btn_disable");
|
||||
$(this).addClass("btn_disable");
|
||||
|
||||
$(document).on("keyup",function(e){
|
||||
if(e.keyCode == 88 && e.ctrlKey){ // ctrl + x
|
||||
clearLogs();
|
||||
if(/stop/i.test($(this).html()) ){
|
||||
ifPause = true;
|
||||
indicatorEl.fadeOut();
|
||||
// indicatorEl.css("visibility","hidden");
|
||||
}else{
|
||||
ifPause = false;
|
||||
indicatorEl.fadeIn();
|
||||
// indicatorEl.css("visibility","visible");
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
function clearLogs(){
|
||||
recList.reset();
|
||||
}
|
||||
//invoke AnyProxy web socket util
|
||||
(function(){
|
||||
try{
|
||||
var ws = window.ws = new anyproxy_wsUtil({
|
||||
baseUrl : $("#baseUrl").val(),
|
||||
port : $("#socketPort").val(),
|
||||
onOpen : function(){
|
||||
indicatorEl.css("visibility","visible");
|
||||
},
|
||||
onGetUpdate : function(content){
|
||||
if(ifPause) return;
|
||||
|
||||
//pause btn
|
||||
var ifPause = false,
|
||||
indicatorEl = $("#J_indicator");
|
||||
(function(){
|
||||
var statusBtn = $(".J_statusBtn");
|
||||
statusBtn.on("click",function(e){
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
$(".J_statusBtn").removeClass("btn_disable");
|
||||
$(this).addClass("btn_disable");
|
||||
|
||||
if(/stop/i.test($(this).html()) ){
|
||||
ifPause = true;
|
||||
indicatorEl.fadeOut();
|
||||
// indicatorEl.css("visibility","hidden");
|
||||
}else{
|
||||
ifPause = false;
|
||||
indicatorEl.fadeIn();
|
||||
// indicatorEl.css("visibility","visible");
|
||||
}
|
||||
});
|
||||
})();
|
||||
|
||||
//[test]render custom menu
|
||||
var customMenu = $("#customMenu").val().split("@@@");
|
||||
|
||||
//data via web socket
|
||||
if(!WebSocket){
|
||||
alert("WebSocket is required. Please use a modern browser.");
|
||||
return;
|
||||
}
|
||||
var socketPort = $("#socketPort").val(),
|
||||
baseUrl = $("#baseUrl").val(),
|
||||
dataSocket = new WebSocket("ws://" + baseUrl + ":" + socketPort);
|
||||
dataSocket.onopen = function(){
|
||||
indicatorEl.css("visibility","visible");
|
||||
}
|
||||
|
||||
dataSocket.onmessage = function(event){
|
||||
if(ifPause) return;
|
||||
try{
|
||||
var data = JSON.parse(event.data);
|
||||
|
||||
if(data.type == 'update'){
|
||||
var content = data.content;
|
||||
var reqDate = new Date(content.startTime);
|
||||
content.startTimeStr = reqDate.format("hh:mm:ss") + "";
|
||||
|
||||
@ -197,22 +185,24 @@ seajs.use(['$', 'Underscore', 'Backbone',"Handlebars","Popup","./detail"], funct
|
||||
}else{
|
||||
recList.add(new RecordModel(content),{merge: true});
|
||||
}
|
||||
},
|
||||
onError : function(e){
|
||||
console.log(e);
|
||||
indicatorEl.css("visibility","hidden");
|
||||
alert("socket err, please refresh");
|
||||
},
|
||||
onClose : function(e){
|
||||
console.log(e);
|
||||
indicatorEl.css("visibility","hidden");
|
||||
alert("socket closed, please refresh");
|
||||
}
|
||||
});
|
||||
window.ws = ws;
|
||||
|
||||
}catch(e){
|
||||
console.log(e);
|
||||
}
|
||||
}catch(e){
|
||||
alert("failed to invoking web socket on this browser");
|
||||
}
|
||||
|
||||
dataSocket.onclose = function(e){}
|
||||
|
||||
dataSocket.onerror = function(e){
|
||||
console.log(e);
|
||||
indicatorEl.css("visibility","hidden");
|
||||
alert("socket err, please refresh");
|
||||
}
|
||||
|
||||
});
|
||||
})();
|
||||
|
||||
//draggable panel
|
||||
(function(){
|
||||
|
56
web/websocket_sample.html
Normal file
56
web/websocket_sample.html
Normal file
@ -0,0 +1,56 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Anyproxy</title>
|
||||
<link rel="icon" type="image/png" href="/favico.png" />
|
||||
<style type="text/css">
|
||||
.logPanel{
|
||||
border: 1px solid #AAA;
|
||||
}
|
||||
|
||||
.logPanel p{
|
||||
padding-left: 20px;
|
||||
margin: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<input type="text" id="J_data" placeholder="req id" value="1" / >
|
||||
<button type="button" id="J_sendReq">Send</button>
|
||||
<div class="logPanel" id="J_logPanel"></div>
|
||||
|
||||
<script src="./anyproxy_wsUtil.js"></script>
|
||||
<script type="text/javascript">
|
||||
|
||||
//print log
|
||||
var logPanel = document.getElementById("J_logPanel");
|
||||
function log(data){
|
||||
var thisLog = "<p>" + new Date()+ "<br>" + data + "</p>";
|
||||
logPanel.innerHTML = thisLog + logPanel.innerHTML;
|
||||
}
|
||||
|
||||
//instantiate ws util
|
||||
var ws = new anyproxy_wsUtil({
|
||||
baseUrl : "127.0.0.1",
|
||||
port : "8003",
|
||||
onGetUpdate : function(content){
|
||||
log("update id " + content.id + " , content :" + JSON.stringify(content));
|
||||
},
|
||||
onError : function(e){
|
||||
console.log(e);
|
||||
}
|
||||
});
|
||||
|
||||
//to get some response body
|
||||
document.getElementById("J_sendReq").addEventListener("click",function(e){
|
||||
var id = document.getElementById("J_data").value;
|
||||
log("request for body id=" + id + "...");
|
||||
ws.reqBody(id,function(content){
|
||||
log("body id " + content.id + " ,content :" + content.body);
|
||||
});
|
||||
});
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
Loading…
x
Reference in New Issue
Block a user