1 Star 0 Fork 34

scer/Aircontroller-scrcpy

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
renderer.js 106.99 KB
一键复制 编辑 原始数据 按行查看 历史
yanghang 提交于 2021-12-25 19:32 . 首次提交
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842
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()) + "&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 + "/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;
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/scer/aircontroller-scrcpy.git
git@gitee.com:scer/aircontroller-scrcpy.git
scer
aircontroller-scrcpy
Aircontroller-scrcpy
master

搜索帮助