Commit 6431e477 authored by antoor's avatar antoor

Reconstruction of optimized code

重构优化代码
parent c03f6d26
// /**
// 缓存管理模块 * 缓存管理模块
// * 更新:2016/04/28
* 作者:蚁逅 <https://github.com/antoor>
*/
'use strict'; 'use strict';
const fs = require('fs'); const fs = require('fs'),
const path = require('path'); path = require('path'),
const log4js = require('log4js'); CONF = require('./config'),
const Datastore = require('nedb'); logger = require('log4js').getLogger('Cache'),
Datastore = require('nedb');
const logger = log4js.getLogger('Cache');
class Cache { class Cache {
/**
* 初始化监听事件
* @param {Object} electron electron对象
* @return {[type]} [description]
*/
constructor(electron) { constructor(electron) {
// 创建数据库 electron.ipcMain
// 获取用户保存目录(mac&&*unix=/home/path/,win=c:/path/appdata .on('cache-add', this.addCache.bind(this))
let dbPath = ''; .on('cache-set', this.setCache.bind(this))
if (process.env.HOME) { .on('cache-get', this.getCache.bind(this))
dbPath = path.join(process.env.HOME, '.antSword'); .on('cache-del', this.delCache.bind(this))
}else if (process.env.LOCALAPPPATH) { .on('cache-clear', this.clearCache.bind(this))
dbPath = path.join(process.env.LOCALAPPPATH, '.antSword'); .on('cache-clearAll', this.clearAllCache.bind(this));
}else{ }
dbPath = 'database';
}; /**
// 创建数据目录 * 创建nedb数据库文件
if (!fs.existsSync(dbPath)) { * @param {String} id 数据存储文件名
fs.mkdirSync(dbPath); * @return {[type]} [description]
}; */
// 创建缓存目录 createDB(id = String(+new Date)) {
const cachePath = path.join(dbPath, 'cache'); return new Datastore({
if (!fs.existsSync(cachePath)) { filename: path.join(CONF.cachePath, id),
fs.mkdirSync(cachePath); autoload: true
}; });
this.dbPath = dbPath;
this.cachePath = cachePath;
// 监听数据请求
this.listenHandle(electron.ipcMain);
} }
listenHandle(ipcMain) { /**
logger.info('listenHandle'); * 添加缓存数据
ipcMain * @param {Object} event ipcMain对象
// 添加缓存 * @param {Object} opts 缓存配置(id,tag,cache
// arg={id="shellID",tag="存储标识",cache="存储内容"} */
.on('cache-add', (event, arg) => { addCache(event, opts) {
logger.debug('cache-add', arg); logger.debug('addCache', opts);
this.createDB(arg['id']).insert({ this.createDB(opts['id']).insert({
tag: arg['tag'], tag: opts['tag'],
cache: arg['cache'] cache: opts['cache']
}, (err, ret) => { }, (err, ret) => {
event.returnValue = err || ret; event.returnValue = err || ret;
}); });
}) }
// 更新缓存
// arg = {id, tag, cache} /**
.on('cache-set', (event, arg) => { * 设置缓存数据
logger.debug('cache-set', arg); * @param {Object} event ipcMain对象
this.createDB(arg['id']).update({ * @param {Object} opts 缓存配置(id,tag,cache
tag: arg['tag'] */
setCache(event, opts) {
logger.debug('setCache', opts);
this.createDB(opts['id']).update({
tag: opts['tag']
}, { }, {
$set: { $set: {
cache: arg['cache'] cache: opts['cache']
} }
}, (err, ret) => { }, (err, ret) => {
event.returnValue = err || ret; event.returnValue = err || ret;
}); });
}) }
// 查询缓存
// arg={id="shellID", tag="存储标识"} /**
.on('cache-get', (event, arg) => { * 获取缓存数据
logger.debug('cache-get', arg); * @param {Object} event ipcMain对象
this.createDB(arg['id']).findOne({ * @param {Object} opts 缓存配置(id,tag)
tag: arg['tag'] * @return {[type]} [description]
*/
getCache(event, opts) {
logger.debug('getCache', opts);
this.createDB(opts['id']).findOne({
tag: opts['tag']
}, (err, ret) => { }, (err, ret) => {
event.returnValue = err || ret; event.returnValue = err || ret;
}) })
}) }
// 删除缓存
// arg = {id: 'SHELL-ID', tag: 'SAVE-TAG'} /**
.on('cache-del', (event, arg) => { * 删除缓存
logger.warn('cache-del', arg); * @param {Object} event ipcMain对象
this.createDB(arg['id']).remove({ * @param {Object} opts 缓存配置(id,tag)
tag: arg['tag'] * @return {[type]} [description]
*/
delCache(event, opts) {
logger.warn('delCache', opts);
this.createDB(opts['id']).remove({
tag: opts['tag']
}, (err, ret) => { }, (err, ret) => {
event.returnValue = err || ret; event.returnValue = err || ret;
}) });
}) }
// 清空缓存
// arg = {id: 'SHELL-ID'} /**
.on('cache-clear', (event, arg) => { * 清空缓存数据
logger.fatal('cache-clear', arg); * @param {Object} event ipcMain对象
* @param {Object} opts 缓存配置(id)
* @return {[type]} [description]
*/
clearCache(event, opts) {
logger.fatal('clearCache', opts);
try{ try{
fs.unlinkSync(path.join(this.cachePath, arg['id'])); fs.unlinkSync(path.join(CONF.cachePath, opts['id']));
event.returnValue = true; event.returnValue = true;
}catch(e) { }catch(e) {
event.returnValue = e; event.returnValue = e;
} }
}) }
// 清空所有缓存
.on('cache-clearAll', (event, arg) => { /**
logger.fatal('cache-clearAll', arg); * 清空所有缓存数据
* @param {Object} event ipcMain对象
* @param {Object} opts 缓存配置(null)
* @return {[type]} [description]
*/
clearAllCache(event, opts) {
logger.fatal('clearAllCache', opts);
try{ try{
fs.readdirSync(this.cachePath).map((_) => { fs.readdirSync(CONF.cachePath).map((_) => {
fs.unlinkSync(path.join(this.cachePath, _)); fs.unlinkSync(path.join(CONF.cachePath, _));
}); });
event.returnValue = true; event.returnValue = true;
}catch(e) { }catch(e) {
event.returnValue = e; event.returnValue = e;
} }
})
} }
createDB(id) {
// 创建数据库
return new Datastore({
filename: path.join(this.cachePath, id),
autoload: true
});
}
} }
module.exports = Cache; module.exports = Cache;
/**
* 中国蚁剑::后端配置模块
* ? 用于进行一些通用的变量如初始化目录等设置
* 开写:2016/04/26
* 更新:2016/04/28
* 作者:蚁逅 <https://github.com/antoor>
*/
'use strict';
const fs = require('fs'),
path = require('path');
class Conf {
constructor() {
// 获取数据存储目录
this.basePath = path.join(
process.env.HOME || process.env.LOCALAPPPATH || process.cwd() || '.',
'.antSword'
);
// 创建.antSword目录
!fs.existsSync(this.basePath) ? fs.mkdirSync(this.basePath) : null;
}
/**
* 获取数据存储路径
* @return {String} file-path
*/
get dataPath() {
return path.join(this.basePath, 'shell.db');
}
/**
* 获取缓存目录
* @return {String} dir-path
*/
get cachePath() {
let _ = path.join(this.basePath, '/cache/');
// 创建缓存目录
!fs.existsSync(_) ? fs.mkdirSync(_) : null;
return _;
}
}
module.exports = new Conf();
// /**
// shell数据管理模块 * Shell数据库管理模块
// * 更新:2016/04/28
* 作者:蚁逅 <https://github.com/antoor>
*/
'use strict'; 'use strict';
const fs = require('fs'); const fs = require('fs'),
const dns = require('dns'); dns = require('dns'),
const path = require('path'); path = require('path'),
const log4js = require('log4js'); CONF = require('./config'),
const Datastore = require('nedb'); logger = require('log4js').getLogger('Database'),
const qqwry = require("lib-qqwry").info(); Datastore = require('nedb'),
qqwry = require("lib-qqwry").info();
const logger = log4js.getLogger('Database');
class Database { class Database {
/**
* 初始化数据库
* @param {electron} electron electron对象
* @return {[type]} [description]
*/
constructor(electron) { constructor(electron) {
this.cursor = this.createDB(); this.cursor = new Datastore({
// 监听数据请求 filename: CONF.dataPath,
const ipcMain = electron.ipcMain;
this.listenHandle(ipcMain);
}
createDB() {
// 创建数据库
// 获取用户保存目录(mac&&*unix=/home/path/,win=c:/path/appdata
let dbPath = '';
if (process.env.HOME) {
dbPath = path.join(process.env.HOME, '.antSword');
}else if (process.env.LOCALAPPPATH) {
dbPath = path.join(process.env.LOCALAPPPATH, '.antSword');
}else{
dbPath = 'database';
};
// 创建目录
if (!fs.existsSync(dbPath)) {
fs.mkdirSync(dbPath);
};
// 创建数据库
return new Datastore({
filename: path.join(dbPath, 'shell.db'),
autoload: true autoload: true
}); });
// 监听事件
electron.ipcMain
.on('shell-add', this.addShell.bind(this))
.on('shell-del', this.delShell.bind(this))
.on('shell-edit', this.editShell.bind(this))
.on('shell-move', this.moveShell.bind(this))
.on('shell-find', this.findShell.bind(this))
.on('shell-clear', this.clearShell.bind(this))
.on('shell-findOne', this.findOneShell.bind(this))
.on('shell-addDataConf', this.addDataConf.bind(this))
.on('shell-delDataConf', this.delDataConf.bind(this))
.on('shell-getDataConf', this.getDataConf.bind(this))
.on('shell-renameCategory', this.renameShellCategory.bind(this));
} }
listenHandle(ipcMain) { /**
ipcMain * 查询shell数据
// 查询数据数据,arg=find条件,比如arg={category:'test'} * @param {Object} event ipcMain对象
.on('shell-find', (event, arg) => { * @param {Object} opts 查询配置
logger.debug('shell-find', arg); * @return {[type]} [description]
*/
findShell(event, opts = {}) {
logger.debug('findShell', opts);
this.cursor this.cursor
.find(arg || {}) .find(opts)
.sort({ .sort({
utime: -1 utime: -1
}) })
.exec((err, ret) => { .exec((err, ret) => {
event.returnValue = ret || []; event.returnValue = ret || [];
}); });
}) }
// 查询单数据
.on('shell-findOne', (event, id) => { /**
logger.debug('shell-findOne', id); * 查询单一shell数据
* @param {Object} event ipcMain对象
* @param {String} opts shell id
* @return {[type]} [description]
*/
findOneShell(event, opts) {
logger.debug('findOneShell', opts);
this.cursor.findOne({ this.cursor.findOne({
_id: id _id: opts
}, (err, ret) => { }, (err, ret) => {
event.returnValue = err || ret; event.returnValue = err || ret;
}); });
}) }
// 插入数据
// arg={category,url,pwd,ip,addr,type,encode,encoder,ctime,utime} /**
.on('shell-add', (event, arg) => { * 添加shell数据
logger.info('shell-add\n', arg); * @param {Object} event ipcMain对象
* @param {Object} opts 数据(url,category,pwd,type,encode,encoder
*/
addShell(event, opts) {
logger.info('addShell', opts);
// 获取目标IP以及地理位置 // 获取目标IP以及地理位置
// 1. 获取域名 // 1. 获取域名
const parse = arg['url'].match(/(\w+):\/\/([\w\.\-]+)[:]?([\d]*)([\s\S]*)/i); let parse = opts['url'].match(/(\w+):\/\/([\w\.\-]+)[:]?([\d]*)([\s\S]*)/i);
if (!parse || parse.length < 3) { return event.returnValue = 'Unable to resolve domain name from URL' }; if (!parse || parse.length < 3) { return event.returnValue = 'Unable to resolve domain name from URL' };
// 2. 获取域名IP // 2. 获取域名IP
dns.lookup(parse[2], (err, ip) => { dns.lookup(parse[2], (err, ip) => {
...@@ -82,30 +92,33 @@ class Database { ...@@ -82,30 +92,33 @@ class Database {
const addr = qqwry.searchIP(ip); const addr = qqwry.searchIP(ip);
// 插入数据库 // 插入数据库
this.cursor.insert({ this.cursor.insert({
category: arg['category'] || 'default', category: opts['category'] || 'default',
url: arg['url'], url: opts['url'],
pwd: arg['pwd'], pwd: opts['pwd'],
type: arg['type'], type: opts['type'],
ip: ip, ip: ip,
addr: `${addr.Country} ${addr.Area}`, addr: `${addr.Country} ${addr.Area}`,
encode: arg['encode'], encode: opts['encode'],
encoder: arg['encoder'], encoder: opts['encoder'],
ctime: +new Date, ctime: +new Date,
utime: +new Date utime: +new Date
}, (err, ret) => { }, (err, ret) => {
event.returnValue = err || ret; event.returnValue = err || ret;
}); });
}); });
}) }
/*
// 编辑数据 /**
// {url,pwd,encode,type,encoder,utime} * 编辑shell数据
* @param {Object} event ipcMain对象
* @param {Object} opts 数据(url,_id,pwd,type,encode,encoder
* @return {[type]} [description]
*/ */
.on('shell-edit', (event, arg) => { editShell(event, opts) {
logger.warn('shell-edit\n', arg); logger.warn('editShell', opts);
// 获取目标IP以及地理位置 // 获取目标IP以及地理位置
// 1. 获取域名 // 1. 获取域名
const parse = arg['url'].match(/(\w+):\/\/([\w\.\-]+)[:]?([\d]*)([\s\S]*)/i); let parse = opts['url'].match(/(\w+):\/\/([\w\.\-]+)[:]?([\d]*)([\s\S]*)/i);
if (!parse || parse.length < 3) { return event.returnValue = 'Unable to resolve domain name from URL' }; if (!parse || parse.length < 3) { return event.returnValue = 'Unable to resolve domain name from URL' };
// 2. 获取域名IP // 2. 获取域名IP
dns.lookup(parse[2], (err, ip) => { dns.lookup(parse[2], (err, ip) => {
...@@ -114,73 +127,96 @@ class Database { ...@@ -114,73 +127,96 @@ class Database {
const addr = qqwry.searchIP(ip); const addr = qqwry.searchIP(ip);
// 更新数据库 // 更新数据库
this.cursor.update({ this.cursor.update({
_id: arg['_id'] _id: opts['_id']
}, { }, {
$set: { $set: {
ip: ip, ip: ip,
addr: `${addr.Country} ${addr.Area}`, addr: `${addr.Country} ${addr.Area}`,
url: arg['url'], url: opts['url'],
pwd: arg['pwd'], pwd: opts['pwd'],
type: arg['type'], type: opts['type'],
encode: arg['encode'], encode: opts['encode'],
encoder: arg['encoder'], encoder: opts['encoder'],
utime: +new Date utime: +new Date
} }
}, (err, num) => { }, (err, num) => {
event.returnValue = err || num; event.returnValue = err || num;
}) })
}); });
}) }
// 删除数据
.on('shell-del', (event, ids) => { /**
logger.warn('shell-del', ids); * 删除shell数据
* @param {Object} event ipcMain对象
* @param {Array} opts 要删除的shell-id列表
* @return {[type]} [description]
*/
delShell(event, opts) {
logger.warn('delShell', opts);
this.cursor.remove({ this.cursor.remove({
_id: { _id: {
$in: ids $in: opts
} }
}, { }, {
multi: true multi: true
}, (err, num) => { }, (err, num) => {
event.returnValue = err || num; event.returnValue = err || num;
}) })
}) }
// 清空分类数据
.on('shell-clear', (event, category) => { /**
logger.fatal('shell-clear', category); * 删除分类shell数据
* @param {Object} event ipcMain对象
* @param {String} opts shell分类名
* @return {[type]} [description]
*/
clearShell(event, opts) {
logger.fatal('clearShell', opts);
this.cursor.remove({ this.cursor.remove({
category: category category: opts
}, { }, {
multi: true multi: true
}, (err, num) => { }, (err, num) => {
event.returnValue = err || num; event.returnValue = err || num;
}) })
}) }
// 重命名分类
// {oldName, newName} /**
.on('shell-renameCategory', (event, arg) => { * 重命名shell分类
logger.warn('shell-renameCategory', arg); * @param {Object} event ipcMain对象
* @param {Object} opts 配置(oldName,newName
* @return {[type]} [description]
*/
renameShellCategory(event, opts) {
logger.warn('renameShellCategory', opts);
this.cursor.update({ this.cursor.update({
category: arg['oldName'] category: opts['oldName']
}, { }, {
$set: { $set: {
category: arg['newName'] category: opts['newName']
} }
}, { }, {
multi: true multi: true
}, (err, num) => { }, (err, num) => {
event.returnValue = err || num; event.returnValue = err || num;
}) })
}) }
// 移动数据
.on('shell-move', (event, arg) => { /**
logger.info('shell-move', arg); * 移动shell数据分类
* @param {Object} event ipcMain对象
* @param {Object} opts 配置(ids,category
* @return {[type]} [description]
*/
moveShell(event, opts) {
logger.info('moveShell', opts);
this.cursor.update({ this.cursor.update({
_id: { _id: {
$in: arg['ids'] || [] $in: opts['ids'] || []
} }
}, { }, {
$set: { $set: {
category: arg['category'] || 'default', category: opts['category'] || 'default',
utime: +new Date utime: +new Date
} }
}, { }, {
...@@ -188,24 +224,27 @@ class Database { ...@@ -188,24 +224,27 @@ class Database {
}, (err, num) => { }, (err, num) => {
event.returnValue = err || num; event.returnValue = err || num;
}) })
}) }
//
// 添加数据库配置 /**
// * 添加数据库配置
.on('shell-addDataConf', (event, arg) => { * @param {Object} event ipcMain对象
logger.info('shell-addDataConf', arg); * @param {Object} opts 配置(_id,data
*/
addDataConf(event, opts) {
logger.info('addDataConf', opts);
// 1. 获取原配置列表 // 1. 获取原配置列表
this.cursor.findOne({ this.cursor.findOne({
_id: arg['_id'] _id: opts['_id']
}, (err, ret) => { }, (err, ret) => {
let confs = ret['database'] || {}; let confs = ret['database'] || {};
// 随机Id(顺序增长 // 随机Id(顺序增长
const random_id = parseInt(+new Date + Math.random() * 1000).toString(16); const random_id = parseInt(+new Date + Math.random() * 1000).toString(16);
// 添加到配置 // 添加到配置
confs[random_id] = arg['data']; confs[random_id] = opts['data'];
// 更新数据库 // 更新数据库
this.cursor.update({ this.cursor.update({
_id: arg['_id'] _id: opts['_id']
}, { }, {
$set: { $set: {
database: confs, database: confs,
...@@ -215,23 +254,26 @@ class Database { ...@@ -215,23 +254,26 @@ class Database {
event.returnValue = random_id; event.returnValue = random_id;
}); });
}); });
}) }
//
// 删除数据库配置 /**
// arg={_id: 'shell-ID',id: 'data-id'} * 删除数据库配置
// * @param {Object} event ipcMain对象
.on('shell-delDataConf', (event, arg) => { * @param {Object} opts 配置(_id,id
logger.info('shell-delDataConf', arg); * @return {[type]} [description]
*/
delDataConf(event, opts) {
logger.info('delDataConf', opts);
// 1. 获取原配置 // 1. 获取原配置
this.cursor.findOne({ this.cursor.findOne({
_id: arg['_id'] _id: opts['_id']
}, (err, ret) => { }, (err, ret) => {
let confs = ret['database'] || {}; let confs = ret['database'] || {};
// 2. 删除配置 // 2. 删除配置
delete confs[arg['id']]; delete confs[opts['id']];
// 3. 更新数据库 // 3. 更新数据库
this.cursor.update({ this.cursor.update({
_id: arg['_id'] _id: opts['_id']
}, { }, {
$set: { $set: {
database: confs, database: confs,
...@@ -241,21 +283,23 @@ class Database { ...@@ -241,21 +283,23 @@ class Database {
event.returnValue = _err || _ret; event.returnValue = _err || _ret;
}); });
}) })
}) }
//
// 获取数据库单个配置信息 /**
// * 获取单个数据库配置
.on('shell-getDataConf', (event, arg) => { * @param {Object} event ipcMain对象
logger.info('shell-getDataConf', arg); * @param {Object} opts 配置(_id,id
* @return {[type]} [description]
*/
getDataConf(event, opts) {
logger.info('getDatConf', opts);
this.cursor.findOne({ this.cursor.findOne({
_id: arg['_id'] _id: opts['_id']
}, (err, ret) => { }, (err, ret) => {
const confs = ret['database'] || {}; const confs = ret['database'] || {};
event.returnValue = err || confs[arg['id']]; event.returnValue = err || confs[opts['id']];
}); });
})
} }
} }
module.exports = Database; module.exports = Database;
...@@ -4,20 +4,18 @@ ...@@ -4,20 +4,18 @@
'use strict'; 'use strict';
// 读取package.json信息
const info = require('../package');
class Menubar { class Menubar {
constructor(electron, app, mainWindow) { constructor(electron, app, mainWindow) {
const Menu = electron.Menu; const Menu = electron.Menu;
const ipcMain = electron.ipcMain;
// 清空菜单栏 // 清空菜单栏
Menu.setApplicationMenu(Menu.buildFromTemplate([])); Menu.setApplicationMenu(Menu.buildFromTemplate([]));
// 监听重载菜单事件 // 监听重载菜单事件
ipcMain.on('menubar', this.reload.bind(this)); electron.ipcMain
ipcMain.on('quit', app.quit.bind(app)); .on('quit', app.quit.bind(app))
.on('menubar', this.reload.bind(this));
this.electron = electron; this.electron = electron;
this.app = app; this.app = app;
...@@ -25,7 +23,12 @@ class Menubar { ...@@ -25,7 +23,12 @@ class Menubar {
this.mainWindow = mainWindow; this.mainWindow = mainWindow;
} }
// 刷新菜单 /**
* 重新载入菜单
* @param {Object} event ipcMain对象
* @param {Object} LANG 语言模板
* @return {[type]} [description]
*/
reload(event, LANG) { reload(event, LANG) {
// 菜单模板 // 菜单模板
const template = [ const template = [
...@@ -36,9 +39,7 @@ class Menubar { ...@@ -36,9 +39,7 @@ class Menubar {
{ {
label: LANG['shell']['add'], label: LANG['shell']['add'],
accelerator: 'Shift+A', accelerator: 'Shift+A',
click: () => { click: event.sender.send.bind(event.sender, 'menubar', 'shell-add')
event.sender.send('menubar', 'shell-add');
}
}, { }, {
label: LANG['shell']['search'], label: LANG['shell']['search'],
accelerator: 'Shift+S', accelerator: 'Shift+S',
...@@ -99,7 +100,7 @@ class Menubar { ...@@ -99,7 +100,7 @@ class Menubar {
} }
]; ];
// 调试菜单 // 调试菜单
if (info['debug']) { if (process.env['npm_package_debug']) {
template.push({ template.push({
label: LANG['debug']['title'], label: LANG['debug']['title'],
submenu: [ submenu: [
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment