1 Star 1 Fork 31

梁小玛/Aircontroller-scrcpy

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
bak_9001 54.92 KB
一键复制 编辑 原始数据 按行查看 历史
yanghang 提交于 2021-12-25 19:32 . 首次提交
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525
// "package": "electron-packager ./ aircontroller_v0.09 --platform=win32 --arch=x64 --out=./out --asar --app-version=0.0.9"
const { ipcRenderer } = require('electron');
var net = require("net");
const path = require('path');
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');
var time;
var cmd = require('node-cmd');
const { machineId, machineIdSync } = require('node-machine-id');
const { throws } = require('assert');
const log = require('electron-log');
const { connectDeviceCommon, connectDeviceByThread } = require('./connecter');
var connectDevice;
var isOpenThreadConnecter = pg.get("connecter").txt;
// isOpenThreadConnecter = confirm("是否开启多线程模式(速度快,适合少量设备)");
// if(isOpenThreadConnecter){
// connectDevice = connectDeviceByThread;
// pg.set("connecter", "1");
// }else{
// pg.set("connecter", "0");
// connectDevice = connectDeviceCommon;
// }
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 = {};
const app = new Vue({
el: '#app',
data: {
visible: false,
page: 1,
total: 0,
recording: false,
delay: 10,
welcomeMsg: '',
text: '',
clients: [],
controllerClients: [],
screens: [],
controllerGroup: [],
renameMap: {},
renameIndex: -1,
accessToken: {},
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: '状态',
key: 'stateName'
}
],
data2: [],
defaultControllerIndex: -1,
modelStyle: {
width: '80%',
height: '80%'
},
timeLineContent: '',
comment: '',
conditon: '',
showManager: false,
isShow5: false,
showScriptForm: false,
loopConfig: false,
showScriptEditer: false,
data1: [],
msgList: [],
imgSources: [],
imgData: '',
sendMsg: '',
imgCount: 0,
selected: [],
timeHandler: null,
focusClient: null,
currentGroup: '',
tableWidth: window.innerWidth,
tableHeight: window.innerHeight - 150,
mouseDow: [],
mouseUp: [],
screensMap: {},
startMouseDownTime: 0,
groupSelect: [],
groupClients: [],
imgsource: '',
devices: {},
delayScript: '',
delayTimeHandle: null,
appOnlyOne: false,
delayScriptTime: 0,
port: 1716,
renameText: '',
mainName: '',
permission: false,
tokenCode: '',
connectMap: {},
connectCount: 0,
port1: 2888,
containerStyle: { height: window.screen.height - 200 + "px" },
scriptContent: [],
frameNum: 4,
scriptName: '',
downFlag: false,
delayControl: false,
runningForm: {
loopTime: 0,
loopInfinity: 1,
stopScript: false,
isRunning: false,
scriptIndex: -1
},
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>`;
}
}
],
recordScript: '',
scriptTime: 0,
scriptTimeHandler: null
},
methods: {
keyboard(key) {
this.sendRemoteCommand({ command: 'keyboard', key: key })
},
closeAccessTokenModel() {
ipcRenderer.send("close");
},
loop(index) {
app.runningForm.scriptIndex = index;
app.loopConfig = true;
},
showEdit(index) {
app.editIndex = index;
app.showScriptEditer = true;
app.recordScript = app.scriptContent[index].script;
},
saveEdit() {
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");
}
}
},
runningScript(index) {
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) {
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("删除成功");
},
saveScript() {
app.scriptContent.push({ scriptName: app.scriptName, script: app.recordScript });
pg.set("script", app.scriptContent);
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);
}
},
createGroup() {
try {
for (let i = 0; i < app.controllerGroup.length; i++) {
let item = app.controllerGroup[i];
if (item.group_name == app.groupName) {
app.$Message.error("已存在同名分组");
return;
}
}
app.controllerGroup.push({ group_name: app.groupName, clients: [] });
pg.set("group", app.controllerGroup);
app.$Message.success("添加成功");
} catch (error) {
console.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) {
this.renameMap[id] = this.renameText;
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));
if (tk && tk.exp) {
if (parseInt(tk.exp) > new Date().getTime() && tk.id == machineIdSync()) {
app.accessToken = tk;
return;
}
}
}
} catch (error) {
console.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) {
try {
cmd.run(adb_path + " -s " + device + " shell LD_LIBRARY_PATH=/data/local/tmp /data/local/tmp/minicap -P " + app.devices[device].wm[0] + "x" + app.devices[device].wm[1].replace("\r", "") + "@400x" + parseInt(app.devices[device].wm[0]) / 400 * app.devices[device].wm[1] + "/0");
cmd.run(adb_path + " -s " + device + " shell /data/local/tmp/minitouch");
setTimeout(() => {
cmd.get(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port + " localabstract:minicap", () => {
cmd.get(adb_path + " -s " + device + " forward tcp:" + app.devices[device].port1 + " localabstract:minitouch", () => {
connectDevice(app, device);
});
});
}, 3000);
} catch (error) {
app.$Message.error("无法连接到设备:请重新拔插设备USB或者重启设备");
delete app.devices[device];
}
},
refreshDevices() {
let pms = [];
let stateMap = {
device: '已连接',
offline: '无法链接',
unauthorized: '未授权'
};
app.data2 = [];
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) {
console.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 = [400, 400 / 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) {
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) {
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 " + d[0] + "x" + d[1] + "@400x" + parseInt(d[0]) / 400 * d[1] + "/0");
setTimeout(() => {
connectDevice(app, device);
// app.refreshGroupDevices(device);
}, 2000);
}, 4000);
});
});
resolve();
});
} catch (error) {
resolve();
console.error(error);
}
});
}));
} else {
app.data2.push({ client: device, stateName: stateMap[deviceInfo[1]] });
}
})
// Promise.all(pms).then(() => {
// app.controllerGroupChange();
// })
});
},
checkController(id,event){
app.controllerMap[id] = !app.controllerMap[id];
event.stopPropagation();
},
async sendRemoteCommand(params, isDelay, delayTime) {
if (app.runningForm.isRunning && app.runningForm.stopScript) {
app.runningForm.isRunning = false;
app.runningForm.stopScript = false;
throw {};
}
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 += "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(app.screens[app.defaultControllerIndex].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;
},
getController(index, flag) {
if (app.mainName) {
app.exitMainControl(index);
}
if (index == -1) {
return;
}
app.appOnlyOne = flag;
app.mainName = app.screens[index].name;
if (app.mainName) {
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 = 400;
copyCanvas.height = mnwm[1];
g.drawImage(img, 0, 0, 400, 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;
},
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 () {
img.width = 300;
img.style.width = 300 + "px";
img.style.height = 300 + "px";
copyCanvas.width = 150;
copyCanvas.height = 225;
g.drawImage(img, 0, 0, 150, 225);
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;
// 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;
}
});
}
},
addGroupByName() {
if (app.currentGroup) {
app.controllerGroup.forEach(item => {
if (item.group_name == app.currentGroup) {
for (let i = 0; i < app.groupSelect.length; i++) {
if (item.clients.includes(app.groupSelect[i].client)) continue;
item.clients.push(app.groupSelect[i].client);
// app.refreshGroupDevices(app.groupSelect[i].client);
}
}
})
} else {
app.$Message.error("当前是无效分组请切换到有效的分组");
return;
}
pg.set("group", app.controllerGroup);
app.controllerGroupChange();
},
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) {
app.exitMainControl();
app.mainName = "";
app.controllerGroup.forEach(item => {
if (item.group_name == app.currentGroup) {
app.screens = [];
app.screensMap = [];
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 (index > app.accessToken.clientNum - 1) {
return;
}
app.screens.push({ name: item, source: '', wm: app.devices[item].wm });
if (!app.renameMap[item]) {
app.renameMap[item] = item;
}
app.screensMap[item] = index;
});
}
});
}
},
controllerMove(event) {
if (!app.mouseDow || app.mouseDow.length == 0) 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;
app.sendRemoteCommand({ x: remoteX, y: remoteY, command: 'move' });
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;
app.sendRemoteCommand({ x: remoteX, y: remoteY, command: 'move' });
time = null;
});
}
},
controllerMouseDown(event) {
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;
app.mouseDow = [remoteX, remoteY];
// app.sendRemoteCommand({ command: 'up' });
app.sendRemoteCommand({ x: remoteX, y: remoteY, command: 'click' });
},
controllerMouseup(event) {
event.stopPropagation();
if (!app.mouseDow || app.mouseDow.length == 0) {
return;
}
app.mouseDow = null;
// app.sendRemoteCommand({ command: 'up' });
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' });
}
},
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);
},
send() {
if (!this.sendMsg) {
alert("不能发送空消息");
return;
}
$.get(base_url + "/wx/console/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/console/addCommand?tk=" + token + "&clients=" + encodeURI(wxIds.toString()) + "&params=" + 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 + "/wxconsole/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/console/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) {
},
openClientList() {
this.isShow1 = true;
app.selected = [];
},
saveAccessToken() {
$.get(base_url + "/wx/console/getAccessToken?tokenCode=" + app.tokenCode).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.id = machineIdSync();
pg.set("accessToken", encrypt(JSON.stringify(decodeToken)));
app.accessToken = decodeToken;
init();
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 : [];
}, 1000);
}
},
created: function () {
setTimeout(() => {
init();
app.checkPermission();
}, 2000);
},
mounted() {
alert();
}
});
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;
}
};
app.getGroup();
setInterval(() => {
try {
let tk = pg.get("accessToken").txt;
tk = JSON.parse(decrypt(tk));
if (tk && tk.exp) {
if (parseInt(tk.exp) > new Date().getTime() && tk.id == machineIdSync()) {
return;
}
}
} catch (error) {
}
app.permission = true;
}, 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) {
console.error(error);
}
});
}
})
});
})
}
function changeScreenPoint(point, target) {
// let x = 400, y = 800;
let 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) {
try {
if (!app.devices[device]) {
return;
}
if (type == 'size') {
cmd.get(adb_path + " -s " + device + " shell wm size", function (e, d, s) {
// console.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("c\n");
// cmd.get(adb_path + " -s " + device + " shell input tap " + point[0] + " " + point[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 == 'up') {
app.connectMap[device + "_tc"].postMessage("u 0 \n");
app.connectMap[device + "_tc"].postMessage("c\n");
}
if (type == 'move') {
let point = changeScreenPoint([extend.x, extend.y], app.devices[device].wm);
app.connectMap[device + "_tc"].postMessage("m 0 " + parseInt(point[0]) + " " + parseInt(point[1]) + " 100\n");
app.connectMap[device + "_tc"].postMessage("c\n");
// 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 == 'lock' || key == 'open') {
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 {
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) {
// console.debug(d);
app.devices[device].version = d.split("\n")[0];
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) {
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 () {
canvas.width = img.width;
canvas.height = img.height;
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;
}
function loadImg(buf, canvas) {
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 () {
img.width = 300;
img.style.width = 300 + "px";
img.style.height = 300 + "px";
canvas.width = 150;
canvas.height = 225;
g.drawImage(img, 0, 0, 150, 225);
g = null;
img.onload = null;
URL.revokeObjectURL(u);
u = null;
blob = null;
// img.src = BLANK_IMG;
img = null;
};
img.src = u;
}
// function connectDevice(deviceId) {
// if (app.connectMap[deviceId]) {
// try {
// app.connectMap[deviceId].terminate();
// app.connectMap[deviceId + "_tc"].terminate();
// } catch (error) {
// console.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) {
// console.error(error);
// }
// };
// app.connectMap[deviceId + "_tc"] = new Worker('deviceTouchWorker.js');
// app.connectMap[deviceId + "_tc"].postMessage({ event: 'connect', data: app.devices[deviceId] });
// }
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;
// console.debug(data[547]);
for (var i = 6; i < data.length; i++) {
console.debug(i);
await query.saveData(data[i]);
}
}
async function test() {
for (var i = 100; i < 200; i++) {
await sleep(3000);
console.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('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;
console.log("file:", path);
if (/\.apk/.test(path)) {
app.sendRemoteCommand({ command: 'install', path: path });
} else {
alert("此文件非APK文件")
}
}
});
container.addEventListener("dragover", (e) => {
e.preventDefault();
})
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/layneliang/aircontroller-scrcpy.git
git@gitee.com:layneliang/aircontroller-scrcpy.git
layneliang
aircontroller-scrcpy
Aircontroller-scrcpy
master

搜索帮助