Merge branch 'quickcommand3' of https://github.com/fofolee/uTools-quickcommand into quickcommand3

This commit is contained in:
fofolee 2022-04-29 22:56:41 +08:00
commit 9c81600d26
6 changed files with 92 additions and 63 deletions

View File

@ -157,14 +157,13 @@ window.quickcommand = {
}, },
// 载入在线资源 // 载入在线资源
loadRemoteScript: async function(url, forceUpdate = false) { loadRemoteScript: async function(url) {
if (!/^((ht|f)tps?):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?/.test(url)) throw 'url 不合法' if (!/^((ht|f)tps?):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?/.test(url)) throw 'url 不合法'
let remote = url let local = getQuickcommandTempFile('js')
let root = path.join(os.tmpdir(), 'qcRemoteScript') await this.downloadFile(url, local)
if (!fs.existsSync(root)) fs.mkdirSync(root) let source = require(local)
let local = path.join(root, require('crypto').createHash('md5').update(url).digest('hex')) fs.unlinkSync(local)
if (forceUpdate || !fs.existsSync(local)) await this.downloadFile(remote, local) return source
return require(local)
}, },
// 唤醒 uTools // 唤醒 uTools
@ -187,7 +186,7 @@ window.quickcommand = {
// 运行vbs脚本 // 运行vbs脚本
if (process.platform == 'win32') quickcommand.runVbs = function(script) { if (process.platform == 'win32') quickcommand.runVbs = function(script) {
return new Promise((reslove, reject) => { return new Promise((reslove, reject) => {
var tempfile = path.join(os.tmpdir(), 'TempVBSScript.vbs') var tempfile = getQuickcommandTempFile('vbs', 'TempVBSScript')
fs.writeFile(tempfile, iconv.encode(script, 'gbk'), err => { fs.writeFile(tempfile, iconv.encode(script, 'gbk'), err => {
child_process.exec(`cscript.exe /nologo "${tempfile}"`, { child_process.exec(`cscript.exe /nologo "${tempfile}"`, {
encoding: "buffer" encoding: "buffer"
@ -258,7 +257,7 @@ window.pluginInfo = () => {
let getSleepCodeByShell = ms => { let getSleepCodeByShell = ms => {
var cmd, tempFilePath var cmd, tempFilePath
if (utools.isWindows()) { if (utools.isWindows()) {
tempFilePath = getQuickcommandTempFile('vbs') tempFilePath = getQuickcommandTempFile('vbs', 'SleepVBSScript')
cmd = `echo set ws=CreateObject("Wscript.Shell") > ${tempFilePath} && echo Wscript.sleep ${ms} >> ${tempFilePath} && cscript /nologo ${tempFilePath}` cmd = `echo set ws=CreateObject("Wscript.Shell") > ${tempFilePath} && echo Wscript.sleep ${ms} >> ${tempFilePath} && cscript /nologo ${tempFilePath}`
} else { } else {
cmd = `sleep ${ms / 1000}` cmd = `sleep ${ms / 1000}`
@ -316,8 +315,16 @@ window.getUtoolsPlugins = () => {
return plugins; return plugins;
} }
window.getQuickcommandTempFile = ext => { window.getQuickcommandTempFile = (ext, name, dir = 'quickcommandTempDir') => {
return path.join(os.tmpdir(), `quickcommandTempFile.${ext}`) if (!name) name = new Date().getTime() + (Math.random() * 10 ** 6).toFixed()
let tempDir = path.join(os.tmpdir(), dir)
if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir)
return path.join(tempDir, `${name}.${ext}`)
}
window.delTempFile = (...args) => {
let tmpPath = path.join(os.tmpdir(), ...args)
if (fs.existsSync(tmpPath)) fs.unlinkSync(tmpPath)
} }
window.getBase64Ico = filepath => { window.getBase64Ico = filepath => {
@ -518,8 +525,8 @@ window.runCodeFile = (cmd, option, terminal, callback) => {
ext = option.ext, ext = option.ext,
charset = option.charset, charset = option.charset,
scptarg = option.scptarg || ""; scptarg = option.scptarg || "";
let script = getQuickcommandTempFile(ext) let script = getQuickcommandTempFile(ext, 'quickcommandTempScript')
// 批处理和 powershell 默认编码为 GBK, 解决批处理的换行问题 // 批处理和 powershell 默认编码为 GBK, 解决批处理的换行问题
if (charset.scriptCode) cmd = iconv.encode(cmd.replace(/\n/g, '\r\n'), charset.scriptCode); if (charset.scriptCode) cmd = iconv.encode(cmd.replace(/\n/g, '\r\n'), charset.scriptCode);
fs.writeFileSync(script, cmd); fs.writeFileSync(script, cmd);
// var argvs = [script] // var argvs = [script]
@ -541,27 +548,27 @@ window.runCodeFile = (cmd, option, terminal, callback) => {
// 在终端中输出 // 在终端中输出
if (terminal) cmdline = getCommandToLaunchTerminal(cmdline) if (terminal) cmdline = getCommandToLaunchTerminal(cmdline)
child = child_process.spawn(cmdline, { child = child_process.spawn(cmdline, {
encoding: 'buffer', encoding: 'buffer',
shell: true shell: true
}) })
// var chunks = [], // var chunks = [],
// err_chunks = []; // err_chunks = [];
console.log('running: ' + cmdline); console.log('running: ' + cmdline);
child.stdout.on('data', chunk => { child.stdout.on('data', chunk => {
if (charset.outputCode) chunk = iconv.decode(chunk, charset.outputCode) if (charset.outputCode) chunk = iconv.decode(chunk, charset.outputCode)
callback(chunk.toString(), null) callback(chunk.toString(), null)
// chunks.push(chunk) // chunks.push(chunk)
}) })
child.stderr.on('data', stderr => { child.stderr.on('data', stderr => {
if (charset.outputCode) stderr = iconv.decode(stderr, charset.outputCode) if (charset.outputCode) stderr = iconv.decode(stderr, charset.outputCode)
callback(null, stderr.toString()) callback(null, stderr.toString())
// err_chunks.push(err_chunk) // err_chunks.push(err_chunk)
}) })
// child.on('close', code => { // child.on('close', code => {
// let stdout = chunks.join(""); // let stdout = chunks.join("");
// let stderr = err_chunks.join(""); // let stderr = err_chunks.join("");
// callback(stdout, stderr) // callback(stdout, stderr)
// }) // })
return child return child
} }
@ -599,7 +606,7 @@ window.quickcommandHttpServer = () => {
req.on('end', () => { req.on('end', () => {
let parsedParams let parsedParams
let params = data.join("").toString() let params = data.join("").toString()
// 先尝试作为 json 解析 // 先尝试作为 json 解析
try { try {
parsedParams = JSON.parse(params) parsedParams = JSON.parse(params)
} catch (error) { } catch (error) {

View File

@ -69,6 +69,8 @@ export default {
frameInitHeight: 0, frameInitHeight: 0,
childProcess: null, childProcess: null,
timeStamp: null, timeStamp: null,
urlReg:
/^((ht|f)tps?):\/\/([\w\-]+(\.[\w\-]+)*\/)*[\w\-]+(\.[\w\-]+)*\/?(\?([\w\-\.,@?^=%&:\/~\+#]*)+)?/,
}; };
}, },
props: { props: {
@ -102,15 +104,18 @@ export default {
}, },
async fire(currentCommand) { async fire(currentCommand) {
currentCommand.cmd = this.assignSpecialVars(currentCommand.cmd); currentCommand.cmd = this.assignSpecialVars(currentCommand.cmd);
this.enableHtml = currentCommand.output === "html"; if (currentCommand.output === "html") {
this.enableHtml = true;
currentCommand.cmd = await this.cacheScript(currentCommand.cmd);
}
let { hideWindow, outPlugin, action } = let { hideWindow, outPlugin, action } =
outputTypes[currentCommand.output]; outputTypes[currentCommand.output];
// //
hideWindow && utools.hideMainWindow(); hideWindow && utools.hideMainWindow();
// 退 // 退
// 退 // 退
let quitBeforeShowResult = this.fromUtools && outPlugin; let earlyExit = this.fromUtools && outPlugin;
quitBeforeShowResult && earlyExit &&
setTimeout(() => { setTimeout(() => {
utools.outPlugin(); utools.outPlugin();
}, 500); }, 500);
@ -118,19 +123,12 @@ export default {
window.runCodeInSandbox( window.runCodeInSandbox(
currentCommand.cmd, currentCommand.cmd,
(stdout, stderr) => { (stdout, stderr) => {
if (stderr) { this.handleResult(stdout, stderr, { outPlugin, action, earlyExit });
return quitBeforeShowResult
? alert(stderr)
: this.showRunResult(stderr, false, action);
}
outPlugin
? action(stdout.toString())
: this.showRunResult(stdout, true);
}, },
{ enterData: this.$root.enterData } { enterData: this.$root.enterData }
); );
} else if (currentCommand.program === "html") { } else if (currentCommand.program === "html") {
this.showRunResult(currentCommand.cmd, true, action); this.showRunResult(currentCommand.cmd, true);
} else { } else {
let option = let option =
currentCommand.program === "custom" currentCommand.program === "custom"
@ -143,14 +141,7 @@ export default {
option, option,
currentCommand.output === "terminal", currentCommand.output === "terminal",
(stdout, stderr) => { (stdout, stderr) => {
if (stderr) { this.handleResult(stdout, stderr, { outPlugin, action, earlyExit });
return quitBeforeShowResult
? alert(stderr)
: this.showRunResult(stderr, false, action);
}
outPlugin
? action(stdout.toString())
: this.showRunResult(stdout, true);
} }
); );
// ctrl c // ctrl c
@ -235,6 +226,16 @@ export default {
payload: await commandTypes[type]?.tempPayload?.(), payload: await commandTypes[type]?.tempPayload?.(),
}; };
}, },
handleResult(stdout, stderr, options) {
if (stderr) {
return options.earlyExit
? alert(stderr)
: this.showRunResult(stderr, false);
}
options.outPlugin
? options.action(stdout.toString())
: this.showRunResult(stdout, true);
},
// //
showRunResult(content, isSuccess) { showRunResult(content, isSuccess) {
this.isResultShow = true; this.isResultShow = true;
@ -278,6 +279,19 @@ export default {
frameLoad(initHeight) { frameLoad(initHeight) {
this.frameInitHeight = initHeight; this.frameInitHeight = initHeight;
}, },
//
async cacheScript(cmd) {
let html = quickcommand.htmlParse(cmd);
let scriptDoms = html.querySelectorAll("script");
for (let i = 0; i < scriptDoms.length; i++) {
let src = scriptDoms[i].src;
if (!this.urlReg.test(src)) continue;
let dest = window.getQuickcommandTempFile("js", "remoteScript_" + i);
await quickcommand.downloadFile(src, dest);
scriptDoms[i].src = "file://" + dest;
}
return html.documentElement.innerHTML;
},
}, },
unmounted() { unmounted() {
this.stopRun(); this.stopRun();

View File

@ -82,10 +82,21 @@ export default {
frameInit() { frameInit() {
let cfw = this.$refs?.iframe?.contentWindow; let cfw = this.$refs?.iframe?.contentWindow;
if (!cfw) return; if (!cfw) return;
let showError = (...args) => {
quickcommand.showMessageBox(args.join(" "), "error", 0);
};
let showLog = (...args) => {
quickcommand.showMessageBox(args.join(" "), "success", 0);
};
let ctx = { let ctx = {
quickcommand: _.cloneDeep(quickcommand), quickcommand: _.cloneDeep(quickcommand),
utools: _.cloneDeep(utools), utools: _.cloneDeep(utools),
parent: undefined, parent: undefined,
console: {
log: showLog,
error: showError,
},
onerror: (e) => showError(e),
}; };
Object.assign(cfw, ctx); Object.assign(cfw, ctx);
cfw.onload = () => { cfw.onload = () => {

View File

@ -177,7 +177,7 @@ export default {
argvs: imgUrl, argvs: imgUrl,
readfile: false, readfile: false,
}); });
let imgPath = window.getQuickcommandTempFile(imgInfo.ext); let imgPath = window.getQuickcommandTempFile(imgInfo.ext, 'TempImgFile');
quickcommand quickcommand
.downloadFile(imgUrl, imgPath) .downloadFile(imgUrl, imgPath)
.then(() => { .then(() => {

View File

@ -92,6 +92,15 @@ export default {
message: message, message: message,
timeout: time, timeout: time,
position: "top", position: "top",
actions:
time === 0
? [
{
label: "确定",
color: "white",
},
]
: [],
}); });
}, },

View File

@ -138,7 +138,7 @@ interface quickcommandApi {
* ``` * ```
* @param message * @param message
* @param icon success * @param icon success
* @param time 3000 * @param time 3000 0
*/ */
showMessageBox( showMessageBox(
message: string, message: string,
@ -352,18 +352,6 @@ interface quickcommandApi {
*/ */
simulatePaste(); simulatePaste();
/**
*
*/
readClipboard(): text<string>;
/**
*
*
* @param text
*/
writeClipboard(text: string);
/** /**
* uTools * uTools
* *