forked from VRPirates/sidenoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.js
2832 lines (2438 loc) · 77.3 KB
/
tools.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const exec = require("child_process").exec;
// const fs = require('fs');
const fs = require("fs");
const fsp = fs.promises;
const util = require("util");
const path = require("path");
const crypto = require("crypto");
const commandExists = require("command-exists");
const { dialog } = require("electron");
const ApkReader = require("adbkit-apkreader");
const adbkit = require("@devicefarmer/adbkit").default;
const adb = adbkit.createClient();
const fetch = (...args) =>
import("node-fetch").then(({ default: fetch }) => fetch(...args));
const WAE = require("web-auto-extractor").default;
// const HttpProxyAgent = require('https-proxy-agent'); // TODO add https proxy support
const { SocksProxyAgent } = require("socks-proxy-agent");
const url = require("url");
// const ApkReader = require('node-apk-parser');
const fixPath = (...args) =>
import("fix-path").then(({ default: fixPath }) => fixPath(...args));
// adb.kill();
const pkg = require("./package.json");
const _sec = 1000;
const _min = 60 * _sec;
let CHECK_META_PERIOD = 2 * _min;
const l = 32;
const configLocationOld = path.join(global.homedir, "sidenoder-config.json");
const configLocation = path.join(global.sidenoderHome, "config.json");
let agentOculus, agentSteam, agentSQ;
init();
const GAME_LIST_NAMES = global.currentConfiguration.gameListNames || [
"FFA.txt",
"GameList.txt",
"VRP-GameList.txt/VRP-GameList.txt",
"VRP-GameList.txt",
"Dynamic.txt",
];
let META_VERSION = [];
let QUEST_ICONS = [];
let cacheOculusGames = false;
let KMETAS = {};
let KMETAS2 = {};
let adbCmd = "adb";
let grep_cmd = "| grep ";
if (platform == "win") {
grep_cmd = "| findstr ";
}
let RCLONE_ID = 0;
module.exports = {
//properties
resetCache,
//methods
getDeviceSync,
trackDevices,
checkDeps,
checkMount,
mount,
killRClone,
getDir,
returnError,
sideloadFolder,
getInstalledApps,
getInstalledAppsWithUpdates,
getApkFromFolder,
uninstall,
getDirListing,
getPackageInfo,
wifiGetStat,
wifiEnable,
connectWireless,
disconnectWireless,
enableMTP,
startSCRCPY,
rebootDevice,
rebootRecovery,
rebootBootloader,
sideloadFile,
getLaunchActivity,
getActivities,
startActivity,
devOpenUrl,
checkAppTools,
changeAppConfig,
backupApp,
backupAppData,
restoreAppData,
getDeviceInfo,
getStorageInfo,
getUserInfo,
getFwInfo,
getBatteryInfo,
changeConfig,
reloadConfig,
execShellCommand,
updateRcloneProgress,
deviceTweaksGet,
deviceTweaksSet,
appInfo,
appInfoEvents,
isIdle,
wakeUp,
detectInstallTxt,
detectNoteTxt,
// ...
};
async function getDeviceInfo() {
if (!global.adbDevice) {
return {
success: false,
};
}
// console.log('getDeviceInfo()');
const storage = await getStorageInfo();
const user = await getUserInfo();
const fw = await getFwInfo();
const battery = await getBatteryInfo();
const ip = await getDeviceIp();
const wifi = await wifiGetStat();
const res = {
success: !!storage,
storage,
user,
fw,
battery,
ip,
wifi,
};
// console.log('getDeviceInfo', res);
return res;
}
async function getFwInfo() {
console.log("getFwInfo()");
const res = await adbShell("getprop ro.build.branch");
if (!res) return false;
return {
version: res.replace("releases-oculus-", ""),
};
}
async function getBatteryInfo() {
console.log("getBatteryInfo()");
const res = await adbShell("dumpsys battery");
if (!res) return false;
return parceOutOptions(res);
}
async function getUserInfo() {
if (global.currentConfiguration.userHide)
return {
name: "<i>hidden</i>",
};
console.log("getUserInfo()");
const res = await adbShell("dumpsys user | grep UserInfo");
if (!res) return false;
return {
name: res.split(":")[1],
};
}
async function deviceTweaksGet(arg) {
console.log("deviceTweaksGet()", arg);
let res = {
cmd: "get",
// mp_name: '',
// guardian_pause: '0',
// frc: '0',
// gRR: '72',
// gCA: '-1',
// gFFR: '2',
// CPU: '2',
// GPU: '2',
// vres: '1024',
// cres: '640x480',
// gSSO: '1440x1584',
};
if (arg.key === "mp_name")
res.mp_name = await adbShell("settings get global username");
if (arg.key === "guardian_pause")
res.guardian_pause = await adbShell("getprop debug.oculus.guardian_pause");
if (arg.key === "frc")
res.frc = await adbShell("getprop debug.oculus.fullRateCapture");
if (arg.key === "gRR")
res.gRR = await adbShell("getprop debug.oculus.refreshRate");
if (arg.key === "gCA")
res.gCA = await adbShell("getprop debug.oculus.forceChroma");
if (arg.key === "gFFR")
res.gFFR = await adbShell("getprop debug.oculus.foveation.level");
if (arg.key === "CPU")
res.CPU = await adbShell("getprop debug.oculus.cpuLevel");
if (arg.key === "GPU")
res.GPU = await adbShell("getprop debug.oculus.gpuLevel");
if (arg.key === "vres")
res.vres = await adbShell("getprop debug.oculus.videoResolution");
if (arg.key === "cres") {
let captureDims =
(await adbShell("getprop debug.oculus.capture.width")) +
"x" +
(await adbShell("getprop debug.oculus.capture.height"));
// Default when not set
if (captureDims === "x") {
captureDims = "3840x1920";
}
res.cres = captureDims;
}
if (arg.key === "gSSO")
res.gSSO =
(await adbShell("getprop debug.oculus.textureWidth")) +
"x" +
(await adbShell("getprop debug.oculus.textureHeight"));
//oculus.capture.bitrate
return res;
}
async function deviceTweaksSet(arg) {
console.log("deviceTweaksSet()", arg);
let res = { cmd: "set" };
if (typeof arg.mp_name != "undefined") {
res.mp_name = await adbShell("settings put global username " + arg.mp_name);
}
if (typeof arg.guardian_pause != "undefined") {
res.guardian_pause = await adbShell(
"setprop debug.oculus.guardian_pause " + (arg.guardian_pause ? "1" : "0"),
);
}
if (typeof arg.frc != "undefined") {
res.frc = await adbShell(
"setprop debug.oculus.fullRateCapture " + (arg.frc ? "1" : "0"),
);
}
if (typeof arg.gRR != "undefined") {
res.gRR = await adbShell("setprop debug.oculus.refreshRate " + arg.gRR);
}
if (typeof arg.gCA != "undefined") {
res.gCA = await adbShell("setprop debug.oculus.forceChroma " + arg.gCA);
}
if (typeof arg.gFFR != "undefined") {
res.gFFR = await adbShell(
"setprop debug.oculus.foveation.level " + arg.gFFR,
);
}
if (typeof arg.CPU != "undefined") {
res.CPU = await adbShell("setprop debug.oculus.cpuLevel " + arg.CPU);
}
if (typeof arg.GPU != "undefined") {
res.GPU = await adbShell("setprop debug.oculus.gpuLevel " + arg.GPU);
}
if (typeof arg.vres != "undefined") {
res.vres = await adbShell(
"setprop debug.oculus.videoResolution " + arg.vres,
);
}
if (typeof arg.cres != "undefined") {
const [width, height] = arg.cres.split("x");
await adbShell("setprop debug.oculus.capture.width " + width);
res.cres = await adbShell("setprop debug.oculus.capture.height " + height);
}
if (typeof arg.gSSO != "undefined") {
const [width, height] = arg.gSSO.split("x");
await adbShell("setprop debug.oculus.textureWidth " + width);
await adbShell("setprop debug.oculus.textureHeight " + height);
res.gSSO = await adbShell(
"settings put system font_scale 0.85 && settings put system font_scale 1.0",
);
}
return res;
}
async function getStorageInfo() {
console.log("getStorageInfo()");
const linematch = await adbShell('df -h | grep "/storage/emulated"');
if (!linematch) return false;
const refree = new RegExp("([0-9(.{1})]+[a-zA-Z%])", "g");
const storage = linematch.match(refree);
console.log(storage);
if (storage.length == 3) {
return {
size: storage[0],
used: storage[1],
free: 0,
percent: storage[2],
};
}
return {
size: storage[0],
used: storage[1],
free: storage[2],
percent: storage[3],
};
}
async function getLaunchActivity(pkg) {
console.log("startApp()", pkg);
const activity = await adbShell(
`dumpsys package ${pkg} | grep -A 1 'filter' | head -n 1 | cut -d ' ' -f 10`,
);
return startActivity(activity);
}
async function getActivities(pkg, activity = false) {
console.log("getActivities()", pkg);
let activities = await adbShell(
`dumpsys package | grep -Eo '^[[:space:]]+[0-9a-f]+[[:space:]]+${pkg}/[^[:space:]]+' | grep -oE '[^[:space:]]+$'`,
);
if (!activities) return false;
activities = activities.split("\n");
// activities.pop();
console.log({ pkg, activities });
// TODO: check manifest.application.launcherActivities
return activities;
}
async function startActivity(activity) {
console.log("startActivity()", activity);
wakeUp();
const result = await adbShell(`am start ${activity}`); // TODO activity selection
console.log("startActivity", activity, result);
return result;
}
async function devOpenUrl(url) {
console.log("devOpenUrl", url);
wakeUp();
const result = await adbShell(
`am start -a android.intent.action.VIEW -d "${url}"`,
); // TODO activity selection
console.log("devOpenUrl", url, result);
return result;
}
async function readAppCfg(pkg) {
let config = await adbShell(
`cat /sdcard/Android/data/${pkg}/private/config.json 1>&1 2> /dev/null`,
);
try {
config = config && JSON.parse(config);
} catch (e) {
console.error("readAppCfg", e);
config = false;
}
return config;
}
async function checkAppTools(pkg) {
const backupPath = path.join(global.sidenoderHome, "backup_data", pkg);
const availableBackup = await adbFileExists(`/sdcard/Android/data/${pkg}`);
let availableRestore = false;
let availableConfig = false;
if (await fsp.exists(backupPath)) {
try {
availableRestore = await fsp.readFile(`${backupPath}/time.txt`, "utf8");
} catch (err) {
availableRestore = 1;
}
}
if (availableBackup) {
availableConfig = await readAppCfg(pkg);
}
return {
success: true,
pkg,
availableRestore,
availableConfig,
};
}
async function changeAppConfig(pkg, key, val) {
console.log("changeAppConfig()", { pkg, key, val });
const res = {
pkg,
key,
val,
success: false,
};
let config = await readAppCfg(pkg);
try {
config = Object.assign(config, { [key]: val });
adbShell(
`echo '${JSON.stringify(config)}' > "/sdcard/Android/data/${pkg}/private/config.json"`,
);
config = await readAppCfg(pkg);
res.val = config && config[key];
res.success = !!config;
} catch (e) {
console.error("changeAppConfig", res, e);
}
return res;
}
// Implementation ----------------------------------
async function getDeviceIp() {
// let ip = await adb.getDHCPIpAddress(global.adbDevice);
// if (ip) return ip;
if (!global.adbDevice && global.currentConfiguration.lastIp) {
return global.currentConfiguration.lastIp;
}
let ip = await adbShell(
`ip -o route get to 8.8.8.8 | sed -n 's/.*src \\([0-9.]\\+\\).*/\\1/p'`,
);
console.log({ ip });
if (ip) return ip;
ip = await adbShell(
`ip addr show wlan0 | grep 'inet ' | cut -d ' ' -f 6 | cut -d / -f 1`,
);
console.log({ ip });
if (ip) return ip;
return false;
}
async function wifiGetStat() {
const on = await adbShell("settings get global wifi_on");
return on && +on;
}
async function wifiEnable(enable) {
return adbShell(`svc wifi ${enable ? "enable" : "disable"}`);
}
async function connectWireless() {
const on = await adbShell("settings get global wifi_on");
if (!(await wifiGetStat())) {
console.error("connectWireless", "wifi disabled");
await wifiEnable(true);
return false;
}
// await adbShell(`setprop service.adb.tcp.port 5555`);
// TODO: save ip & try use it
const ip = await getDeviceIp();
console.log({ ip });
if (!ip) return false;
try {
if (global.adbDevice) {
const device = adb.getDevice(global.adbDevice);
const port = await device.tcpip();
await device.waitForDevice();
console.log("set tcpip", port);
await changeConfig("lastIp", ip);
}
const deviceTCP = await adb.connect(ip, 5555);
// await deviceTCP.waitForDevice();
console.log("connectWireless", { ip, res: deviceTCP });
return ip;
} catch (err) {
console.error("connectWireless", err);
await changeConfig("lastIp", "");
return false;
}
}
async function disconnectWireless() {
const ip = await getDeviceIp();
if (!ip) return false;
try {
const res = await adb.disconnect(ip, 5555);
// const res = await adb.usb(global.adbDevice);
console.log("disconnectWireless", { ip, res });
// await changeConfig('lastIp', '');
// await getDeviceSync();
return res;
} catch (err) {
console.error("disconnectWireless.error", err);
return !(await isWireless());
}
}
async function isWireless() {
try {
const devices = await adb.listDevices();
for (const device of devices) {
if (!device.id.includes(":5555")) continue;
if (["offline", "authorizing"].includes(device.type)) continue;
if (["unauthorized"].includes(device.type)) {
win.webContents.send(
"alert",
"Please authorize adb access on your device",
);
continue;
}
console.log("device.id", device.type);
return device.id;
}
return false;
} catch (err) {
console.error("Something went wrong:", err.stack);
return false;
}
}
async function enableMTP() {
const res = await adbShell(`svc usb setFunctions mtp`);
console.log("enableMTP", { res });
return res;
}
async function isIdle() {
const res = await adbShell(`dumpsys deviceidle | grep mScreenOn`);
console.log(res, res.includes("true"));
return !res.includes("true");
}
async function wakeUp() {
if (!(await isIdle())) return;
return adbShell(`input keyevent KEYCODE_POWER`);
}
async function startSCRCPY() {
console.log("startSCRCPY()");
if (
!global.currentConfiguration.scrcpyPath &&
!(await commandExists("scrcpy"))
) {
returnError("Can`t find scrcpy binary");
return;
}
const scrcpyCmd =
`"${global.currentConfiguration.scrcpyPath || "scrcpy"}" ` +
(global.currentConfiguration.scrcpyCrop
? `--crop ${global.currentConfiguration.scrcpyCrop} `
: "") +
`-b ${global.currentConfiguration.scrcpyBitrate || 1}M ` +
(global.currentConfiguration.scrcpyFps
? `--max-fps ${global.currentConfiguration.scrcpyFps} `
: "") +
(global.currentConfiguration.scrcpySize
? `--max-size ${global.currentConfiguration.scrcpySize} `
: "") +
(!global.currentConfiguration.scrcpyWindow ? "-f " : "") +
(global.currentConfiguration.scrcpyOnTop ? "--always-on-top " : "") +
(!global.currentConfiguration.scrcpyControl ? "-n " : "") +
'--window-title "SideNoder Stream" ' +
`-s ${global.adbDevice} `;
console.log({ scrcpyCmd });
wakeUp();
exec(scrcpyCmd, (error, stdout, stderr) => {
if (error) {
console.error("scrcpy error:", error);
win.webContents.send("cmd_sended", { success: error });
return;
}
if (stderr) {
console.error("scrcpy stderr:", stderr);
// win.webContents.send('cmd_sended', { success: stderr });
return;
}
console.log("scrcpy stdout:", stdout);
});
return scrcpyCmd;
}
async function rebootDevice() {
const res = await adbShell(`reboot`);
console.log("rebootDevice", { res });
return res;
}
async function rebootRecovery() {
const res = await adbShell(`reboot recovery`);
console.log("rebootRecovery", { res });
return res;
}
async function rebootBootloader() {
const res = await adbShell(`reboot bootloader`);
console.log("rebootBootloader", { res });
return res;
}
async function sideloadFile(path) {
const res = await execShellCommand(`"${adbCmd}" sideload "${path}"`);
console.log("sideloadFile", { res });
return res;
}
async function getDeviceSync(attempt = 0) {
try {
// const lastDevice = global.adbDevice;
const devices = await adb.listDevices();
console.log({ devices });
global.adbDevice = false;
for (const device of devices) {
if (["offline", "authorizing"].includes(device.type)) continue;
if (["unauthorized"].includes(device.type)) {
win.webContents.send(
"alert",
"Please authorize adb access on your device",
);
continue;
}
if (
!global.currentConfiguration.allowOtherDevices &&
(await adbShell("getprop ro.product.brand", device.id)) != "oculus"
)
continue;
global.adbDevice = device.id;
}
/*if (!global.adbDevice && devices.length > 0 && attempt < 1) {
return setTimeout(()=> getDeviceSync(attempt + 1), 1000);
}*/
// if (lastDevice == global.adbDevice) return;
win.webContents.send("check_device", { success: global.adbDevice });
return global.adbDevice;
} catch (err) {
console.error("Something went wrong:", err.stack);
}
}
/**
* Executes a shell command and return it as a Promise.
* @param cmd {string}
* @return {Promise<string>}
*/
async function adbShell(cmd, deviceId = global.adbDevice, skipRead = false) {
try {
if (!deviceId) {
throw "device not defined";
}
global.adbError = null;
const r = await adb.getDevice(deviceId).shell(cmd);
// console.timeLog(cmd);
if (skipRead) {
console.log(`adbShell[${deviceId}]`, { cmd, skipRead });
return true;
}
let output = await adbkit.util.readAll(r);
output = await output.toString();
// output = output.split('\n');
// const end = output.pop();
// if (end != '') output.push();
console.log(`adbShell[${deviceId}]`, { cmd, output });
if (output.substr(-1) == "\n") return output.slice(0, -1);
return output;
} catch (err) {
console.error(`adbShell[${deviceId}]: err`, { cmd }, err);
global.adbError = err;
if (err.toString() == `FailError: Failure: 'device offline'`) {
getDeviceSync();
}
return false;
}
}
function parceOutOptions(line) {
let opts = {};
for (let l of line.split("\n")) {
l = l.split(" ").join("");
let [k, v] = l.split(":");
if (v == "true") v = true;
if (v == "false") v = false;
if (!isNaN(+v)) v = +v;
opts[k] = v;
}
return opts;
}
// on empty dirrectory return false
async function adbFileExists(path) {
const r = await adbShell(`ls "${path}" 1>&1 2> /dev/null`);
return r;
}
async function adbPull(orig, dest, sync = false) {
console.log("adbPull", orig, dest);
const transfer = sync
? await sync.pull(orig)
: await adb.getDevice(global.adbDevice).pull(orig);
return new Promise(function (resolve, reject) {
let c = 0;
transfer.on("progress", (stats) => {
c++;
if (c % 40 != 1) return; // skip 20 events
// console.log(orig + ' pulled', stats);
const res = {
cmd: "pull",
bytes: stats.bytesTransferred,
size: 0,
percentage: 0,
speedAvg: 0,
eta: 0,
name: orig,
};
win.webContents.send("process_data", res);
});
transfer.on("end", () => {
console.log(orig, "pull complete");
win.webContents.send("process_data", false);
resolve(true);
});
transfer.on("error", (err) => {
console.error("adb_pull_stderr", err);
win.webContents.send("process_data", false);
reject(err);
});
transfer.pipe(fs.createWriteStream(dest));
});
}
async function adbPullFolder(orig, dest, sync = false) {
console.log("pullFolder", orig, dest);
/*let need_close = false;
if (!sync) {
need_close = true;
sync = await adb.getDevice(global.adbDevice).syncService();
}*/
let actions = [];
await fsp.mkdir(dest, { recursive: true });
const files = sync
? await sync.readdir(orig)
: await adb.getDevice(global.adbDevice).readdir(orig);
for (const file of files) {
const new_orig = `${orig}/${file.name}`;
const new_dest = path.join(dest, file.name);
if (file.isFile()) {
actions.push(adbPull(new_orig, new_dest, sync)); // file.size
continue;
}
actions.push(adbPullFolder(new_orig, new_dest, sync));
}
await Promise.all(actions);
// if (need_close) sync.end();
return true;
}
async function adbPush(orig, dest, sync = false) {
console.log("adbPush", orig, dest);
const transfer = sync
? await sync.pushFile(orig, dest)
: await adb.getDevice(global.adbDevice).push(orig, dest);
const stats = await fsp.lstat(orig);
const size = stats.size;
return new Promise(function (resolve, reject) {
let c = 0;
transfer.on("progress", (stats) => {
c++;
if (c % 40 != 1) return; // skip 20 events
// console.log(orig + ' pushed', stats);
const res = {
cmd: "push",
bytes: stats.bytesTransferred,
size,
percentage: ((stats.bytesTransferred * 100) / size).toFixed(2),
speedAvg: 0,
eta: 0,
name: orig,
};
win.webContents.send("process_data", res);
});
transfer.on("end", () => {
console.log(orig, "push complete");
win.webContents.send("process_data", false);
resolve(true);
});
transfer.on("error", (err) => {
console.error("adb_push_stderr", err);
win.webContents.send("process_data", false);
reject(err);
});
});
}
async function adbPushFolder(orig, dest, sync = false) {
console.log("pushFolder", orig, dest);
const stat = await fsp.lstat(orig);
console.log({ orig, stat }, stat.isFile());
if (stat.isFile()) return adbPush(orig, dest);
/*let need_close = false;
if (!sync) {
need_close = true;
sync = await adb.getDevice(global.adbDevice).syncService();
}*/
let actions = [];
await adbShell(`mkdir -p ${dest}`, global.adbDevice, true);
const files = await fsp.readdir(orig, { withFileTypes: true });
for (const file of files) {
const new_orig = path.join(orig, file.name);
const new_dest = `${dest}/${file.name}`;
if (file.isFile()) {
actions.push(adbPush(new_orig, new_dest, sync));
continue;
}
actions.push(adbPushFolder(new_orig, new_dest, sync));
}
await Promise.all(actions);
// if (need_close) sync.end();
return true;
}
async function adbInstall(apk) {
console.log("adbInstall", apk);
const temp_path = "/data/local/tmp/install.apk";
await adbPush(apk, temp_path, false, false);
try {
await adb.getDevice(global.adbDevice).installRemote(temp_path);
} catch (err) {
adbShell(`rm ${temp_path}`);
throw err;
}
return true;
}
function execShellCommand(cmd, ignoreError = false, buffer = 100) {
console.log({ cmd });
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * buffer }, (error, stdout, stderr) => {
if (error) {
if (ignoreError) return resolve(false);
console.error("exec_error", cmd, error);
return reject(error);
}
if (stdout || !stderr) {
console.log("exec_stdout", cmd, stdout);
return resolve(stdout);
} else {
if (ignoreError) return resolve(false);
console.error("exec_stderr", cmd, stderr);
return reject(stderr);
}
});
});
}
async function trackDevices() {
console.log("trackDevices()");
await getDeviceSync();
try {
const tracker = await adb.trackDevices();
tracker.on("add", async (device) => {
console.log("Device was plugged in", device.id);
// await getDeviceSync();
});
tracker.on("remove", async (device) => {
console.log("Device was unplugged", device.id);
// await getDeviceSync();
});
tracker.on("change", async (device) => {
// TODO: // need fix double run
console.log("Device was changed", device.id);
await getDeviceSync();
});
tracker.on("end", () => {
console.error("Tracking stopped");
trackDevices();
});
} catch (err) {
console.error("Something went wrong:", err.stack);
returnError(err);
}
}
async function appInfo(args) {
const { res, pkg } = args;
const app = KMETAS[pkg];
let data = {
res,
pkg,
id: 0,
name: app.simpleName,
short_description: "",
detailed_description: "",
about_the_game: "",
supported_languages: "",
genres: [],
header_image: "",
screenshots: [],
url: "",
};
try {
if (res == "steam") {
const steam = app && app.steam;
if (!steam || !steam.id) throw "incorrect args";
data.id = steam.id;
data.url = `https://store.steampowered.com/app/${data.id}/`;
const resp = await fetchTimeout(
`https://store.steampowered.com/api/appdetails?appids=${data.id}`,
{
headers: {
"Accept-Language": global.locale + ",en-US;q=0.5,en;q=0.3",
},
agent: agentSteam,
},
);
const json = await resp.json();
// console.log({ json });
Object.assign(data, json[data.id].data);
}
if (res == "oculus") {
const oculus = app && app.oculus;
if (!oculus || !oculus.id) throw "incorrect args";
// console.log({ oculus });
data.id = oculus.id;
data.url = `https://www.oculus.com/experiences/quest/${data.id}`;
// data.genres = oculus.genres && oculus.genres.split(', ');
//https://computerelite.github.io
let resp = await fetchTimeout(
`https://graph.oculus.com/graphql?forced_locale=${global.locale}`,
{
method: "POST",
body: `access_token=OC|1317831034909742|&variables={"itemId":"${oculus.id}","first":1}&doc_id=5373392672732392`,
headers: {
"Accept-Language": global.locale + ",en-US;q=0.5,en;q=0.3",
"Content-Type": "application/x-www-form-urlencoded",
Origin: "https://www.oculus.com",
},
agent: agentOculus,