代码拉取完成,页面将自动刷新
同步操作将从 大菜卵/Aircontroller-scrcpy 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
const log = require('electron-log');
log.transports.file.file = './logs';
const { ipcRenderer, crashReporter } = require('electron');
var net = require("net");
const path = require('path');
const UIAutomator = require('uiautomator-server');
const fs = require("fs");
const LNDB = require('lndb');
const db = new LNDB(path.join(__dirname, '../db'));
const pg = db.init('page');
const token = "sycsky";
const base_url = "http://www.51aigou.com/jeecg-boot";
const adb_path = path.join(__dirname, '../adb/adb.exe');
const app_path = path.join(__dirname, '../libs/ADBKeyBoard.apk');
const crypto = require('crypto');
const os = require('os');
var time;
const md5 = require('md5');
var cmd = require('node-cmd');
const { machineId, machineIdSync } = require('node-machine-id');
const { throws } = require('assert');
const { connectDeviceCommon, connectDeviceByThread } = require('./connecter');
const { scpConnect } = require('./scpConnecter');
const moment = require('moment');
const request = require('request');
const { changeCoordinate } = require('./util/MapMouseUtils');
var robot;
// var robot = require("robotjs");
// var screenSize = robot.getScreenSize();
var screenSize = {height:100,widht:100}
var Winheight = screenSize.height;
var WinWidth = screenSize.width;
// ipcRenderer.send("menu");
var connectDevice, timeOutHandle;
var isOpenThreadConnecter = pg.get("connecter").txt;
var isScp = true;
if (isOpenThreadConnecter) {
isScp = false;
} else {
isScp = true;
}
if (isScp) {
connectDevice = scpConnect;
} else {
connectDevice = connectDeviceCommon;
}
Date.prototype.Format = function (fmt) {
var o = {
'M+': this.getMonth() + 1,
'd+': this.getDate(),
'H+': this.getHours(),
'm+': this.getMinutes(),
's+': this.getSeconds(),
'S+': this.getMilliseconds()
};
//因为date.getFullYear()出来的结果是number类型的,所以为了让结果变成字符串型,下面有两种方法:
if (/(y+)/.test(fmt)) {
//第一种:利用字符串连接符“+”给date.getFullYear()+'',加一个空字符串便可以将number类型转换成字符串。
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(fmt)) {
//第二种:使用String()类型进行强制数据类型转换String(date.getFullYear()),这种更容易理解。
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(String(o[k]).length)));
}
}
return fmt;
};
const workerMap = {};
var devicesInfo = pg.get("devicesInfo").data ? pg.get("devicesInfo").data : {};
var mapRecordTime = 0;
var app = new Vue({
el: '#app',
data: {
visible: false,
page: 1,
isRemoteScript: false,
total: 0,
recording: false,
delay: 10,
welcomeMsg: '',
text: '',
groupName: '',
clients: [],
addTokenCode: '',
controllerClients: [],
screens: [],
reconnectState: {},
controllerGroup: [],
renameMap: {},
renameIndex: -1,
accessToken: {},
rotateState: 0,
renderWidth: 120,
columns2: [
{
type: 'index',
align: 'center'
},
{
type: 'selection',
align: 'center'
},
{
title: '设备名', key: 'client', render(row, column, index) {
return `<div>` + (app.renameMap[row.client] ? app.renameMap[row.client] : row.client) + `</div>`;
}
},
{
title: '设备ID', key: 'client', render(row, column, index) {
return `<div>` + row.client + `</div>`;
}
}, {
title: '状态',
key: 'stateName'
}, {
title: '操作',
key: 'action',
render(row, column, index) {
return `
<i-button size="small" :disabled="${app.reconnectState[row.client] == 1 ? 'false' : 'true'}" type="error" id="${row.client}_rc" @click="$root.reconnect('${row.client}',$event)">重连</i-button>
`;
}
}
],
data2: [],
defaultControllerIndex: -1,
modelStyle: {
width: '80%',
height: '80%'
},
controllerCenterHandler: null,
timeLineContent: '',
comment: '',
conditon: '',
showManager: false,
isShow5: false,
showScriptForm: false,
radius: 1,
loopConfig: false,
showScriptEditer: false,
isHideMouse: false,
data1: [],
msgList: [],
imgSources: [],
imgData: '',
mapRecordName: '',
sendMsg: '',
imgCount: 0,
selected: [],
myIp: getIPAdress(),
timeHandler: null,
focusClient: null,
currentGroup: '',
tableWidth: window.innerWidth,
tableHeight: window.innerHeight - 150,
mouseDow: [],
mouseUp: [],
screensMap: {},
startMouseDownTime: 0,
groupSelect: [],
groupClients: [],
imgsource: '',
mapShow: false,
mapType: 1,
devices: {},
delayScript: '',
swipeR: 0.1,
delayTimeHandle: null,
appOnlyOne: false,
delayScriptTime: 0,
port: 1716,
renameText: '',
mainName: '',
permission: false,
tokenCode: '',
connectMap: {},
connectCount: 0,
addAccessTokenShow: false,
port1: 2888,
containerStyle: { height: window.screen.height - 200 + "px" },
scriptContent: [],
airScriptContent: [],
frameNum: 4,
scriptName: '',
keyMapKey: '',
downFlag: false,
delayControl: false,
isAirScript: false,
rate: 1,
runningForm: {
loopTime: 0,
loopInfinity: 1,
stopScript: false,
isRunning: false,
scriptIndex: -1
},
mainScale: {
width: 0,
height: 0
},
panelConfig: {
scale: 300,
quality: 40,
rate: 40,
remoteIp: '',
groupRate: 5
},
keyMapP: 0, //多点触控索引
linkDeviceCount: 0,
controllerMap: {},
delayCommand: [],
columnScript: [
{
type: 'index',
align: 'center'
},
{
title: '脚本名称', key: 'scriptName'
},
{
title: '操作',
key: 'action',
render(row, column, index) {
return `<i-button size="small" @click="$root.runningScript(${index})"><Icon type="play"></Icon></i-button>
<i-button size="small" @click="$root.loop(${index})"><Icon type="ios-loop-strong"></Icon></i-button>
<i-button size="small" @click="$root.deleteScript(${index})"><Icon type="close"></Icon></i-button>
<i-button size="small" @click="$root.showEdit(${index})"><Icon type="edit"></Icon></i-button>`;
}
}
],
columnAirScript: [
{
type: 'index',
align: 'center'
},
{
title: '脚本名称', key: 'scriptName'
},
{
title: '操作',
key: 'action',
render(row, column, index) {
return `<i-button size="small" @click="$root.runningScript(${index},true)"><Icon type="play"></Icon></i-button>
<i-button size="small" @click="$root.deleteScript(${index},true)"><Icon type="close"></Icon></i-button>
<i-button size="small" @click="$root.showEdit(${index},true)"><Icon type="edit"></Icon></i-button>`;
}
}
],
recordScript: '',
scriptTime: 0,
scriptTimeHandler: null,
mapOpen: false,
mapRecord: false,
currentKeyMap: {},
saveMapRecord: {},
currentMapName: '',
myMapRecord: pg.get("mapRecord").data,
showSaveRecord: false,
mapKeyShow: false,
},
methods: {
refreshApp() {
// app1.reload();
},
controllerLeave(event) {
},
mapRecordChange(event) {
// event.stopPropagation();
if (this.mapRecord == true) {
app.showSaveRecord = true;
}
this.mapRecord = !this.mapRecord;
},
saveRecord() {
if (Object.keys(this.saveMapRecord).length > 0) {
app.myMapRecord = app.myMapRecord ? app.myMapRecord : {};
app.myMapRecord[this.mapRecordName] = this.saveMapRecord;
let tmp = JSON.stringify(app.myMapRecord);
app.myMapRecord = JSON.parse(tmp);
pg.set("mapRecord", app.myMapRecord);
app.showSaveRecord = false;
app.$Message.success("保存成功");
}
$(".mapItem").remove();
this.saveMapRecord = {};
},
mapOpenChange(evnet) {
evnet.stopPropagation();
app.containerWidth = $("#divid").width();
app.containerHeight = $("#divid").height();
this.mapOpen = !this.mapOpen;
if (this.mapOpen) {
app.isHideMouse = (app.currentKeyMap['ML'] != null || app.currentKeyMap['MR'] != null);
if (app.isHideMouse) {
$(".layui-layer-title").eq(0).css('cursor', '');
}
} else {
app.isHideMouse = false;
}
},
excCpy(evt) {
app.keyboard('cp');
},
recordMapScriptChange() {
app.currentKeyMap = app.myMapRecord[app.currentMapName];
},
keyboard(key, e) {
if (e) {
e.stopPropagation();
}
this.sendRemoteCommand({ command: 'keyboard', key: key })
},
exit() {
ipcRenderer.send("close");
},
letRotate(e) {
e.stopPropagation();
if (this.rotateState == 3) {
this.rotateState = 0;
return;
}
this.rotateState += 1;
},
supportInstall(type) {
app.$Message.success("开始安装APP");
switch (type) {
case "keyboard":
try {
app.sendRemoteCommand({ command: 'install', path: path.join(__dirname, '../libs/ADBKeyBoard.apk') });
} catch (error) {
log.log("123");
}
break;
case "airscirpt":
app.sendRemoteCommand({ command: 'install', path: path.join(__dirname, '../libs/AirScript.apk') });
break;
case "aircontrol":
app.sendRemoteCommand({ command: 'install', path: path.join(__dirname, '../libs/AirControl.apk') });
break;
case "uiautomator":
app.sendRemoteCommand({ command: 'install', path: path.join(__dirname, '../libs/app-uiautomator.apk') });
app.sendRemoteCommand({ command: 'install', path: path.join(__dirname, '../libs/app-uiautomator-test.apk') });
break;
default:
break;
}
},
disconnectControllerCenter() {
app.controllerCenterHandler.postMessage("disconnect");
},
closeAccessTokenModel() {
ipcRenderer.send("close");
},
scaleChange(value) {
adbshell(app.mainName, "changeScale", null, { num: value });
},
rateChange(value) {
adbshell(app.mainName, "changeFrame", null, { num: value });
},
qualityChange(value) {
adbshell(app.mainName, "changeQuality", null, { num: value });
},
groupRateChange(value) {
app.sendRemoteCommand({ num: value, command: "changeFrame" });
},
loop(index) {
app.runningForm.scriptIndex = index;
app.loopConfig = true;
},
showEdit(index, flag) {
app.editIndex = index;
app.showScriptEditer = true;
app.isAirScript = flag;
if (flag) {
app.recordScript = app.airScriptContent[index].script;
} else {
app.recordScript = app.scriptContent[index].script;
}
},
saveEdit() {
if (app.isAirScript) {
app.airScriptContent[app.editIndex].script = app.recordScript;
pg.set("airscript", app.airScriptContent);
} else {
app.scriptContent[app.editIndex].script = app.recordScript;
pg.set("script", app.scriptContent);
}
app.$Message.success("保存成功!");
},
saveLoopConfig() {
if (app.runningForm.loopInfinity == 1) {
app.runningScript(app.runningForm.scriptIndex);
} else {
if (app.runningForm.loopTime) {
app.runningScript(app.runningForm.scriptIndex);
} else {
app.$Message.error("循环次数必需大于0");
}
}
},
showTools() {
document.getElementById('tools').style.display = 'block';
},
toolsHide(e) {
e.stopPropagation();
setTimeout(() => {
document.getElementById('tools').style.display = 'none';
}, 500);
},
runningScript(index, flag) {
if (flag) {
if (!app.airScriptContent[index].isRemote) {
fs.writeFileSync(path.resolve("./" + "airscript_temp"), app.airScriptContent[index].script);
app.sendRemoteCommand({ command: 'airscript', isRemote: app.airScriptContent[index].isRemote, });
} else {
app.sendRemoteCommand({ command: 'airscript', isRemote: app.airScriptContent[index].isRemote, msg: app.airScriptContent[index].script })
}
} else {
if (app.runningForm.isRunning) {
app.$Message.error("已经有一个脚本在执行了请先停止");
return;
}
app.loopConfig = false;
app.showManager = false;
app.runningForm.isRunning = true;
if (app.runningForm.scriptIndex != -1) {
if (app.runningForm.loopInfinity == 1) {
eval("async function execScript(){\n while(true){\n" + app.scriptContent[app.runningForm.scriptIndex].script + "}\napp.runningForm.isRunning = false;}\nexecScript();\n");
} else {
eval("async function execScript(){\n for(var i=1;i<=" + app.runningForm.loopTime + ";i++){\n" + app.scriptContent[app.runningForm.scriptIndex].script + "}\napp.runningForm.isRunning = false;}\nexecScript();\n");
}
app.runningForm.scriptIndex = -1;
return;
}
eval("async function execScript(){\n" + app.scriptContent[index].script + "app.runningForm.isRunning = false;\n}\nexecScript();\n");
}
},
deleteScript(index, isAirScript) {
if (isAirScript) {
let scripName = app.airScriptContent[index].scriptName;
let newGroup = [];
for (let i = 0; i < app.airScriptContent.length; i++) {
let item = app.airScriptContent[i];
if (item.scriptName == scripName) {
continue;
}
newGroup.push(item);
}
app.airScriptContent = newGroup;
pg.set("airscript", app.airScriptContent);
} else {
let scripName = app.scriptContent[index].scriptName;
let newGroup = [];
for (let i = 0; i < app.scriptContent.length; i++) {
let item = app.scriptContent[i];
if (item.scriptName == scripName) {
continue;
}
newGroup.push(item);
}
app.scriptContent = newGroup;
pg.set("script", app.scriptContent);
}
app.$Message.success("删除成功");
},
createScript(flag) {
app.showScriptForm = true;
app.isAirScript = flag;
app.recordScript = '';
},
remoteConnect() {
cmd.get(adb_path + " connect " + app.panelConfig.remoteIp, (e, d) => {
app.$Message.success(d);
})
},
saveScript() {
app.isRemoteScript = app.isRemoteScript == 'true' ? true : false;
if (app.isAirScript) {
app.airScriptContent.push({ scriptName: app.scriptName, script: app.recordScript, isRemote: app.isRemoteScript });
pg.set("airScript", app.airScriptContent);
} else {
app.scriptContent.push({ scriptName: app.scriptName, script: app.recordScript });
pg.set("script", app.scriptContent);
}
app.isAirScript = false;
app.showScriptForm = false;
app.$Message.success("保存成功!");
},
record() {
app.recording = !app.recording;
if (!app.recording && app.recordScript) {
clearInterval(app.scriptTimeHandler);
app.showScriptForm = true;
} else {
app.scriptTime = 0;
app.recordScript = "";
app.scriptTimeHandler = setInterval(() => {
app.scriptTime += 30;
}, 30);
}
},
test() {
alert();
},
createGroup() {
try {
if (!app.groupName) {
app.$Message.error("分组不能为空");
return
}
for (let i = 0; i < app.controllerGroup.length; i++) {
let item = app.controllerGroup[i];
//已经有的分组
if (item.group_name == app.groupName) {
let clients = [];
Object.keys(app.controllerMap).forEach(item => {
if (app.controllerMap[item]) {
clients.push(item);
}
app.controllerGroup[i].clients = clients;
});
pg.set("group", app.controllerGroup);
app.$Message.success("保存成功");
return;
}
}
//新的分组
let clients = [];
Object.keys(app.controllerMap).forEach(item => {
if (app.controllerMap[item]) {
clients.push(item);
}
});
app.controllerGroup.push({ group_name: app.groupName, clients: clients });
pg.set("group", app.controllerGroup);
app.$Message.success("保存成功");
} catch (error) {
log.debug(error);
}
},
deleteGroup() {
let newGroup = [];
for (let i = 0; i < app.controllerGroup.length; i++) {
let item = app.controllerGroup[i];
if (item.group_name == app.currentGroup) {
continue;
}
newGroup.push(item);
}
app.controllerGroup = newGroup;
pg.set("group", app.controllerGroup);
app.currentGroup = '';
app.$Message.success("删除成功");
},
rename(id) {
let map = JSON.parse(JSON.stringify(app.renameMap));
map[id] = this.renameText;
this.renameMap = map;
pg.set("rename", this.renameMap);
app.$Message.success("保存成功!");
app.renameIndex = -1;
},
checkPermission() {
try {
let tk = pg.get("accessToken").txt;
if (tk) {
tk = JSON.parse(decrypt(tk));
let encode = JSON.stringify({ token: tk.token, time: new Date().getTime(), deviceId: machineInfo() });
$.post(base_url + "/wx/console/checkBind",{encode:encrypt(encode)})
.then(rs => {
if (rs.success) {
app.permission = false;
app.accessToken = tk;
} else {
app.permission = true;
}
});
}else{
app.permission = true;
}
} catch (error) {
log.error(error);
app.permission = true;
}
},
deleteToGroup(index) {
Array.prototype.indexOf = function (val) {
for (var i = 0; i < this.length; i++) {
if (this[i] == val) return i;
}
return -1;
};
Array.prototype.remove = function (val) {
var index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
let client = app.screens[index];
app.screens[index] = {};
document.getElementById(client.name + "_index").style.display = "none";
app.screensMap[client.name] = null;
app.controllerGroup.forEach(item => {
if (item.group_name == app.currentGroup) {
item.clients.remove(client.name);
// app.screens = item.clients;
}
});
pg.set("group", app.controllerGroup);
app.$Message.success("操作成功");
// app.controllerGroupChange();
},
addController(index) {
let flag = true;
app.controllerClients.forEach(item => {
if (item == app.screens[index].client) {
flag = false;
}
});
if (flag) {
app.controllerClients.push(app.screens[index].client);
}
},
reconnect(device, e) {
app.$Message.success("开始准备重连");
document.getElementById(device + "_rc").disabled = true;
app.reconnectState[device] = 2;
if (timeOutHandle) {
try {
clearTimeout(timeOutHandle);
} catch (error) {
}
}
timeOutHandle = setTimeout(() => {
if (app.reconnectState[device] == 2) {
app.$Message.error("设备连接超时");
app.reconnectState[device] = 1;
}
}, 20000);
if (e) {
e.stopPropagation();
}
try {
cmd.get(adb_path + " reconnect offline", (e, d) => {
cmd.get(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port + " tcp:6612", () => {
log.info("转发完毕:", device);
cmd.get(adb_path + " -s " + device + " shell ANDROID_DATA=/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -L", function (e, d) {
let rp = d.replace(/[\n\r]/g, "");
log.info("lib_info", rp);
log.log(adb_path + " -s " + device + " shell LD_LIBRARY_PATH=" + rp + ":/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -Q 90 -r 40 -P 300");
cmd.get(adb_path + " -s " + device + " shell ANDROID_DATA=/data/local/tmp LD_LIBRARY_PATH=" + rp + ":/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -Q 90 -r 5 -P 300", function (e, d) {
app.reconnectState[device] = 1;
});
});
setTimeout(() => {
app.$Message.success("连接远程服务");
connectDevice(app, device);
}, 5000);
})
});
} catch (error) {
app.$Message.error("无法连接到设备:请重新拔插设备USB或者重启设备");
delete app.devices[device];
}
},
refreshDevices() {
app.$Message.success("开始刷新设备");
if (app.permission) {
alert("请输入卡密,激活软件");
ipcRenderer.send("close");
}
refreshDevicesByScp();
},
checkController(id, event) {
app.controllerMap[id] = !app.controllerMap[id];
event.stopPropagation();
},
async sendRemoteCommand(params, isDelay, delayTime) {
if (app.recording || app.delayControl) {
if (app.delayControl) {
if (app.delayScriptTime >= 10) {
app.recordScript += "await app.sendRemoteCommand(" + JSON.stringify(params) + ",true," + app.delayScriptTime + ");\n";
app.delayScript += "await app.sendRemoteCommand(" + JSON.stringify(params) + ",true," + app.delayScriptTime + ");\n";
app.delayScriptTime = 0;
} else {
app.delayScript += "await app.sendRemoteCommand(" + JSON.stringify(params) + ",true,0);\n";
app.recordScript += "await app.sendRemoteCommand(" + JSON.stringify(params) + ",true,0);\n";
}
return;
} else if (!isDelay) {
if (app.scriptTime >= 30) {
app.recordScript += "await sleep(" + app.scriptTime + ");\n";
app.scriptTime = 0;
}
if (!params.noRecord) {
app.recordScript += "await app.sendRemoteCommand(" + JSON.stringify(params) + ");\n";
}
}
}
if (!isDelay) {
await app.excDelayCommand(app.screens[app.defaultControllerIndex].name);
adbshell(app.screens[app.defaultControllerIndex].name, params.command, null, params);
if (!app.appOnlyOne) {
for (let i = 0; i < app.screens.length; i++) {
let item = app.screens[i];
if (app.screens[app.defaultControllerIndex].name == item.name || !app.controllerMap[item.name]) {
continue;
}
await app.excDelayCommand(item.name);
adbshell(item.name, params.command, null, params);
}
}
app.delayCommand = [];
} else {
if (delayTime) {
app.delayCommand.push({ command: params.command, params: params, delay: delayTime });
} else {
app.delayCommand.push({ command: params.command, params: params });
}
}
},
async excDelayCommand(device) {
if (app.delayCommand.length == 0) return;
for (let i = 0; i < app.delayCommand.length; i++) {
let commandData = app.delayCommand[i];
if (commandData.delay) {
await sleep(commandData.delay);
}
adbshell(device, commandData.command, null, commandData.params);
}
app.scriptTime = 0;
},
controllerSendText() {
if (app.text) {
app.sendRemoteCommand({ text: app.text, command: 'text' });
app.text = '';
} else {
this.keyboard(66);
}
// app.sendRemoteCommand({ text: app.text, command: 'text' });
// app.text = '';
},
sendBack() {
if (!app.text) {
this.keyboard(67);
}
},
addClients() {
app.isShow5 = true;
$("#devices_table").find(".ivu-table-body").eq(0).css("height", "460px");
},
disconnect(deviceId, e) {
if (e) {
e.stopPropagation();
}
try {
app.connectMap[deviceId + "_tc"].terminate();
app.connectMap[deviceId].end();
app.devices[deviceId].disconnect = true;
document.getElementById(deviceId + "_index").style.display = "none";
app.$Message.success("断开成功");
} catch (error) {
log.error(error);
}
},
getController(index, flag, e) {
if (e) {
e.stopPropagation();
}
if (app.mainName) {
app.exitMainControl(index);
}
if (index == -1) {
return;
}
app.appOnlyOne = flag;
app.mainName = app.screens[index].name;
if (app.mainName) {
adbshell(app.mainName, "changeFrame", null, { num: 40 });
let mainCanvas = document.getElementById(app.mainName);
document.getElementById(app.mainName).parentNode.parentNode.style.display = "block";
let dataurl = mainCanvas.toDataURL('image/jpeg', 1);
let copyCanvas = document.getElementsByClassName("main_wm")[0];
let g = copyCanvas.getContext('2d');
var img = new Image();
img.onload = function () {
let mnwm = app.devices[app.mainName].mnwm;
img.style.width = mnwm[0] + "px";
img.style.height = mnwm[1] + "px";
copyCanvas.width = 300;
copyCanvas.height = mnwm[1];
g.drawImage(img, 0, 0, 300, mnwm[1]);
g = null;
img.onload = null;
blob = null;
// img.src = BLANK_IMG;
img = null;
};
img.src = dataurl;
document.getElementById(app.mainName).parentNode.parentNode.style.display = "none";
}
app.defaultControllerIndex = index;
document.getElementById("tools").style.display = 'block';
app.mainLayer = layer.open({
type: 1,
shade: false,
id: "mycontroler",
title: app.renameMap[app.mainName], //不显示标题
area: 'auto',
offset: ['200px', '30px'],
resize: false,
success: function () {
document.getElementById("mycontroler").parentNode.append(document.getElementById("tools"));
},
cancel() {
document.getElementById("divid").append(document.getElementById("tools"));
},
content: $('#divid'), //捕获的元素,注意:最好该指定的元素要存放在body最外层,否则可能被其它的相对元素所影响
end: function () {
app.mainLayer = null;
app.getController(-1, false);
}
});
},
exitMainControl(index) {
if (app.mainName) {
document.getElementById(app.mainName).parentNode.parentNode.style.display = "block";
if (app.mainName) {
let mainCanvas = document.getElementById(app.mainName + "_t");
let context = mainCanvas.getContext('2d');
document.getElementById(app.mainName).parentNode.parentNode.style.display = "block";
let dataurl = mainCanvas.toDataURL('image/jpeg', 1);
let copyCanvas = document.getElementById(app.mainName);
let g = copyCanvas.getContext('2d');
var img = new Image();
img.onload = function () {
let f = 225 / 150;
let height = app.renderWidth * f;
img.width = 300;
img.style.width = 300 + "px";
img.style.height = 300 + "px";
copyCanvas.width = app.renderWidth;
copyCanvas.height = height;
g.drawImage(img, 0, 0, app.renderWidth, height);
g = null;
img.onload = null;
blob = null;
// img.src = BLANK_IMG;
img = null;
if (index == -1) {
var canvas = document.getElementById(app.mainName + "_t");
var g1 = canvas.getContext('2d');
var img1 = new Image();
img1.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
img1.onload = function () {
canvas.width = img1.width;
canvas.height = img1.height;
g1.drawImage(img1, 0, 0);
};
}
};
img.src = dataurl;
adbshell(app.mainName, "changeFrame", null, { num: 5 });
// let imagedata = context.getImageData(0,0,mainCanvas.width,mainCanvas.height);
// copyCanvas.getContext('2d').putImageData(imagedata,0, 0,0,0,mainCanvas.width,mainCanvas.height);
}
app.mainName = '';
return;
}
},
lisenerOnSelect(t) {
app.selected = t;
},
groupOnSelect(t) {
app.groupSelect = t;
},
openDebug() {
ipcRenderer.send("openDebug");
},
groupChange() {
if (app.currentGroup) {
app.controllerGroup.forEach(item => {
if (item == app.currentGroup) {
app.screens = [];
app.screensMap = {};
app.groupClients = item.clients;
}
});
}
},
setRemote() {
for (let i = 0; i < app.groupSelect.length; i++) {
var device = app.groupSelect[i].client;
cmd.run(adb_path + " -s " + device + " tcpip 5555");
// app.refreshGroupDevices(app.groupSelect[i].client);
}
app.$Message.success("设置成功");
},
refreshGroupDevices(deviceId) {
if (app.currentGroup) {
if (app.accessToken.clientNum <= app.screens.length) {
return;
}
app.controllerGroup.forEach(item => {
app.screens.push({ name: item, source: '', wm: app.devices[item].wm });
app.screensMap[item] = app.screens.length - 1;
if (item.group_name == app.currentGroup) {
let newClients = [];
item.clients.map(item => {
if (app.devices[item] == null || app.devices[item].state != 'device') {
return false;
}
newClients.push(item);
});
newClients.forEach((item, index) => {
if (item == deviceId && app.screensMap[item] == null) {
if (!app.renameMap[item]) {
app.renameMap[item] = item;
}
app.screens.push({ name: item, source: '', wm: app.devices[item].wm });
app.screensMap[item] = app.screens.length - 1;
}
});
}
});
}
},
controllerGroupChange() {
if (app.currentGroup) {
if (app.mainLayer) {
layer.close(app.mainLayer);
}
Object.keys(app.controllerMap).forEach(key => {
if (app.controllerMap[key]) {
document.getElementById(key + "_check").getElementsByTagName("input")[0].click();
}
});
app.controllerGroup.forEach(item => {
if (item.group_name == app.currentGroup) {
app.groupName = app.currentGroup;
item.clients.map(item => {
try {
document.getElementById(item + "_check").getElementsByTagName("input")[0].click();
document.getElementById("devices_container").insertBefore(document.getElementById(item + '_index'), document.getElementsByClassName("devices_list")[0]);
} catch (error) {
}
});
}
});
}
},
controllerMove(event) {
if (!app.mouseDow || app.mouseDow.length == 0) return;
if (app.mapOpen && app.isHideMouse) {
return;
}
if (app.mapRecord) {
let remoteX = event.offsetX;
let remoteY = event.offsetY;
let { x, y } = rotationXY(remoteX, remoteY);
app.mapRecordScript += "await sleep(50);";
app.mapRecordScript += " app.sendRemoteCommand({ x: " + x + ", y: " + y + ", command: 'move', p: map.p });;";
return;
}
if (time) {
clearTimeout(time);
time = setTimeout(() => {
var odiv = document.getElementById('divid');
// x = event.clientX;
// y = event.clientY;
// let remoteX = x - odiv.getBoundingClientRect().left;
// let remoteY = y - odiv.getBoundingClientRect().top;
let remoteX = event.offsetX;
let remoteY = event.offsetY;
let { x, y } = rotationXY(remoteX, remoteY);
app.sendRemoteCommand({ x: x, y: y, command: 'move', p: 0 });
time = null;
});
} else {
time = setTimeout(() => {
var odiv = document.getElementById('divid');
// x = event.clientX;
// y = event.clientY;
// let remoteX = x - odiv.getBoundingClientRect().left;
// let remoteY = y - odiv.getBoundingClientRect().top;
let remoteX = event.offsetX;
let remoteY = event.offsetY;
let { x, y } = rotationXY(remoteX, remoteY);
app.sendRemoteCommand({ x: x, y: y, command: 'move', p: 0 });
time = null;
});
}
},
controllerMouseDown(event) {
if (app.mapOpen && app.isHideMouse) {
return;
}
if (event.button == 2) {
if (app.scriptTime >= 30) {
app.recordScript += "await sleep(" + app.scriptTime + ");\n";
app.scriptTime = 0;
}
// app.keyboard(4);
// return;
app.delayControl = true;
if (app.recording) {
}
app.delayTimeHandle = setInterval(() => {
app.delayScriptTime += 10;
}, 10);
}
app.startMouseDownTime = new Date().getTime();
var odiv = document.getElementById('divid');
// let x = event.clientX;
// let y = event.clientY;
// let remoteX = x - odiv.getBoundingClientRect().left;
// let remoteY = y - odiv.getBoundingClientRect().top;
let remoteX = event.offsetX;
let remoteY = event.offsetY;
let { x, y } = rotationXY(remoteX, remoteY);
app.mouseDow = [remoteX, remoteY];
if (app.mapRecord) {
app.mapRecordScript = '';
return;
}
// app.sendRemoteCommand({ command: 'up' });
app.sendRemoteCommand({ x: x, y: y, command: 'click', p: 0 });
setTimeout(() => {
$("#myTextBox").find("input").eq(0).focus();
})
},
addMap() {
if (app.keyMapKey || app.mapType==4) {
let containerWidth = $("#divid").width(), containerHeight = $("#divid").height();
app.mouseDow[0] = app.mouseDow[0] / $("#divid").width();
app.mouseDow[1] = app.mouseDow[1] / $("#divid").height();
app.mouseUp[0] = app.mouseUp[0] / $("#divid").width();
app.mouseUp[1] = app.mouseUp[1] / $("#divid").height();
if (app.mapType == 1) {
if (app.keyMapKey == 'Space') {
app.saveMapRecord['Space'] =
{ x: app.mouseDow[0], y: app.mouseDow[1], code: 'Space', command: 'click', p: app.keyMapP };
} else if (/\d{1}/.test(app.keyMapKey)) {
app.saveMapRecord['Digit' + app.keyMapKey] =
{ x: app.mouseDow[0], y: app.mouseDow[1], code: app.keyMapKey, command: 'click', p: app.keyMapP };
} else {
app.saveMapRecord['Key' + app.keyMapKey] =
{ x: app.mouseDow[0], y: app.mouseDow[1], code: app.keyMapKey, command: 'click', p: app.keyMapP };
}
var item = $("<div class='mapItem'>" + app.keyMapKey + "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.mouseDow[0] - 10 + "px",
"top": containerHeight * app.mouseDow[1] - 10 + "px",
width: '20px',
height: '20px',
background: 'rgba(45,135,225,.7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': '10px',
border: '1px solid'
});
app.mouseDow = null;
$("#divid").append(item);
} else if (app.mapType == 2) {
if (app.keyMapKey == 'Space') {
app.saveMapRecord['Space'] =
{ x: app.mouseDow[0], y: app.mouseDow[1], x1: app.mouseUp[0], y1: app.mouseUp[1], code: app.keyMapKey, command: 'move', p: app.keyMapP };
} else if (/\d{1}/.test(app.keyMapKey)) {
app.saveMapRecord['Digit' + app.keyMapKey] =
{ x: app.mouseDow[0], y: app.mouseDow[1], code: 'Space', command: 'click', p: app.keyMapP };
} else {
app.saveMapRecord['Key' + app.keyMapKey] =
{ x: app.mouseDow[0], y: app.mouseDow[1], x1: app.mouseUp[0], y1: app.mouseUp[1], code: app.keyMapKey, command: 'move', p: app.keyMapP };
}
var item = $("<div class='mapItem'>" + app.keyMapKey + "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.mouseDow[0] - 10 + "px",
"top": containerHeight * app.mouseDow[1] - 10 + "px",
width: '20px',
height: '20px',
background: 'rgba(239, 68, 16, .7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': '10px',
border: '1px solid'
});
var item1 = $("<div class='mapItem'>" + app.keyMapKey + "</div>");
item1.css({
"position": "absolute",
"left": containerWidth * app.mouseUp[0] - 10 + "px",
"top": containerHeight * app.mouseUp[1] - 10 + "px",
width: '20px',
height: '20px',
background: 'rgba(239, 68, 16, .7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': '10px',
border: '1px solid'
});
// $("#divid").append(item);
$("#divid").append(item1);
} else if(app.mapType==3){
app.saveMapRecord['M' + app.keyMapKey] =
{ x: app.mouseDow[0], y: app.mouseDow[1], r: app.radius, code: app.keyMapKey, command: 'M', p: app.keyMapP, rate: app.rate };
var item = $("<div class='mapItem'>" + app.keyMapKey + "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.mouseDow[0] - (app.radius) + "px",
"top": containerHeight * app.mouseDow[1] - (app.radius) + "px",
width: app.radius * 2 + 'px',
height: app.radius * 2 + 'px',
background: 'rgba(194, 63, 226, .7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': app.radius + 'px',
border: '1px solid'
});
app.mouseDow = null;
$("#divid").append(item);
}else{
app.saveMapRecord['control'] =
{ x: app.mouseDow[0], y: app.mouseDow[1], r: app.radius, code: app.keyMapKey, command: 'M', p: app.keyMapP, rate: app.rate };
app.saveMapRecord['control']['KeyW']=[app.mouseDow[0],app.mouseDow[1]-app.radius];
app.saveMapRecord['control']['KeyD']=[app.mouseDow[0]+app.radius,app.mouseDow[1]];
app.saveMapRecord['control']['KeyS']=[app.mouseDow[0],app.mouseDow[1]+app.radius];
app.saveMapRecord['control']['KeyA']=[app.mouseDow[0]-app.radius,app.mouseDow[1]];
var item = $("<div class='mapItem'>" +'方向键'+ "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.mouseDow[0] - (app.radius) + "px",
"top": containerHeight * app.mouseDow[1] - (app.radius) + "px",
width: app.radius * 2 + 'px',
height: app.radius * 2 + 'px',
background: '#009f95',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': app.radius + 'px',
border: '1px solid'
});
app.mouseDow = null;
$("#divid").append(item);
}
app.mapShow = false;
} else {
app.$Message.error("错误的按键");
}
},
mapKeyShowChange() {
app.mapKeyShow = !app.mapKeyShow;
let containerWidth = $("#divid").width(), containerHeight = $("#divid").height();
if (app.mapKeyShow == true) {
for (key in app.currentKeyMap) {
if (app.currentKeyMap[key].command == 'click') {
var item = $("<div class='mapItem'>" + app.currentKeyMap[key].code + "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.currentKeyMap[key].x - 10 + "px",
"top": containerHeight * app.currentKeyMap[key].y - 10 + "px",
width: '20px',
height: '20px',
background: 'rgba(45,135,225,.5)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': '10px',
border: '1px solid'
});
$("#divid").append(item);
} else if (app.currentKeyMap[key].command == 'move') {
var item = $("<div class='mapItem'>" + app.currentKeyMap[key].code + "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.currentKeyMap[key].x - 10 + "px",
"top": containerHeight * app.currentKeyMap[key].y - 10 + "px",
width: '20px',
height: '20px',
background: 'rgba(239, 68, 16, .7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': '10px',
border: '1px solid'
});
var item1 = $("<div class='mapItem'>" + app.currentKeyMap[key].code + "</div>");
item1.css({
"position": "absolute",
"left": containerWidth * app.currentKeyMap[key].x1 - 10 + "px",
"top": containerHeight * app.currentKeyMap[key].y1 - 10 + "px",
width: '20px',
height: '20px',
background: 'rgba(239, 68, 16, .7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': '10px',
border: '1px solid'
});
// $("#divid").append(item);
$("#divid").append(item1);
} else if(key=='control'){
var item = $("<div class='mapItem'>" + '方向键' + "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.currentKeyMap[key].x - (app.currentKeyMap[key].r) + "px",
"top": containerHeight * app.currentKeyMap[key].y - (app.currentKeyMap[key].r) + "px",
width: app.currentKeyMap[key].r * 2 + 'px',
height: app.currentKeyMap[key].r * 2 + 'px',
background: 'rgba(11, 150, 141, .7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': app.currentKeyMap[key].r + 'px',
border: '1px solid'
});
$("#divid").append(item);
}else {
var item = $("<div class='mapItem'>" + app.currentKeyMap[key].code + "</div>");
item.css({
"position": "absolute",
"left": containerWidth * app.currentKeyMap[key].x - (app.currentKeyMap[key].r) + "px",
"top": containerHeight * app.currentKeyMap[key].y - (app.currentKeyMap[key].r) + "px",
width: app.currentKeyMap[key].r * 2 + 'px',
height: app.currentKeyMap[key].r * 2 + 'px',
background: 'rgba(194, 63, 226, .7)',
color: '#fff',
display: 'flex',
'justify-content': 'center',
'align-items': 'center',
'border-radius': app.currentKeyMap[key].r + 'px',
border: '1px solid'
});
$("#divid").append(item);
}
}
} else {
$(".mapItem").remove();
}
},
controllerMouseup1(event) {
if (app.mapOpen) {
app.mapUp(event);
return;
}
if (!app.mouseDow || app.mouseDow.length == 0) {
return;
}
if (app.mapRecord) {
return;
}
app.mouseDow = null;
if (event.button == 2) {
app.delayControl = false;
clearInterval(app.delayTimeHandle);
app.scriptTime = 0;
eval("(async function (){\n" + app.delayScript + "app.runningForm.isRunning = false;\napp.sendRemoteCommand({ command: 'up',noRecord:true });\n})();\n");
app.recordScript += "\napp.sendRemoteCommand({ command: 'up' });\n";
app.delayScript = "";
return;
} else {
app.sendRemoteCommand({ command: 'up', p: 0 });
}
},
controllerMouseup(event) {
if (!app.mouseDow || app.mouseDow.length == 0) {
return;
}
if (app.mapOpen && app.isHideMouse) {
return;
}
if (app.mapRecord) {
let remoteX = event.offsetX;
let remoteY = event.offsetY;
let { x, y } = rotationXY(remoteX, remoteY);
app.mouseUp = [x, y];
app.mapShow = true;
return;
}
app.mouseDow = null;
if (event.button == 2) {
app.delayControl = false;
clearInterval(app.delayTimeHandle);
app.scriptTime = 0;
eval("(async function (){\n" + app.delayScript + "app.runningForm.isRunning = false;\napp.sendRemoteCommand({ command: 'up',noRecord:true });\n})();\n");
app.recordScript += "\napp.sendRemoteCommand({ command: 'up' });\n";
app.delayScript = "";
return;
} else {
app.sendRemoteCommand({ command: 'up', p: 0 });
}
},
timeLineLike() {
if (app.selected.length == 0) {
app.$Message.error('未选中任何客户端');
return;
}
let wxIds = [];
app.selected.forEach(item => {
wxIds.push(item.client);
});
if (this.isTask == '是') {
this.addTask('朋友圈随机点赞', wxIds, '1', this.delay);
} else {
this.sendComand(2, '1', wxIds);
}
},
openSwitch() {
if (app.selected.length == 0) {
app.$Message.error('未选中任何客户端');
return;
}
let wxIds = [];
app.selected.forEach(item => {
wxIds.push(item.client);
});
this.sendComand(3, '1', wxIds);
},
closeSwitch() {
if (app.selected.length == 0) {
app.$Message.error('未选中任何客户端');
return;
}
let wxIds = [];
app.selected.forEach(item => {
wxIds.push(item.client);
});
this.sendComand(4, '1', wxIds);
},
getMainScale() {
app.mainScale.width = app.devices[app.mainName].mnwm[0];
app.mainScale.height = app.devices[app.mainName].mnwm[1];
},
send() {
if (!this.sendMsg) {
alert("不能发送空消息");
return;
}
$.get(base_url + "/wx/log/sendMsg?tk=" + token + "&client=" + encodeURI(this.focusClient.client) + "&msg=" + encodeURI(this.sendMsg) + "&wxId=" + this.focusClient.wx_id).then(rs => {
if (rs.code == 200) {
this.$Message.success('发送成功');
app.msgList.push({
flag: false,
msg: app.sendMsg
});
query.insertDataCommon('t1', { wx_id: app.focusClient.wx_id, msg: app.sendMsg, flag: false, client: app.focusClient.client, wx_name: app.focusClient.wx_name });
app.sendMsg = '';
} else {
this.$Message.error(JSON.stringify(rs));
}
});
},
sendComand(comandCode, params, wxIds) {
/**
* comandCode
* 1:批量同意好友
* 2:随机点赞朋友圈
*/
$.get(base_url + "/wx/log/addCommand?tk=" + token + "&clients=" + encodeURI(wxIds.toString()) + "¶ms=" + params + "&command=" + comandCode).then(rs => {
if (rs.code == 200) {
this.$Message.success('发送成功');
} else {
this.$Message.error(JSON.stringify(rs));
}
});
},
sendImg1(file) {
var reader = new FileReader();
if (file) {
//通过文件流将文件转换成Base64字符串
reader.readAsDataURL(file);
//转换成功后
reader.onloadend = function () {
app.imgSources.push(reader.result.replace("data:image/jpeg;base64,", "").replace("data:image/png;base64,", ""));
app.imgCount = app.imgSources.length;
};
}
return false;
},
sendImg(file) {
//声明js的文件流
var reader = new FileReader();
if (file) {
//通过文件流将文件转换成Base64字符串
reader.readAsDataURL(file);
//转换成功后
reader.onloadend = function () {
//输出结果
$.ajax({
url: base_url + "/wxlog/agImg/add",
type: "post",
dataType: 'json',
data: JSON.stringify({ tk: token, content: ' ', imgData: reader.result.replace("data:image/jpeg;base64,", "").replace("data:image/png;base64,", "") }),
headers: { 'Content-Type': 'application/json;charset=utf8' },
success: function (rs) {
if (rs.code == 200) {
$.ajax(base_url + "/wx/log/sendMsg?tk=" + token + "&client=" + encodeURI(app.focusClient.client) + "&msg=" + "$img" + rs.result + "&wxId=" + app.focusClient.wx_id);
app.$Message.success('发送成功');
app.msgList.push({
flag: false,
msg: '图片[' + rs.result + ']'
});
query.insertDataCommon('t1', { wx_id: app.focusClient.wx_id, msg: '图片[' + rs.result + ']', flag: false, client: app.focusClient.client });
} else {
app.$Message.error(JSON.stringify(rs));
}
}
});
};
}
return false;
},
show(index) {
},
mapMove(event) {
if (!app.mapOpen || !app.mapMouseDown) {
return;
}
if (!app.currentKeyMap[app.mk]) {
return;
}
let xy = changeCoordinate([app.currentKeyMap[app.mk].x * app.containerWidth, app.currentKeyMap[app.mk].y * app.containerHeight], app.mapRoot, [event.screenX, event.screenY], app.currentKeyMap[app.mk].r, app.currentKeyMap[app.mk].rate);
app.sendRemoteCommand({ x: xy[0], y: xy[1], command: 'move', p: parseInt(app.currentKeyMap[app.mk].p) });
},
mapUp($event) {
if (!app.mapOpen) {
return;
}
if (!app.currentKeyMap[app.mk]) {
return;
}
app.mapMouseDown = false;
app.sendRemoteCommand({ command: 'up', p: parseInt(app.currentKeyMap[app.mk].p) });
},
mapDown(event) {
if (!app.mapOpen) {
return;
}
app.mk = 'M' + (event.button == 0 ? 'L' : 'R');
if (!app.currentKeyMap[app.mk]) {
return;
}
app.mapRoot = [WinWidth / 2, Winheight / 2];
let xy = changeCoordinate([app.currentKeyMap[app.mk].x * app.containerWidth, app.currentKeyMap[app.mk].y * app.containerHeight], [event.screenX, event.screenY], [event.screenX, event.screenY], app.currentKeyMap[app.mk].r, app.currentKeyMap[app.mk].rate);
robot.moveMouse(WinWidth / 2, Winheight / 2);
app.sendRemoteCommand({ command: 'click', x: xy[0], y: xy[1], p: parseInt(app.currentKeyMap[app.mk].p) });
app.mapMouseDown = true;
},
openClientList() {
this.isShow1 = true;
app.selected = [];
},
addAccessToken() {
$.post(base_url + "/wx/console/addDevice",{encode:encrypt(JSON.stringify({sourceToken:app.addTokenCode,targetToken:app.accessToken.token,time:new Date().getTime()}))}).then(rs => {
if (rs.success) {
let token = rs.message;
if (token) {
let decodeToken = JSON.parse(decrypt(token));
if (parseInt(decodeToken.exp) > new Date().getTime()) {
// let t1 = (moment(decodeToken.exp).diff(moment(new Date().getTime()), 'days') + 1) * decodeToken.clientNum;
// let t2 = (moment(app.accessToken.exp).diff(moment(new Date().getTime()), 'days') + 1) * app.accessToken.clientNum;
// let totalClient = decodeToken.clientNum + app.accessToken.clientNum;
// let avgDays = parseInt((t1 + t2) / totalClient);
// app.accessToken.clientNum = totalClient;
// app.days = avgDays;
// app.accessToken.exp = new Date(moment(new Date().getTime()).add(avgDays, 'days')).getTime();
// // decodeToken.id = machineIdSync();
pg.set("accessToken", token);
// // app.accessToken = decodeToken;
// // init();
// // app.permission = false;
app.$Message.success("增加设备成功");
ipcRenderer.send("reload");
return;
}
}
} else {
app.$Message.error(rs.message);
return;
}
app.$Message.error("无效的卡密");
})
},
saveAccessToken() {
$.post(base_url + "/wx/console/bindDevice",{encode:encrypt(JSON.stringify({ token: app.tokenCode, time: new Date().getTime(), deviceId: machineInfo() }))}).then(rs => {
if (rs.success) {
let token = rs.message;
if (token) {
let decodeToken = JSON.parse(decrypt(token));
if (parseInt(decodeToken.exp) > new Date().getTime()) {
decodeToken.token = app.tokenCode;
pg.set("accessToken", encrypt(JSON.stringify(decodeToken)));
app.accessToken = decodeToken;
ipcRenderer.send("reload");
app.permission = false;
return;
}
}
} else {
app.$Message.error(rs.message);
return;
}
app.$Message.error("无效的卡密");
})
},
load: load,
inputFocus(e) {
e.toElement.focus();
// alert();
},
getGroup: () => {
setTimeout(() => {
let data = pg.get('group').data ? pg.get('group').data : [];
app.renameMap = pg.get("rename").data ? pg.get("rename").data : {};
app.controllerGroup = Object.keys(data).length == 0 ? [] : data;
let scripts = pg.get("script").data;
app.scriptContent = scripts ? scripts : [];
let airScripts = pg.get("airScript").data;
app.airScriptContent = airScripts ? airScripts : [];
}, 1000);
}
},
watch: {
permission(newval, old) {
if (newval) {
setTimeout(() => {
$(".ivu-modal-wrap").eq(0).css({ "top": '100px', "bottom": '0px', "right": '0px', "left": '0px' });
}, 500);
}
}
},
created: function () {
setTimeout(() => {
init();
app.checkPermission();
}, 2000);
},
mounted() {
}
});
function init() {
workerMap['deviceInfo'] = new Worker('devicesWorker.js');
workerMap['deviceInfo'].onmessage = function (event) {
if (event.data.permission) {
app.permission = event.data.permission;
} else {
app.data2 = event.data;
}
};
try {
app.controllerCenterHandler = new Worker('AirControllerCenter.js');
app.controllerCenterHandler.onmessage = (m) => {
var commands = m.data.split(" ");
switch (commands[0]) {
case "d":
app.sendRemoteCommand({ x: commands[1], y: commands[2], command: 'click', p: 0 });
break;
case "u":
app.sendRemoteCommand({ command: 'up', p: 0 });
break;
case "m":
app.sendRemoteCommand({ x: commands[1], y: commands[2], command: 'move', p: 0 });
break;
default:
break;
}
};
} catch (error) {
}
app.getGroup();
// setInterval(() => {
// app.checkPermission();
// }, 30000);
var buf = '';
var contentLength = 0;
// setTimeout(() => {
// app.checkPermission();
// }, 5000);
}
function loadDevices() {
app.data2 = [];
cmd.get(adb_path + " start-server", (e, d1, s) => {
cmd.get(adb_path + " devices", (e, d, s) => {
res = d.split("\n");
res.forEach((item, index) => {
if (index < 1 || !(item.replace(/[ ]*/g, '')) || item.length == 1) {
return;
}
var device = item.split(" ")[0];
app.data2.push({ client: device });
if (!app.devices[device]) {
app.devices[device] = {
port: app.port,
index: app.screens.length,
id: device,
};
app.port++;
cmd.get(adb_path + " -s " + item.split(" ")[0] + " forward tcp:" + app.devices[device].port + " localabstract:minicap", () => {
// connectDevice(device);
try {
adbshell(device, 'size', (d) => {
app.devices[device].wm = d;
})
} catch (error) {
log.error(error);
}
});
}
})
});
})
}
function changeScreenPoint(point, target) {
// let x = 400, y = 800;
let x, y;
// if (app.devices[app.mainName].wm[0] > app.devices[app.mainName].wm[1]) {
// x = app.devices[app.mainName].mnwm[1], y = app.devices[app.mainName].mnwm[0];
// } else {
// x = app.devices[app.mainName].mnwm[0], y = app.devices[app.mainName].mnwm[1];
// }
x = app.devices[app.mainName].mnwm[0], y = app.devices[app.mainName].mnwm[1];
return [point[0] / x * target[0], point[1] / y * target[1]];
}
function adbshell(device, type, callback, extend) {
if (app.runningForm.isRunning && app.runningForm.stopScript) {
app.runningForm.isRunning = false;
app.runningForm.stopScript = false;
throw {};
}
try {
if (!app.devices[device]) {
return;
}
if (type == 'size') {
cmd.get(adb_path + " -s " + device + " shell wm size", function (e, d, s) {
// log.debug(d);
callback(d.split("\n")[0].split(": ")[1].split("x"));
});
}
if (type == 'click') {
let point = changeScreenPoint([extend.x, extend.y], app.devices[device].wm);
// app.connectMap[device + "_tc"].postMessage("u 0 \n");
// app.connectMap[device + "_tc"].postMessage("c\n");
// app.connectMap[device + "_tc"].postMessage("d 0 " + parseInt(point[0]) + " " + parseInt(point[1]) + " 50\n");
app.connectMap[device + "_tc"].postMessage(["d", extend.p, parseInt(point[0]), parseInt(point[1]), 50]);
// app.connectMap[device + "_tc"].postMessage("c\n");
}
if (type == 'uploadFile') {
cmd.get(adb_path + " -s " + device + " shell mkdir /sdcard/ac_upload ", (a, d, b) => {
let paths = extend.path.split("\\");
cmd.run(adb_path + " -s " + device + " push " + extend.path + " /sdcard/ac_upload/" + paths[paths.length - 1]);
});
}
if (type == 'install') {
cmd.get(adb_path + " -s " + device + " install " + extend.path, (a, d, b) => {
if (/Success/.test(d)) {
app.$Message.success(app.renameMap[device] + ":安装app成功");
} else {
app.$Message.error(app.renameMap[device] + ":安装app失败");
}
});
}
if (type == 'changeFrame') {
app.connectMap[device + "_tc"].postMessage(["f", extend.num]);
}
if (type == 'changeScale') {
app.connectMap[device + "_tc"].postMessage(["s", extend.num]);
}
if (type == 'changeQuality') {
app.connectMap[device + "_tc"].postMessage(["q", extend.num]);
}
if (type == 'airscript') {
if (extend.isRemote) {
cmd.get(adb_path + " -s " + device + " shell am broadcast -a ADB_EXECUTE_AS_SCRIPTE --es msg '" + extend.msg + "'", (e, d) => {
log.debug(e);
});
} else {
cmd.get(adb_path + " -s " + device + " push " + path.resolve("./" + "airscript_temp") + " /sdcard/actmp.js", (e, d) => {
cmd.get(adb_path + " -s " + device + " shell am broadcast -a ADB_EXECUTE_AS_SCRIPTE --es file '/sdcard/actmp.js'", (e, d) => {
log.debug(e);
});
});
}
}
if (type == 'up') {
app.connectMap[device + "_tc"].postMessage(["u", extend.p]);
}
if (type == 'move') {
let point = changeScreenPoint([extend.x, extend.y], app.devices[device].wm);
app.connectMap[device + "_tc"].postMessage(["m", extend.p, parseInt(point[0]), parseInt(point[1]), 100]);
// cmd.get(adb_path + " -s " + device + " shell input tap " + point[0] + " " + point[1], () => { })
}
if (type == 'swipe') {
let point1 = changeScreenPoint([extend.x1, extend.y1], app.devices[device].wm);
let point2 = changeScreenPoint([extend.x2, extend.y2], app.devices[device].wm);
cmd.get(adb_path + " -s " + device + " shell input swipe " + point1[0] + " " + point1[1] + " " + point2[0] + " " + point2[1] + " " + extend.time, () => { });
}
if (type == 'text') {
// cmd.get(adb_path + " -s " + device + " shell input text " + extend.text, () => { })
cmd.get(adb_path + " -s " + device + " shell am broadcast -a ADB_INPUT_TEXT --es msg '" + extend.text + "'", (a, d, b) => {
});
}
if (type == 'keyboard') {
let key = extend.key;
let a, b, c;
if (key == 'cap') {
// cmd.get(adb_path + " -s " + device + " shell input text " + extend.text, () => { })
cmd.get(adb_path + " -s " + device + " shell screencap -p /sdcard/ac_screen.png");
}
if (key == 'capToPc') {
// cmd.get(adb_path + " -s " + device + " shell input text " + extend.text, () => { })
cmd.get(adb_path + " -s " + device + " shell screencap -p /sdcard/ac_screen.png", (a, d, b) => {
cmd.get(adb_path + " -s " + device + " pull sdcard/ac_screen.png " + path.join(__dirname, '../screen/' + app.renameMap[device] + new Date().getTime() + ".png"))
});
}
if (key == 'back') {
app.connectMap[device + "_tc"].postMessage(["ul"]);
}
if (key == 'cp') {
app.connectMap[device + "_tc"].postMessage(["cp", app.text]);
}
if (key == 'lock' || key == 'open') {
if (key == 'lock') {
app.connectMap[device + "_tc"].postMessage(["l"]);
} else if (key == 'open') {
app.connectMap[device + "_tc"].postMessage(["ul"]);
}
// new Promise(resolve => {
// cmd.get(adb_path + ' -s ' + device + ' shell dumpsys window policy |find "mScreenOnFully"', function (e, d) {
// try {
// a = new Boolean(d.split("mScreenOnFully=")[1].replace(/[\n\r]/g, "") == 'true').valueOf();
// } catch (error) {
// }
// cmd.get(adb_path + ' -s ' + device + ' shell dumpsys window policy |find "mScreenOnEarly"', function (e, d) {
// try {
// b = new Boolean(d.split("mScreenOnEarly=")[1].replace(/[\n\r]/g, "") == 'true').valueOf();
// } catch (error) {
// }
// cmd.get(adb_path + ' -s ' + device + ' shell dumpsys window policy |find "mOrientationSensorEnabled"', function (e, d) {
// try {
// c = new Boolean(d.split("mOrientationSensorEnabled=")[1].replace(/[\n\r]/g, "") == 'true').valueOf();
// } catch (error) {
// }
// resolve();
// });
// });
// });
// }).then(() => {
// if (key == 'lock') {
// if ((a || b || c)) {
// extend.key = 26;
// } else {
// return;
// }
// }
// if (key == 'open') {
// if ((a || b || c)) {
// return;
// } else {
// extend.key = 26;
// }
// }
// cmd.get(adb_path + " -s " + device + " shell input keyevent " + extend.key, () => { });
// });
} else {
app.connectMap[device + "_tc"].postMessage(["k", extend.key]);
// cmd.get(adb_path + " -s " + device + " shell input keyevent " + extend.key, () => { });
}
if (key == 'close') {
// cmd.get(adb_path + " -s " + device + " shell input text " + extend.text, () => { })
cmd.get(adb_path + " -s " + device + " shell reboot -p", (a, d, b) => {
});
}
if (key == 'reboot') {
// cmd.get(adb_path + " -s " + device + " shell input text " + extend.text, () => { })
cmd.get(adb_path + " -s " + device + " shell reboot", (a, d, b) => {
});
}
}
if (type == 'device_info') {
cmd.get(adb_path + " -s " + device + " shell \"getprop ro.product.cpu.abi", function (e, d, s) {
app.devices[device].cpu = d.split("\n")[0];
cmd.get(adb_path + " -s " + device + " shell \"getprop ro.build.version.sdk", function (e, d, s) {
// log.debug(d);
app.devices[device].version = d.split("\n")[0];
callback();
});
});
}
if (type == 'scp') {
cmd.get(adb_path + " -s " + device + " push " + path.join(__dirname, '../libs/srcp/scrcpy-server.jar') + " /data/local/tmp", () => {
cmd.get(adb_path + " -s " + device + " push " + path.join(__dirname, '../libs/srcp/' + app.devices[device].cpu + "/libcompress.so") + " /data/local/tmp", () => {
cmd.get(adb_path + " -s " + device + " push " + path.join(__dirname, '../libs/srcp/' + app.devices[device].cpu + "/libturbojpeg.so") + " /data/local/tmp", () => {
cmd.get(adb_path + " -s " + device + " shell chmod 777 /data/local/tmp/scrcpy-server.jar", function (e, d, s) {
callback();
});
});
});
});
}
if (type == 'minicap') {
cmd.get(adb_path + " -s " + device + " push " + path.join(__dirname, '../libs/' + app.devices[device].cpu + "/minicap") + " /data/local/tmp", () => {
cmd.get(adb_path + " -s " + device + " push " + path.join(__dirname, '../libs/android-' + app.devices[device].version + "/" + app.devices[device].cpu + "/minicap.so") + " /data/local/tmp", () => {
cmd.get(adb_path + " -s " + device + " push " + path.join(__dirname, '../libs/touch/' + app.devices[device].cpu + "/minitouch") + " /data/local/tmp", () => {
cmd.run(adb_path + " -s " + device + " shell chmod 0755 /data/local/tmp/minitouch");
});
cmd.get(adb_path + " -s " + device + " shell chmod 0755 /data/local/tmp/minicap", function (e, d, s) {
callback();
});
});
});
}
} catch (error) {
}
}
function loadMainImg(buf, canvas, deviceId) {
var flag = false;
if (!canvas) return;
var g = canvas.getContext('2d');
var BLANK_IMG = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
var blob = new Blob([buf], { type: 'image/jpeg' });
var URL = window.URL || window.webkitURL;
var img = new Image();
app.controllerCenterHandler.postMessage(buf);
var u = URL.createObjectURL(blob);
img.onload = function () {
flag = img.width > img.height;
app.devices[deviceId].mnwm = [img.width, img.height];
if (flag && app.devices[deviceId].wm[0] < app.devices[deviceId].wm[1]) {
var tmp = app.devices[deviceId].wm[1];
app.devices[deviceId].wm[1] = app.devices[deviceId].wm[0];
app.devices[deviceId].wm[0] = tmp;
app.connectMap[deviceId + "_tc"].postMessage({ data: app.devices[deviceId], event: 'update' });
} else if (!flag && app.devices[deviceId].wm[0] > app.devices[deviceId].wm[1]) {
var tmp = app.devices[deviceId].wm[1];
app.devices[deviceId].wm[1] = app.devices[deviceId].wm[0];
app.devices[deviceId].wm[0] = tmp;
app.connectMap[deviceId + "_tc"].postMessage({ data: app.devices[deviceId], event: 'update' });
}
if (app.rotateState != 0) {
switch (app.rotateState) {
case 1:
canvas.width = img.height;
canvas.height = img.width;
g.rotate(90 * Math.PI / 180);
g.drawImage(img, 0, -img.height);
break;
case 2:
canvas.width = img.width;
canvas.height = img.height;
g.rotate(180 * Math.PI / 180);
g.drawImage(img, -img.width, -img.height);
break;
case 3:
canvas.width = img.height;
canvas.height = img.width;
g.rotate(270 * Math.PI / 180);
g.drawImage(img, -img.width, 0);
break;
}
} else {
canvas.width = img.width;
canvas.height = img.height;
g.rotate(0 * Math.PI / 180);
g.drawImage(img, 0, 0);
}
img.onload = null;
// img.src = BLANK_IMG;
URL.revokeObjectURL(u);
img = null;
u = null;
blob = null;
buf = null;
};
img.src = u;
return flag
}
function loadImg(buf, canvas, deviceId) {
var flag = false;
if (!canvas) return;
var g = canvas.getContext('2d');
var BLANK_IMG = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
var blob = new Blob([buf], { type: 'image/jpeg' });
var URL = window.URL || window.webkitURL;
var img = new Image();
var u = URL.createObjectURL(blob);
img.onload = function () {
flag = img.width > img.height;
if (flag && app.devices[deviceId].wm[0] < app.devices[deviceId].wm[1]) {
var tmp = app.devices[deviceId].wm[1];
app.devices[deviceId].wm[1] = app.devices[deviceId].wm[0];
app.devices[deviceId].wm[0] = tmp;
app.connectMap[deviceId + "_tc"].postMessage({ data: app.devices[deviceId], event: 'update' });
} else if (!flag && app.devices[deviceId].wm[0] > app.devices[deviceId].wm[1]) {
var tmp = app.devices[deviceId].wm[1];
app.devices[deviceId].wm[1] = app.devices[deviceId].wm[0];
app.devices[deviceId].wm[0] = tmp;
app.connectMap[deviceId + "_tc"].postMessage({ data: app.devices[deviceId], event: 'update' });
}
let f = 225 / 150;
let height = app.renderWidth * f;
if (flag) {
canvas.width = height;
canvas.height = app.renderWidth;
g.drawImage(img, 0, 0, height, app.renderWidth);
} else {
canvas.width = app.renderWidth;
canvas.height = height;
g.drawImage(img, 0, 0, app.renderWidth, height);
}
g = null;
img.onload = null;
URL.revokeObjectURL(u);
u = null;
blob = null;
// img.src = BLANK_IMG;
img = null;
};
img.src = u;
return flag
}
// function connectDevice(deviceId) {
// if (app.connectMap[deviceId]) {
// try {
// app.connectMap[deviceId].terminate();
// app.connectMap[deviceId + "_tc"].terminate();
// } catch (error) {
// log.error(error);
// }
// }
// var count = 1;
// app.connectMap[deviceId] = new Worker('deviceConnectWorker.js');
// app.connectMap[deviceId].postMessage(app.devices[deviceId]);
// app.connectMap[deviceId].onmessage = (event) => {
// try {
// var canvas = document.getElementById(event.data.device + "_t");
// if(canvas){
// loadMainImg(event.data.buf, canvas);
// }else{
// if(count>=app.frameNum){
// count = 1;
// }else{
// canvas = document.getElementById(event.data.device);
// loadImg(event.data.buf, canvas);
// count++;
// }
// }
// delete event.data;
// event = null;
// } catch (error) {
// log.error(error);
// }
// };
// app.connectMap[deviceId + "_tc"] = new Worker('deviceTouchWorker.js');
// app.connectMap[deviceId + "_tc"].postMessage({ event: 'connect', data: app.devices[deviceId] });
// }
function refreshDevicesByScp() {
// let stateMap = {
// device: '已连接',
// offline: '无法链接',
// unauthorized: '未授权'
// };
// app.data2 = [];
pms = [];
cmd.get(adb_path + " reconnect offline", (e, d) => {
cmd.get(adb_path + " devices", (e, d, s) => {
let res = d.split("\n");
res.forEach((item, index) => {
if (index < 1 || !(item.replace(/[ ]*/g, '')) || item.length == 1) {
return
}
var deviceInfo = item.replace("\r", "").split(" ");
var device = deviceInfo[0];
// if (!app.devices[device] || !(app.devices[device].cpu) || !(app.devices[device].state == 'device') || app.devices[device].disconnect) {
if (app.reconnectState[device] != 2 && app.reconnectState[device] != 3) {
if (!devicesInfo[device]) {
app.devices[device] = {};
// app.data2.push({ client: device, stateName: stateMap[deviceInfo[1]] });
app.devices[device] = {
port: app.port,
port1: app.port1,
index: app.screens.length,
id: device,
state: deviceInfo[1]
// stateName: stateMap[deviceInfo[1]]
};
if (app.devices[device].state != 'device') {
return;
}
cmd.get(adb_path + " -s " + device + " shell pm list packages -3", (e, d) => {
if (d.indexOf('adbkeyboard') >= 0) {
log.log("已安装");
} else {
cmd.run(adb_path + " -s " + device + " install " + app_path);
}
});
app.port++;
app.port1++;
pms.push(new Promise(resolve => {
app.reconnectState[device] = 2;
log.log("请求转发:tcp{}", app.devices[device].port);
// cmd.run(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port1 + " localabstract:minitouch");
cmd.get(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port + " tcp:6612", () => {
log.log("请求转发完毕", device);
try {
adbshell(device, 'size', (d) => {
d[0] = parseInt(d[0]);
d[1] = parseInt(d[1]);
app.devices[device].wm = d;
adbshell(device, 'device_info', () => {
adbshell(device, 'scp', () => {
setTimeout(() => {
app.devices[device].mnwm = [300, 300 / parseInt(d[0]) * d[1]];
timeOutHandle = setTimeout(() => {
if (app.reconnectState[device] == 2) {
log.log("time out:", device);
app.reconnectState[device] = 1;
}
}, 25000);
// connectDevice(app, device);
cmd.get(adb_path + " -s " + device + " shell ANDROID_DATA=/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -L", function (e, d) {
let rp = d.replace(/[\n\r]/g, "");
if (rp == null || rp.indexOf("Aborted") >= 0 || rp == '') {
App.$Message.error("初始化启动失败");
log.log("获取路径失败:" + rp);
return;
}
app.devices[device].libInfo = rp;
log.log("lib_info:", device, rp);
log.log(adb_path + " -s " + device + " shell LD_LIBRARY_PATH=" + rp + ":/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -Q 90 -r 40 -P 300");
cmd.get(adb_path + " -s " + device + " shell ANDROID_DATA=/data/local/tmp LD_LIBRARY_PATH=" + rp + ":/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -Q 90 -r 5 -P 300", function (e, d) {
app.reconnectState[device] = 1;
});
setTimeout(() => {
log.log("开始连接", device);
connectDevice(app, device);
}, 5000);
});
}, 4000);
});
});
resolve();
});
} catch (error) {
resolve();
log.error(error);
}
});
}));
} else {
log.log("发现已记录设备,跳过信息收集步骤{}", device);
app.devices[device] = devicesInfo[device];
app.devices[device].port = app.port;
app.devices[device].port1 = app.port1;
app.port++;
app.port1++;
app.reconnectState[device] = 2;
log.log("请求转发:tcp{}", app.devices[device].port);
cmd.get(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port + " tcp:6612", () => {
log.log("请求转发完毕", device);
setTimeout(() => {
if (app.reconnectState[device] == 2) {
log.log("time out:", device);
app.reconnectState[device] = 1;
}
}, 25000);
log.log(adb_path + " -s " + device + " shell LD_LIBRARY_PATH=" + devicesInfo[device].libInfo + ":/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -Q 90 -r 40 -P 300");
cmd.get(adb_path + " -s " + device + " shell ANDROID_DATA=/data/local/tmp LD_LIBRARY_PATH=" + devicesInfo[device].libInfo + ":/data/local/tmp CLASSPATH=/data/local/tmp/scrcpy-server.jar app_process / com.genymobile.scrcpy.Server -Q 90 -r 5 -P 300", function (e, d) {
app.reconnectState[device] = 1;
});
setTimeout(() => {
log.log("开始连接远程服务", device);
connectDevice(app, device);
}, 5000);
});
}
}
// else {
// app.data2.push({ client: device, stateName: stateMap[deviceInfo[1]] });
// }
});
});
});
}
function refreshDevicesByCp() {
let stateMap = {
device: '已连接',
offline: '无法链接',
unauthorized: '未授权'
};
app.data2 = [];
pms = [];
cmd.get(adb_path + " devices", (e, d, s) => {
let res = d.split("\n");
res.forEach((item, index) => {
if (index < 1 || !(item.replace(/[ ]*/g, '')) || item.length == 1) {
return
}
var deviceInfo = item.replace("\r", "").split(" ");
var device = deviceInfo[0];
if (!app.devices[device] || !(app.devices[device].cpu) || !(app.devices[device].state == 'device')) {
app.devices[device] = {};
app.data2.push({ client: device, stateName: stateMap[deviceInfo[1]] });
app.devices[device] = {
port: app.port,
port1: app.port1,
index: app.screens.length,
id: device,
state: deviceInfo[1],
stateName: stateMap[deviceInfo[1]]
};
if (app.devices[device].state != 'device') {
return;
}
cmd.get(adb_path + " -s " + device + " shell pm list packages -3", (e, d) => {
if (d.indexOf('adbkeyboard') >= 0) {
log.debug("已安装");
} else {
cmd.run(adb_path + " -s " + device + " install " + app_path);
}
});
app.port++;
app.port1++;
pms.push(new Promise(resolve => {
cmd.run(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port1 + " localabstract:minitouch");
cmd.get(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port + " localabstract:minicap", () => {
try {
adbshell(device, 'size', (d) => {
app.devices[device].wm = d;
adbshell(device, 'device_info', () => {
adbshell(device, 'minicap', () => {
setTimeout(() => {
d[1] = d[1].replace("\r", "");
app.devices[device].mnwm = [300, 300 / parseInt(d[0]) * d[1]];
cmd.get(adb_path + " -s " + device + " shell /data/local/tmp/minitouch", (e, d1) => {
let data = d1.match(/\d+x\d+/g);
if (data == null && e != null) {
data = e.toString().match(/\d+x\d+/g);
}
if (data) {
data.forEach(item => {
if (item.length > 8) {
app.devices[device].wm = item.split("x");
}
});
}
});
cmd.get(adb_path + " -s " + device + " shell /data/local/tmp/minitouch", (e, d1) => {
let data = d1.match(/\d+x\d+/g);
if (data == null && e != null) {
data = e.toString().match(/\d+x\d+/g);
}
if (data) {
data.forEach(item => {
if (item.length > 8) {
app.devices[device].wm = item.split("x");
}
});
}
});
cmd.run(adb_path + " -s " + device + " shell LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -P " + parseInt(d[0]) + "x" + parseInt(d[1]) + "@400x" + parseInt(parseInt(d[0]) / 400 * parseInt(d[1])) + "/0");
setTimeout(() => {
connectDevice(app, device);
// app.refreshGroupDevices(device);
}, 2000);
}, 4000);
});
});
resolve();
});
} catch (error) {
resolve();
log.error(error);
}
});
}));
} else {
app.data2.push({ client: device, stateName: stateMap[deviceInfo[1]] });
}
})
});
}
// $("#divid").scroll(function(){
// });
function decrypt(encrypt_text, iv) {
var key = new Buffer('12345668');
var iv = new Buffer(iv ? iv : 0);
var decipher = crypto.createDecipheriv('des-ecb', key, iv);
decipher.setAutoPadding(true);
var txt = decipher.update(encrypt_text, 'base64', 'utf8');
txt += decipher.final('utf8');
return txt;
}
function encrypt(plaintext, iv) {
var key = new Buffer('12345668');
var iv = new Buffer(iv ? iv : 0);
var cipher = crypto.createCipheriv('des-ecb', key, iv);
cipher.setAutoPadding(true);
var ciph = cipher.update(plaintext, 'utf8', 'base64');
ciph += cipher.final('base64');
return ciph;
}
async function load() {
var sheets = xlsx.parse('./dataTable.xlsx');
var data = sheets[5].data;
// log.debug(data[547]);
for (var i = 6; i < data.length; i++) {
log.debug(i);
await query.saveData(data[i]);
}
}
async function test() {
for (var i = 100; i < 200; i++) {
await sleep(3000);
log.debug(i);
app.keyboard(i);
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
// 异常捕获
window.onerror = function (message, source, lineno, colno, err) {
log.error(err.stack || err);
};
process.on('unhandledRejection', function (err) {
log.error(err.stack);
});
window.onunhandledrejection = function (e) {
log.error(e.reason);
};
process.on('uncaughtException', function (err) {
log.error(err.stack);
});
let container = document.getElementById("divid");
container.addEventListener("drop", (e) => {
e.preventDefault(); //阻止e的默认行为
const files = e.dataTransfer.files;
if (files && files.length >= 1) {
const path = files[0].path;
log.log("file:", path);
if (/\.apk/.test(path)) {
app.sendRemoteCommand({ command: 'install', path: path });
} else {
app.sendRemoteCommand({ command: 'uploadFile', path: path });
app.$Message.success("文件成功上传到:/sdcard/ac_upload");
}
}
});
container.addEventListener("dragover", (e) => {
e.preventDefault();
});
var lastKeyDowMap = {};
var lastMove = {};
var moveStack = {};
document.addEventListener("keydown", async (e) => {
if (!app.mapOpen || lastKeyDowMap[e.code]) {
return;
}
if('KeyWKeyDKeySKeyA'.indexOf(e.code)>=0 && app.currentKeyMap['control']){
controlDown(e.code,app.currentKeyMap['control']);
return;
}
lastKeyDowMap[e.code] = true;
if (app.currentKeyMap[e.code]) {
let map = app.currentKeyMap[e.code];
switch (map.command) {
case 'click':
app.sendRemoteCommand({ x: map.x * app.containerWidth, y: map.y * app.containerHeight, command: 'click', p: map.p });
break;
case 'move':
if (lastMove["p" + map.p]) {
lastMove["p" + map.p] ++;
moveStack["p" + map.p].push({ x: map.x1 * app.containerWidth, y: map.y1 * app.containerHeight, command: 'move', p: map.p });
await app.sendRemoteCommand({ x: map.x1 * app.containerWidth, y: map.y1 * app.containerHeight, command: 'move', p: map.p });
break;
}
lastMove["p" + map.p] = 1;
moveStack["p" + map.p]= [{ x: parseInt(map.x1 * app.containerWidth), y: map.y1 * app.containerHeight, command: 'move', p: map.p }];
await app.sendRemoteCommand({ x: map.x * app.containerWidth, y: map.y * app.containerHeight, command: 'click', p: map.p });
await sleep(40);
await app.sendRemoteCommand({ x: parseInt(map.x1 * app.containerWidth), y: map.y1 * app.containerHeight, command: 'move', p: map.p });
// await app.sendRemoteCommand({ x: map.x, y: map.y, command: 'click', p: map.p });
// eval('async function exsc(){'+map.script+"}; exsc();");
break;
default:
break;
}
}
});
document.addEventListener("keyup", (e) => {
if (e.code == 'F6') {
$("#openMyMap").click();
}
if (!app.mapOpen) {
return;
}
if('KeyWKeyDKeySKeyA'.indexOf(e.code)>=0 && app.currentKeyMap['control']){
controlUp(e.code,app.currentKeyMap['control']);
return;
}
lastKeyDowMap[e.code] = false;
if (app.currentKeyMap[e.code]) {
let map = app.currentKeyMap[e.code];
lastMove["p" + map.p]--;
if(lastMove["p" + map.p] == 0){
app.sendRemoteCommand({ command: 'up', p: map.p });
}
}
});
var downCount = 0;
var keyStack = {};
async function controlDown(code,data){
if(keyStack[code]){
return;
}
// console.debug(keyStack);
// console.debug(code);
// console.debug(downCount);
var p;
downCount++;
var p0 = [data.x * app.containerWidth, data.y * app.containerHeight];
var pmap = {};
data.r = parseInt(data.r);
pmap['KeyW']=[p0[0],p0[1]-data.r];
pmap['KeyD']=[p0[0]+data.r,p0[1]];
pmap['KeyS']=[p0[0],p0[1]+data.r];
pmap['KeyA']=[p0[0]-data.r,p0[1]];
if(Object.keys(keyStack).length==1){
var p1 = pmap[Object.keys(keyStack)[0]];
var p2 = pmap[code];
p = [p1[0]+((p2[0] - p1[0])/2),p1[1]+((p2[1] - p1[1])/2)];
keyStack[code] = p2
}else{
p = pmap[code];
await app.sendRemoteCommand({ x: p0[0], y: p0[1], command: 'click', p: data.p });
await sleep(40);
keyStack[code] = p
}
await app.sendRemoteCommand({ x:p[0], y: p[1], command: 'move', p: data.p });
}
async function controlUp(code,data){
delete keyStack[code];
if(downCount==2){
var p = keyStack[Object.keys(keyStack)[0]];
console.debug(p);
await app.sendRemoteCommand({ x: p[0], y: p[1], command: 'move', p: data.p });
}else if(downCount==1){
app.sendRemoteCommand({ command: 'up', p: data.p });
}
downCount--;
}
///获取本机ip///
function getIPAdress() {
var interfaces = os.networkInterfaces();
for (var devName in interfaces) {
var iface = interfaces[devName];
for (var i = 0; i < iface.length; i++) {
var alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
return alias.address;
}
}
}
}
function machineInfo() {
return md5(os.hostname() + os.endianness() + os.type() + os.platform() + os.totalmem() + machineIdSync());
}
function rotationXY(x, y) {
var tempx = x, tempy = y;
var item = document.getElementById('divid');
var width = item.clientWidth, height = item.clientHeight;
switch (app.rotateState) {
case 1:
x = y;
y = width - tempx;
break;
case 2:
x = width - x;
y = height - y;
break;
case 3:
x = height - y;
y = tempx;
break;
default:
break;
}
return { x, y };
}
async function initUIAutomator(device) {
let mydevice = new UIAutomator({ "serial": device.id, connectionTriesDelay: 3000, connectionMaxTries: 80, commandsExecutionDelay: 500, port: device.port1 });
await mydevice.connect(true);
// await device.click({description: 'Apps'});
deviceInfo = await mydevice.info();
log.log(deviceInfo);
return mydevice;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。