forked from SuperMonster003/Ant-Forest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnt_Forest_Launcher.js
3613 lines (3116 loc) · 161 KB
/
Ant_Forest_Launcher.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
/**
* @overview alipay ant forest energy intelligent collection script
*
* @last_modified Jul 26, 2019
* @version 1.8.2
* @author SuperMonster003
*
* @tutorial {@link https://github.com/SuperMonster003/Auto.js_Projects/tree/Ant_Forest}
*/
// given that there are bugs with dialogs modules in old auto.js versions like 4.1.0/5 and 4.1.1/2
// in another way, maybe sometimes dialogs.builds() could make things easier
let dialogs = require("./Modules/__dialogs__pro_v6.js")(runtime, this);
let {
launchThisApp,
killThisApp,
waitForAction,
clickAction,
waitForAndClickAction,
messageAction,
showSplitLine,
getVerName,
runJsFile,
debugInfo,
swipeInArea,
refreshObjects,
tryRequestScreenCapture,
keycode,
getDisplayParams,
observeToastMessage,
equalObjects,
} = require("./Modules/MODULE_MONSTER_FUNC");
let classof = o => Object.prototype.toString.call(o).slice(8, -1);
let timers = require("./Modules/__timers__pro_v37")(runtime, this);
try {
auto.waitFor();
} catch (e) {
messageAction("auto.waitFor()不可用", 0, 0, 0, "up");
auto();
}
let current_app = {};
let engines_support_flag = true;
let sel = selector();
let config = {};
let override_config = {};
let {storage_af, storage_af_cfg, unlock_module, WIDTH, HEIGHT, USABLE_HEIGHT, screen_orientation, cX, cY} = {};
checkModules.bind(this)();
checkTasksQueue();
showRunningCountdownIfNeeded();
setInsuranceTaskIfNeeded();
checkVersions();
checkEngines();
setVolKeysListener();
antForest();
// entrance function //
function antForest() {
let main = () => {
prologue();
launchHomepage();
checkLanguage();
checkEnergy();
showResult();
epilogue();
};
let {max_retry_times_global} = config;
let max_retry_times_global_backup = max_retry_times_global;
while (max_retry_times_global--) {
try {
return main();
} catch (e) {
if (e.message && e.message.match("ScriptInterruptedException")) return;
messageAction(e.message, 4, 1, 0, "both_dash");
killThisApp("com.eg.android.AlipayGphone");
let current_retry_times = max_retry_times_global_backup - max_retry_times_global;
messageAction("任务失败重试 (" + current_retry_times + "\/" + max_retry_times_global_backup + ")", 1, 0, 0, "both");
}
}
return main(); // to make Error thrown to main thread and easy to locate
}
// main function(s) //
function prologue() {
let init_operation_logged = null;
debugInfo("准备初始化");
unlock();
setScreenPixelData();
setSelectorProto();
setAutoJsLogPath();
setParams();
loginSpecificUser(); // init_operation_logged doesn't set, and needs optimization
debugInfo("初始化完毕");
if (init_operation_logged) showSplitLine();
// tool function(s) //
function unlock() {
if (!unlock_module) {
messageAction("自动解锁功能无法使用", 3);
return messageAction("解锁模块未导入", 3, 0, 1);
}
if (!current_app.is_screen_on && !config.auto_unlock_switch) {
messageAction("脚本无法继续", 4);
messageAction("屏幕关闭且自动解锁功能未开启", 8, 1, 1, 1);
}
if (!context.getSystemService(context.KEYGUARD_SERVICE).isKeyguardLocked()) {
this._monster_$_no_need_unlock_flag = true;
return debugInfo("无需解锁");
}
debugInfo("尝试自动解锁");
unlock_module.unlock();
debugInfo("自动解锁完毕");
}
function setSelectorProto() {
sel.__proto__ = {
pickup: (condition, memory_keyword, prefer) => {
let _mem_kw_prefix = "_MEM_KW_PREFIX_";
if (memory_keyword) {
let memory_kn = this[_mem_kw_prefix + memory_keyword];
if (memory_kn) return memory_kn;
}
let kn = getSelector();
if (memory_keyword && kn.exists()) {
debugInfo("选择器已记录");
debugInfo(">" + memory_keyword);
debugInfo(">" + kn);
this[_mem_kw_prefix + memory_keyword] = kn;
}
return kn;
// tool function(s)//
function getSelector() {
let classof = Object.prototype.toString.call(condition).slice(8, -1);
if (typeof condition === "string") {
if (prefer === "text") return text(condition).exists() ? text(condition) : desc(condition);
return desc(condition).exists() ? desc(condition) : text(condition);
}
if (classof === "RegExp") {
if (prefer === "text") return textMatches(condition).exists() ? textMatches(condition) : descMatches(condition);
return descMatches(condition).exists() ? descMatches(condition) : textMatches(condition);
}
}
},
selStr: (condition, memory_keyword, prefer) => {
if (classof(condition) === "JavaObject") return condition.toString().slice(0, 4);
return sel.pickup(condition, memory_keyword, prefer).toString().slice(0, 4);
},
};
debugInfo("选择器加入新方法");
Object.keys(sel.__proto__).forEach(key => debugInfo(">" + key + "()"));
}
function setAutoJsLogPath() {
// need more actions here
let log_path = config.auto_js_log_record_path;
if (!log_path) return debugInfo("日志存储功能关闭");
files.createWithDirs(log_path);
console.setGlobalLogConfig({
file: log_path,
});
debugInfo("日志存储功能开启");
}
function setParams() {
files.createWithDirs(files.getSdcardPath() + "/.local/Pics/");
images.getName = (img) => {
let img_str = img.toString().split("@")[1];
return img_str ? "@" + img_str.match(/\w+/)[0] : "(已提前回收)";
};
images.isRecycled = (img) => {
if (!img) return true;
try {
img.getHeight();
return false;
} catch (e) {
if (e.toString().match(/has been recycled/)) return true;
}
};
images.captureCurrentScreen = () => {
let img = captureScreen();
let max_try_times = 10;
while (max_try_times--) {
try {
return images.copy(img || captureScreen());
} catch (e) {
img = null;
sleep(200);
}
}
messageAction("截取当前屏幕失败", 9, 1, 0, 1);
};
current_app = Object.assign({}, current_app, new App("蚂蚁森林"));
current_app.first_time_run = true;
current_app.kw_af_title = () => sel.pickup(/蚂蚁森林|Ant Forest/);
current_app.kw_af_home = () => sel.pickup(/合种|背包|通知|攻略|任务|我的大树养成记录/, "kw_af_home");
current_app.kw_list_more_friends = () => sel.pickup("查看更多好友", "kw_list_more_friends");
current_app.kw_rank_list_title = () => sel.pickup(/好友排行榜|Green heroes/, "kw_rank_list_title");
current_app.kw_wait_for_awhile = () => sel.pickup(/.*稍等片刻.*/, "kw_wait_for_awhile");
current_app.kw_reload_forest_page_btn = () => sel.pickup("重新加载", "kw_reload_forest_page_btn");
current_app.kw_close_btn = () => sel.pickup(/关闭|Close/, "kw_close_btn");
current_app.kw_back_btn = () => sel.pickup("返回", "kw_back_btn_common");
current_app.kw_rank_list = () => {
let ref = [
[idMatches(/.*J_rank_list_append/), 0],
[idMatches(/.*J_rank_list/), 0]
];
for (let i = 0, len = ref.length; i < len; i += 1) {
let arr = ref[i];
let node = arr[0].findOnce();
if (!node) continue;
arr[1] = node.childCount();
if (arr[1] > 5) {
if (i === 0) return (current_app.kw_rank_list = () => idMatches(/.*J_rank_list_append/))();
if (i === 1) return (current_app.kw_rank_list = () => idMatches(/.*J_rank_list/))();
}
}
return ref.sort((a, b) => b[1] - a[1])[0][0];
};
current_app.kw_rank_list_more = idMatches(/.*J_rank_list_more/);
current_app.kw_rank_list_self = idMatches(/.*J_rank_list_self/);
current_app.kw_login_or_switch = idMatches(/.*switchAccount|.*loginButton/);
current_app.ori_app_package = currentPackage();
current_app.kill_when_done = current_app.ori_app_package !== current_app.package_name;
current_app.logged_blacklist_names = [];
current_app.homepage_intent = {
action: "VIEW",
data_backup: encodeURIParams("alipays://platformapi/startapp", {
saId: 20000067,
url: "https://60000002.h5app.alipay.com/www/home.html",
__webview_options__: {
showOptionMenu: "YES",
startMultApp: "YES",
enableScrollBar: "NO",
},
}),
data: encodeURIParams("alipays://platformapi/startapp", {
appId: 60000002,
appClearTop: "NO",
startMultApp: "YES",
// enableScrollBar: "NO",
// backBehavior: "auto",
defaultTitle: "",
}),
};
current_app.rank_list_intent = {
action: "VIEW",
data: encodeURIParams("alipays://platformapi/startapp", {
saId: 20000067,
url: "https://60000002.h5app.alipay.com/www/listRank.html",
__webview_options__: {
startMultApp: "YES",
showOptionMenu: "YES",
appClearTop: "NO",
enableScrollBar: "NO",
defaultTitle: "",
transparentTitle: "none",
},
}),
};
current_app.rank_list_icon_collect = storage_af.get("af_rank_list_icon_collect");
current_app.rank_list_icon_help = storage_af.get("af_rank_list_icon_help");
current_app.rank_list_bottom_template_path = files.getSdcardPath() + "/.local/Pics/rank_list_bottom_template.png";
current_app.rank_list_bottom_template = images.read(current_app.rank_list_bottom_template_path);
current_app.current_file_path = files.path("./Ant_Forest_Launcher.js");
current_app.total_energy_collect_own = 0;
current_app.total_energy_collect_friends = 0;
current_app.rank_list_friend_max_invalid_drop_by_times = 5;
current_app.friend_drop_by_counter = {
get increase() {
return (name) => {
this[name] = this[name] || 0;
if (this[name] >= current_app.rank_list_friend_max_invalid_drop_by_times) {
debugInfo("发送停止排行榜样本停止复查信号");
return current_app.rank_list_review_stop_signal = true;
}
if (!this[name]) this[name] = 1;
else this[name] += 1;
};
},
get decrease() {
return (name) => {
this[name] = this[name] || 0;
if (this[name] > 1) this[name] -= 1;
else this[name] = 0;
};
},
};
debugInfo("会话参数赋值完毕");
checkAlipayVer();
setMaxRunTime();
// constructor //
function App(name) {
this.name = name;
this.quote_name = "\"" + name + "\"";
this.package_name = getAlipayPkgName();
this.specific_user = setSpecificUser();
this.blacklist = handleFirstTimeRunBlacklist();
// tool function(s) //
function getAlipayPkgName() {
let default_pkg = "com.eg.android.AlipayGphone";
if (app.getAppName(default_pkg)) return default_pkg;
let result;
let pkg_samples = ["Alipay", "支付宝", "支付寶"],
joined_pkg_name = "\"" + pkg_samples.join("\/") + "\"";
for (let i = 0, len = pkg_samples.length; i < len; i += 1) {
if ((result = app.getPackageName(pkg_samples[i]))) {
messageAction("已获取新的" + joined_pkg_name + "包名", 3, 1);
messageAction(result, 3, 0, 1);
init_operation_logged = 1;
return result;
}
}
return messageAction("此设备未安装\"" + pkg_samples.join("\/") + "\"软件", 8, 1);
}
function setSpecificUser() {
return "此功能暂未开发" && false;
}
function handleFirstTimeRunBlacklist() {
let blacklist_title_flag = 0;
let blacklist = storage_af.get("blacklist", {}); // {friend_name: {timestamp::, reason::}}
Object.keys(blacklist).forEach(name => {
if (!checkBlackTimestamp(blacklist[name].timestamp)) {
delete blacklist[name];
blacklistTitle(name);
}
});
blacklist_title_flag && showSplitLine();
return blacklist;
// tool function(s) //
function blacklistTitle(name) {
if (!config.console_log_details && !config.debug_info_switch) return;
if (!blacklist_title_flag) {
init_operation_logged && showSplitLine();
messageAction("已从黑名单中移除:", 1);
blacklist_title_flag = 1;
}
messageAction(name, 1, 0, 1);
}
}
}
// tool function(s) //
function checkAlipayVer() {
let bug_vers = ["i have been free so far"];
let alipay_ver = getVerName(current_app.package_name);
debugInfo("支付宝版本: " + alipay_ver);
if (~bug_vers.indexOf(alipay_ver)) {
messageAction("脚本无法继续", 4);
messageAction("当前支付宝版本存在已知问题", 4);
messageAction("请更换支付宝版本", 8, 1, 1, 1);
}
}
function setMaxRunTime() {
let max = config.max_running_time_global;
if (!max || !+max) return;
threads.start(function () {
setTimeout(() => messageAction("超时强制退出", 8, 1, 0, "both_n"), +max * 60000 + 3000);
});
debugInfo("单次运行最大超时设置完毕");
}
}
}
function launchHomepage(params) {
params = params || {};
if (current_app.first_time_run) {
messageAction("开始" + current_app.quote_name + "任务", 1, 1, 0, "both");
current_app.first_time_run = false;
Object.assign(params, {screen_orientation: 0});
}
let launch_result = plans.bind(this)("launchHomepage", Object.assign({}, {exclude: "_test_"}, params));
if (screen_orientation !== 0) setScreenPixelData("refresh");
return launch_result;
}
function launchRankList(params) {
return plans.bind(this)("launchRankList", Object.assign({}, {exclude: "_test_"}, params || {}));
}
function checkLanguage() {
let title_str = "";
if (!waitForAction(() => {
let title_node = current_app.kw_af_title().findOnce();
let title_desc = title_node && title_node.desc();
let title_text = title_node && title_node.text();
return title_str = title_desc || title_text;
}, 10000, 100)) {
messageAction("语言检测已跳过", 3);
return messageAction("语言检测超时", 3, 0, 1, 1);
}
if (title_str.match(/蚂蚁森林/)) debugInfo("当前支付宝语言: 简体中文");
else {
debugInfo("当前支付宝语言: 英语");
changeLangToChs();
launchHomepage();
}
debugInfo("语言检查完毕");
// tool function(s) //
function changeLangToChs() {
getReady() && ~handleTxtPipeline() && showSplitLine();
function getReady() {
let max_try_times_close_btn = 10;
while (max_try_times_close_btn--) {
if (clickAction(current_app.kw_close_btn())) break;
sleep(500);
}
let kw_homepage = className("android.widget.TextView").idContains("tab_description");
if (waitForAction(kw_homepage, 2000)) return true;
let max_try_times = 5;
while (max_try_times--) {
killThisApp(current_app.package_name);
app.launch(current_app.package_name);
if (waitForAction(kw_homepage, 15000)) break;
}
if (max_try_times < 0) {
messageAction("Language switched failed", 4, 1);
messageAction("Homepage failed to get ready", 4, 0, 1);
return false;
}
return true;
}
function handleTxtPipeline() {
let txt_pipe_line = {
"Me": "_next",
"Settings": "_next",
"General": "_next",
"Language": "_next",
"\u7b80\u4f53\u4e2d\u6587": () => sel.pickup("简体中文").findOnce().parent().parent().parent().children().size() === 2,
"Save": () => !text("Save").exists() && !desc("Save").exists(),
};
let ppl_keys = Object.keys(txt_pipe_line);
for (let i = 0, len = ppl_keys.length; i < len; i += 1) {
let key = ppl_keys[i],
value = txt_pipe_line[key],
next_key = ppl_keys[i + 1],
condition = value === "_next" ? sel.pickup(next_key) : value;
let kw_key = sel.pickup(key);
clickAction(kw_key);
let max_try_times = 5;
while (!waitForAction(condition, 2000) && max_try_times--) clickAction(kw_key);
if (max_try_times < 0) return handleFailure(next_key);
}
return messageAction("Language switched to Chinese (Simplified)", 1, 1);
// tool function(s) //
function handleFailure(title) {
messageAction("Language switched failed", 4, 1);
messageAction(title + " failed to get ready", 4, 0, 1);
}
}
}
}
function checkEnergy() {
let list_end_signal = 0;
let kw_more_friends = () => current_app.kw_list_more_friends();
let kw_energy_balls = (type) => {
type = type || "all";
let regexp_type = {
"normal": /\xa0/,
"ripe": /收集能量\d+克/,
};
regexp_type.all = current_app.combined_kw_energy_balls_regexp || (() => {
let combined_regexp_str = "";
Object.keys(regexp_type).forEach(key => combined_regexp_str += regexp_type[key].source + "|");
return current_app.combined_kw_energy_balls_regexp = new RegExp(combined_regexp_str.replace(/\|$/, ""));
})();
return sel.pickup(regexp_type[type], "kw_energy_balls_" + type); // className("Button") has been removed
};
let blacklist_ident_captures = [];
setBlacklistIdentCapturesProto();
checkOwnEnergy();
checkFriendsEnergy();
setTimers();
// main function(s) //
function checkOwnEnergy() {
if (!config.self_collect_switch) return debugInfo("自收功能未开启");
current_app.total_energy_init = getOwnEnergyAmount("buffer");
let total_init_data = current_app.total_energy_init;
debugInfo("初始能量: " + total_init_data + "g");
debugInfo("开始检查自己能量");
if (!waitForAction([kw_more_friends(), current_app.kw_af_home(), "or"], 12000)) debugInfo("蚂蚁森林主页准备超时");
if (waitForAction(() => kw_energy_balls().exists(), config.max_own_forest_balls_ready_time, 50)) checkEnergyBalls();
let total_collect_data = current_app.total_energy_collect_own;
total_collect_data ? debugInfo("共计收取: " + total_collect_data + "g") : debugInfo("无能量球可收取");
debugInfo("自己能量检查完毕");
// tool function(s) //
function checkEnergyBalls() {
checkRipeBalls();
let condition_a = config.homepage_background_monitor_switch;
let condition_b1 = config.timers_switch;
let condition_b2a = config.homepage_monitor_switch;
let condition_b2b = config.timers_self_manage_switch && config.timers_countdown_check_own_switch;
if (condition_a || condition_b1 && (condition_b2a || condition_b2b)) {
while (getMinCountdownOwn()) checkRemain();
}
// tool function(s) //
function checkRipeBalls() {
while (1) {
let all_balls_size = kw_energy_balls().find().length;
let ripe_balls_nodes = null;
let ripe_balls_size = 0;
let getRipeBallsNodes = () => ripe_balls_nodes = kw_energy_balls("ripe").find();
let getRipeBallsSize = () => ripe_balls_size = getRipeBallsNodes().length;
if (!getRipeBallsSize()) return;
let max_try_times = 5;
while (ripe_balls_size && max_try_times--) {
debugInfo("点击自己成熟能量球: " + ripe_balls_size + "个");
ripe_balls_nodes.forEach((w) => {
clickAction(w.bounds(), "press", {press_time: config.energy_balls_click_interval});
});
if (waitForAction(() => getRipeBallsSize() === 0, 2000, 100)) break;
}
if (max_try_times < 0) return;
current_app.total_energy_collect_own += stabilizer(getOwnEnergyAmount, total_init_data) - total_init_data;
total_init_data += current_app.total_energy_collect_own;
if (all_balls_size < 6) return true;
}
}
function getMinCountdownOwn() {
debugInfo("开始检测自己能量球最小倒计时");
let raw_balls = kw_energy_balls("normal").find();
let raw_balls_len = raw_balls.length;
debugInfo("找到自己未成熟能量球: " + raw_balls_len + "个");
if (!raw_balls_len) {
current_app.min_countdown_own = Infinity;
return debugInfo("自己能量球最小倒计时检测完毕");
} // no countdown, no need to checkRemain
let now = new Date();
let min_countdown_own = Math.min.apply(null, getCountdownData());
let ripe_time = new Date(min_countdown_own);
let padZero = num => ("0" + num).slice(-2);
let hh = +padZero(ripe_time.getHours() - now.getHours());
let mm = +padZero(ripe_time.getMinutes() - now.getMinutes());
let remain_minute = hh * 60 + mm;
debugInfo("自己能量最小倒计时: " + remain_minute + "min");
current_app.min_countdown_own = min_countdown_own; // ripe timestamp
debugInfo("时间数据: " + getNextTimeStr(min_countdown_own));
debugInfo("自己能量球最小倒计时检测完毕");
return config.homepage_monitor_switch && remain_minute <= config.homepage_monitor_threshold; // if needs to checkRemain
// tool function(s) //
function getCountdownData() {
let countdown_data = [];
let thread_get_countdown_data = threads.start(function () {
raw_balls.forEach((node) => {
let max_try_times = 3;
while (max_try_times--) {
clickAction(node, "press");
let data = observeToastMessage(current_app.package_name, /才能收取/, 300); // results array, maybe []
if (data.length) return countdown_data = countdown_data.concat(data);
}
});
});
thread_get_countdown_data.join(6000);
if (thread_get_countdown_data.isAlive()) {
thread_get_countdown_data.interrupt();
messageAction("获取自己能量倒计时超时", 3);
messageAction("最小倒计时数据可能不准确", 3, 0, 1);
}
return countdown_data.map(str => {
let matched_time_arr = str.match(/\d+:\d+/);
if (!matched_time_arr) {
messageAction("无效字串:", 3);
messageAction(str, 3);
return Infinity;
}
let time_str_arr = matched_time_arr[0].split(":").map(value => +value);
let [hh, mm] = time_str_arr;
return +now + (hh * 60 + mm) * 60000; // timestamp of next ripe time (not scheduled launch time)
}).filter(value => value !== Infinity);
}
}
function checkRemain() {
let max_check_time = config.homepage_monitor_threshold * 60000 + 3000; // ms
let old_collect_own = current_app.total_energy_collect_own;
let start_timestamp = +new Date();
messageAction("Non-stop checking time", null, 1);
debugInfo("开始监测自己能量");
device.keepScreenOn(max_check_time);
debugInfo("已设置屏幕常亮");
debugInfo(">最大超时时间: " + max_check_time + "ms");
try {
while (new Date() - start_timestamp < max_check_time) {
if (checkRipeBalls()) break;
sleep(180);
}
} catch (e) {
// nothing to do here
}
messageAction("Checking completed", null, 1);
debugInfo("自己能量监测完毕");
debugInfo("本次监测收取结果: " + (current_app.total_energy_collect_own - old_collect_own) + "g");
device.cancelKeepingAwake();
debugInfo("屏幕常亮已取消");
debugInfo("监测用时: " + ((+new Date() - start_timestamp) / 1000).toFixed(1) + "秒");
}
}
function getOwnEnergyAmount(buffer_flag) {
let regexp_energy_amount = /\d+g/;
if (buffer_flag) {
let condition = () => sel.pickup(regexp_energy_amount).exists() && current_app.kw_af_home().exists();
if (!waitForAction(condition, 8000)) {
debugInfo("尝试刷新总能量值参考控件");
refreshObjects();
if (!condition()) {
debugInfo("刷新无效");
return -1;
}
debugInfo("刷新成功");
}
}
let max_try_times = buffer_flag ? 10 : 1;
while (max_try_times--) {
let node_desc = descMatches(regexp_energy_amount).findOnce();
let node_text = textMatches(regexp_energy_amount).findOnce();
let content_desc = node_desc && node_desc.desc() && node_desc.desc().match(/\d+/);
let content_text = node_text && node_text.text() && node_text.text().match(/\d+/);
if (content_desc && content_desc[0]) return +content_desc[0];
if (content_text && content_text[0]) return +content_text[0];
sleep(200);
}
if (max_try_times < 0) return -1;
}
}
function checkFriendsEnergy(review_flag) {
list_end_signal = 0;
delete current_app.valid_rank_list_icon_clicked;
delete current_app.swipe_by_scroll_down_flag;
delete current_app.min_countdown_friends;
blacklist_ident_captures.splice(0, blacklist_ident_captures.length);
let help_collect_switch = config.help_collect_switch;
let friend_collect_switch = config.friend_collect_switch;
if (!help_collect_switch && !friend_collect_switch) {
debugInfo("跳过好友能量检查");
return debugInfo(">收取功能与帮收功能均已关闭");
}
debugInfo("开始" + (review_flag ? "复查" : "检查") + "好友能量");
if (!rankListReady(review_flag)) return;
let help_balls_coords = {};
let thread_energy_balls_monitor = undefined;
let thread_list_end = threads.start(monitorEndOfListByUiObjThread);
let strategy = config.rank_list_samples_collect_strategy;
debugInfo("排行榜样本采集策略: " + (
(strategy === "image" && "图像识别") || (strategy === "layout" && "布局分析")
));
let max_safe_swipe_times = 1200; // just for avoiding infinite loop
while (max_safe_swipe_times--) {
current_app.current_friend = {};
let targets = getCurrentScreenTargets(); // [[targets_green], [targets_orange]]
let pop_item_0, pop_item_1, pop_item;
while ((pop_item = (pop_item_0 = targets[0].pop()) || (pop_item_1 = targets[1].pop()))) {
let pop_name = pop_item.name;
current_app.current_friend.name = pop_name;
current_app.current_friend.console_logged = 0;
current_app.current_friend.name_logged = 0;
let name_title = pop_name; // maybe undefined
let message_switch_on = config.console_log_details || config.debug_info_switch;
if (message_switch_on && name_title && !current_app.current_friend.name_logged) {
messageAction(name_title, "title");
current_app.current_friend.name_logged = 1;
}
let clickRankListItemFunc = () => {
if (strategy === "image") clickAction([cX(0.5), pop_item.list_item_click_y], "press");
else clickAction(sel.pickup(pop_name), "click");
debugInfo("点击" + (pop_item_0 && "收取目标" || pop_item_1 && "帮收目标"));
};
if (inBlackList(clickRankListItemFunc)) continue;
forestPageGetReady() && collectBalls();
backToHeroList();
if (message_switch_on) {
!current_app.current_friend.console_logged && messageAction("无能量球可操作", 1, 0, 1);
showSplitLine();
}
}
if (!list_end_signal) swipeUp();
else break;
}
if (max_safe_swipe_times < 0) debugInfo("已达最大排行榜滑动次数限制");
if (thread_list_end.isAlive()) {
thread_list_end.interrupt();
debugInfo("排行榜底部监测线程中断");
}
if (reviewSamplesIfNeeded()) return checkFriendsEnergy("review");
debugInfo("好友能量检查完毕");
checkMinCountdownFriendsIfNeeded();
checkOwnCountdownDemand(config.homepage_monitor_threshold);
return list_end_signal;
// tool function(s) //
function rankListReady(review_flag) {
if (!launchRankList({review_flag: review_flag})) return;
if (!this._monster_$_request_screen_capture_flag) {
tryRequestScreenCapture({restart_this_engine_flag: true});
sleep(300);
}
getRankListRefMaterials();
getCurrentUserNickname();
if (!(current_app.thread_expand_hero_list && current_app.thread_expand_hero_list.isAlive())) {
current_app.thread_expand_hero_list = threads.start(expandHeroListThread);
}
if (!current_app.thread_monitor_and_set_user_id) {
current_app.thread_monitor_and_set_user_id = threads.start(monitorAndSetUserIdThread);
}
return true;
// tool function(s) //
function getRankListRefMaterials() {
current_app.rank_list_capt_img = images.captureCurrentScreen();
debugInfo("生成排行榜截图: " + images.getName(current_app.rank_list_capt_img));
sleep(100);
waitForAction(() => current_app.kw_rank_list_title().exists(), 2500, 80); // just in case
getCloseBtnCenterCoord();
let key_node = current_app.kw_rank_list_title().findOnce();
if (!key_node) return debugInfo("排行榜标题控件抓取失败");
let bounds = key_node.bounds();
debugInfo("采集并存储排行榜标题区域样本:");
let [l, t, w, h] = [3, bounds.top, WIDTH - 6, bounds.height()];
debugInfo("(" + l + ", " + t + ", " + (l + w) + ", " + (t + h) + ")");
current_app.rank_list_title_area_capt_bounds = [l, t, w, h];
(current_app.setRankListTitleAreaCapt = () => {
if (!current_app.rank_list_title_area_capt_bounds) return debugInfo("排行榜标题区域边界数据不存在");
return current_app.rank_list_title_area_capt = images.clip.apply(null, [current_app.rank_list_capt_img].concat(current_app.rank_list_title_area_capt_bounds));
})();
}
function getCurrentUserNickname() {
try {
let user_nickname_parent_node = current_app.kw_rank_list_self.findOnce();
if (user_nickname_parent_node) {
let user_nickname_node = user_nickname_parent_node.child(0).child(2);
current_app.user_nickname = user_nickname_node.desc() || user_nickname_node.text() || "";
current_app.user_nickname ? debugInfo("已获取当前用户昵称字符串") : debugInfo("获取到无效的当前用户昵称");
}
} catch (e) {
debugInfo("获取当前用户昵称失败");
}
}
function expandHeroListThread() {
if (!config.rank_list_auto_expand_switch) return debugInfo("排行榜自动展开功能未开启");
debugInfo("已开启排行榜自动展开线程");
let kw_list_more = current_app.kw_rank_list_more;
let click_count = 0;
while (!desc("没有更多了").exists() && !text("没有更多了").exists()) {
clickAction(kw_list_more, "widget");
click_count++;
sleep(200);
let rank_list_node = current_app.kw_rank_list().findOnce();
if (!rank_list_node) continue;
let rank_list_items_size = rank_list_node.childCount() - 1;
if (rank_list_items_size >= config.rank_list_auto_expand_length) {
debugInfo("排行榜自动展开已被终止");
debugInfo("列表项已达阈值: " + config.rank_list_auto_expand_length);
debugInfo("当前列表项数值: " + rank_list_items_size);
debugInfo("发送列表底部控件慢速检测信号");
return current_app.slow_check_kw_end_list_ident_flag = true;
}
}
debugInfo("排行榜展开完毕");
debugInfo(">点击\"查看更多\": " + click_count + "次");
}
function monitorAndSetUserIdThread() {
return; // still not works well
debugInfo("已开启好友UserId监测采集线程");
let old_id = getId();
let new_id = old_id;
while (1) {
while (old_id === new_id) {
sleep(200);
new_id = getId();
}
setId(new_id) && debugInfo("已存储当前好友UserId: .+" + new_id.slice(-4));
old_id = new_id;
}
// tool function(s) //
function getId() {
let user_ids = shell("logcat *:I -d | grep userId=2088").result.match(/userId=2088\d+/g);
return user_ids && user_ids.pop().match(/2088\d+/)[0];
}
function setId(id) {
// users: {
// 208812345678: {
// nickname: "ABC",
// },
// 208823456789: {
// nickname: "DEF",
// },
// }
let name = current_app.current_friend.name;
if (!name) return;
let users = storage_af.get("users", {});
let user = users[id] || {};
if (user.nickname === name) return;
user.nickname = name;
users[id] = user;
storage_af.put("users", users);
return true;
}
}
}
function getCurrentScreenTargets() {
let [targets_green, targets_orange] = [[], []];
config.rank_list_samples_collect_strategy === "image" ? getTargetsByImage() : getTargetsByLayout();
debugInfo("已回收排行榜截图: " + images.getName(current_app.rank_list_capt_img));
current_app.rank_list_capt_img.recycle();
current_app.rank_list_capt_img = null;
return [targets_green, targets_orange];
// tool function(s) //
function getTargetsByLayout() {
let screenAreaSamples = getScreenSamples() || [];
screenAreaSamples.forEach(w => {
let parent_node = w.parent();
if (!parent_node) return debugInfo("采集到无效的排行榜样本");
let state_ident_node = parent_node.child(parent_node.childCount() - 2);
if (state_ident_node.childCount()) return; // exclude identifies with countdown
let find_color_options = getFindColorOptions(parent_node);
// special treatment for first 3 ones
let name_node = parent_node.child(1);
let name = name_node.desc() || name_node.text();
if (!name) {
name_node = parent_node.child(2);
name = name_node.desc() || name_node.text();
}
if (!checkRegion(find_color_options.region)) return;
if (friend_collect_switch) {
let pt_green = images.findColor(current_app.rank_list_capt_img, config.friend_collect_icon_color, Object.assign({}, find_color_options, {threshold: config.friend_collect_icon_threshold}));
if (pt_green) return targets_green.unshift({name: name});
}
if (help_collect_switch) {
let pt_orange = images.findColor(current_app.rank_list_capt_img, config.help_collect_icon_color, Object.assign({}, find_color_options, {threshold: config.help_collect_icon_threshold}));
if (pt_orange) return targets_orange.unshift({name: name});
}
});
// tool function(s) //
function getScreenSamples() {
let regexp_energy_amount = /\d+(\.\d+)?(k?g|t)/;
let max_try_times = 10;
while (max_try_times--) {
let screen_samples = boundsInside(cX(0.7), 0, WIDTH, USABLE_HEIGHT - 1).visibleToUser().filter(function (w) {
let bounds = w.bounds();
if (bounds.bottom > bounds.top) {
let _desc_w = w.desc();
if (_desc_w && _desc_w.match(regexp_energy_amount)) return true;
let _text_w = w.text();
if (_text_w && _text_w.match(regexp_energy_amount)) return true;
}
return false;
}).find();
let screen_samples_size = screen_samples.size();
debugInfo("获取当前屏幕好友样本数量: " + screen_samples_size);
if (screen_samples_size) return screen_samples;
}
return !~debugInfo("刷新样本区域失败");
}
function getFindColorOptions(parent_node) {
let region_ref = {
l: cX(0.7),
t: parent_node.bounds().top,
};
let region = [region_ref.l, region_ref.t, WIDTH - region_ref.l - 3, parent_node.bounds().centerY() - region_ref.t];
debugInfo("排行榜图标取色区域:");
debugInfo("[" + region[0] + ", " + region[1] + ", " + (region[0] + region[2]) + ", " + (region[1] + region[3]) + "]");
return {region: region};
}
function checkRegion(arr) {
let [left, top, right, bottom] = [arr[0], arr[1], arr[0] + arr[2], arr[1] + arr[3]];
if (left < WIDTH / 2) return debugInfo("采集区域left参数异常: " + left);
if (top < 10 || top >= USABLE_HEIGHT) return debugInfo("采集区域top参数异常: " + top);