From 39ae0f46480b958543f49e1d6623dd6ca7cfd7f7 Mon Sep 17 00:00:00 2001
From: OttoMao <ottomao@gmail.com>
Date: Thu, 6 Aug 2015 23:13:17 +0800
Subject: [PATCH] optimize recorder

---
 lib/recorder.js     |  6 ++++
 lib/rule_default.js | 85 +++++++++++++++++++++++++++------------------
 lib/webInterface.js | 19 +++++-----
 package.json        |  1 +
 web/build/index.js  | 11 ++++++
 web/page.js         | 11 ++++++
 web/src/index.js    | 11 ++++++
 7 files changed, 101 insertions(+), 43 deletions(-)

diff --git a/lib/recorder.js b/lib/recorder.js
index 4babf28..cc8cf22 100644
--- a/lib/recorder.js
+++ b/lib/recorder.js
@@ -148,6 +148,12 @@ function Recorder(option){
         db.find({},cb);
     };
 
+    self.getRecords = function(idStart, limit, cb){
+        limit   = limit || 10;
+        idStart = typeof idStart == "number" ? idStart : (id - limit);
+        db.find({ _id: { $gte: parseInt(idStart) } }).limit(limit).exec(cb);
+    };
+
     self.db = db;
 }
 
diff --git a/lib/rule_default.js b/lib/rule_default.js
index e09b173..5470900 100644
--- a/lib/rule_default.js
+++ b/lib/rule_default.js
@@ -1,58 +1,75 @@
 var utils      = require("./util"),
     bodyParser = require("body-parser"),
     path       = require("path"),
-    fs         = require("fs");
+    fs         = require("fs"),
+    Promise    = require("promise");
 
 var isRootCAFileExists = require("./certMgr.js").isRootCAFileExists(),
     interceptFlag      = false;
 
 //e.g. [ { keyword: 'aaa', local: '/Users/Stella/061739.pdf' } ]
-var mapConfig = [];
-
-
-var configFile = "mapConfig.json";
+var mapConfig = [],
+    configFile = "mapConfig.json";
 function saveMapConfig(content,cb){
-    try{
+    new Promise(function(resolve,reject){
         var anyproxyHome = utils.getAnyProxyHome(),
             mapCfgPath   = path.join(anyproxyHome,configFile);
-
+        
         if(typeof content == "object"){
             content = JSON.stringify(content);
         }
-        fs.writeFile(mapCfgPath,content,cb);
-    }catch(e){
-        cb && cb(e)
-    }
+        resolve({
+            path    :mapCfgPath,
+            content :content
+        });
+    })
+    .then(function(config){
+        return new Promise(function(resolve,reject){
+            fs.writeFile(config.path, config.content, function(e){
+                if(e){
+                    reject(e);
+                }else{
+                    resolve();
+                }
+            });
+        });
+    })
+    .catch(function(e){
+        cb && cb(e);
+    })
+    .done(function(){
+        cb && cb();
+    });
 }
-
 function getMapConfig(cb){
-    try{
+    var read = Promise.denodeify(fs.readFile);
+
+    new Promise(function(resolve,reject){
         var anyproxyHome = utils.getAnyProxyHome(),
             mapCfgPath   = path.join(anyproxyHome,configFile);
 
-        fs.readFile(mapCfgPath,{encoding:"utf8"},function(err,content){
-            if(err){
-                cb && cb(err)
-            }else{
-                try{
-                    var obj = JSON.parse(content);
-                    cb && cb(null,obj);
-                }catch(e){
-                    cb && cb(e);
-                } 
-            }
-        });
-    }catch(e){
-        cb && cb(e)
-    }
+        resolve(mapCfgPath);
+    })
+    .then(read)
+    .then(function(content){
+        return JSON.parse(content);
+    })
+    .catch(function(e){
+        cb && cb(e);
+    })
+    .done(function(obj){
+        cb && cb(null,obj);
+    });
 }
 
-//load saved config file
-getMapConfig(function(err,result){
-    if(result){
-        mapConfig = result;
-    }
-});
+setTimeout(function(){
+    //load saved config file
+    getMapConfig(function(err,result){
+        if(result){
+            mapConfig = result;
+        }
+    });
+},1000);
 
 
 module.exports = {
diff --git a/lib/webInterface.js b/lib/webInterface.js
index efb1985..e47112a 100644
--- a/lib/webInterface.js
+++ b/lib/webInterface.js
@@ -37,15 +37,15 @@ function webInterface(config){
         return next();
     });
 
-    // app.get("/summary",function(req,res){
-    //     recorder.getSummaryList(function(err,docs){
-    //         if(err){
-    //             res.end(err.toString());
-    //         }else{
-    //             res.json(docs.slice(docs.length -500));
-    //         }
-    //     });
-    // });
+    app.get("/lastestLog",function(req,res){
+        recorder.getRecords(null,60,function(err,docs){
+            if(err){
+                res.end(err.toString());
+            }else{
+                res.json(docs);
+            }
+        });
+    });
 
     app.get("/fetchCrtFile",function(req,res){
         if(crtFilePath){
@@ -108,6 +108,7 @@ function webInterface(config){
 
     app.use(express.static(staticDir));
 
+    //plugin from rule file
     if(typeof userRule._plugIntoWebinterface == "function"){
         userRule._plugIntoWebinterface(app,function(){
             app.listen(port);
diff --git a/package.json b/package.json
index 93e235a..d6e83bf 100644
--- a/package.json
+++ b/package.json
@@ -19,6 +19,7 @@
     "juicer": "^0.6.6-stable",
     "nedb": "^0.11.0",
     "npm": "^2.7.0",
+    "promise": "^7.0.4",
     "qrcode-npm": "0.0.3",
     "stream-throttle": "^0.1.3",
     "ws": "^0.4.32"
diff --git a/web/build/index.js b/web/build/index.js
index 2f60603..f11a0e6 100644
--- a/web/build/index.js
+++ b/web/build/index.js
@@ -114,6 +114,15 @@ var recorder;
 		}
 	}
 
+	function initRecordSet(){
+		$.getJSON("/lastestLog",function(res){
+			if(typeof res == "object"){
+				recordSet = res;
+				eventCenter.dispatchEvent("recordSetUpdated");
+			}
+		});
+	}
+
 	eventCenter.addListener("wsGetUpdate",updateRecordSet);
 
 	eventCenter.addListener('recordSetUpdated',function(){
@@ -137,6 +146,8 @@ var recorder;
 		React.createElement(RecordPanel, {onSelect: showDetail}),
 		document.getElementById("J_content")
 	);
+
+	initRecordSet();
 })();
 
 
diff --git a/web/page.js b/web/page.js
index f470f95..9e7769c 100644
--- a/web/page.js
+++ b/web/page.js
@@ -160,6 +160,15 @@
 			}
 		}
 
+		function initRecordSet(){
+			$.getJSON("/lastestLog",function(res){
+				if(typeof res == "object"){
+					recordSet = res;
+					eventCenter.dispatchEvent("recordSetUpdated");
+				}
+			});
+		}
+
 		eventCenter.addListener("wsGetUpdate",updateRecordSet);
 
 		eventCenter.addListener('recordSetUpdated',function(){
@@ -183,6 +192,8 @@
 			React.createElement(RecordPanel, {onSelect: showDetail}),
 			document.getElementById("J_content")
 		);
+
+		initRecordSet();
 	})();
 
 
diff --git a/web/src/index.js b/web/src/index.js
index de4ae74..e9ee44a 100644
--- a/web/src/index.js
+++ b/web/src/index.js
@@ -114,6 +114,15 @@ var recorder;
 		}
 	}
 
+	function initRecordSet(){
+		$.getJSON("/lastestLog",function(res){
+			if(typeof res == "object"){
+				recordSet = res;
+				eventCenter.dispatchEvent("recordSetUpdated");
+			}
+		});
+	}
+
 	eventCenter.addListener("wsGetUpdate",updateRecordSet);
 
 	eventCenter.addListener('recordSetUpdated',function(){
@@ -137,6 +146,8 @@ var recorder;
 		<RecordPanel onSelect={showDetail}/>,
 		document.getElementById("J_content")
 	);
+
+	initRecordSet();
 })();