-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContactRepository.java
More file actions
900 lines (797 loc) · 38.1 KB
/
Copy pathContactRepository.java
File metadata and controls
900 lines (797 loc) · 38.1 KB
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
package com.leshao.v3.db;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.leshao.v3.ContextManager;
import com.leshao.v3.LogWriter;
import com.leshao.v3.model.Contact;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import dalvik.system.DexFile;
import de.robv.android.xposed.XposedHelpers;
public class ContactRepository {
private static final String TAG = "ContactRepository";
private static List<Contact> sAllContacts;
private static List<Contact> sFriends;
private static List<Contact> sGroups;
private static volatile boolean sLoaded = false;
private static volatile boolean sLoading = false;
private static volatile boolean sListenerRegistered = false;
private static long sCurrentUin = -1;
private static Object sDirDb;
private static final Map<String, String> sNickCache = new HashMap<>();
private static final Object sDirLock = new Object();
public static List<Contact> getAll() { return sAllContacts != null ? sAllContacts : Collections.<Contact>emptyList(); }
public static List<Contact> getFriends() { return sFriends != null ? sFriends : Collections.<Contact>emptyList(); }
public static List<Contact> getGroups() { return sGroups != null ? sGroups : Collections.<Contact>emptyList(); }
public static boolean isLoaded() { return sLoaded; }
public static boolean isLoading() { return sLoading; }
public static Contact findByWxid(String wxid) {
if (wxid == null || wxid.isEmpty()) return null;
if (sAllContacts == null) return null;
for (Contact c : sAllContacts) {
if (wxid.equals(c.wxid)) return c;
}
return null;
}
public static void forceReload() {
if (sLoading) return;
long currentUin = getCurrentUin();
if (currentUin > 0 && currentUin != sCurrentUin) {
LogWriter.log(TAG, "UIN changed: " + sCurrentUin + " -> " + currentUin + ", clearing cache");
sAllContacts = null;
sFriends = null;
sGroups = null;
sLoaded = false;
}
if (sLoaded) return;
sCurrentUin = currentUin;
loadContacts();
}
public static void onContactChanged() {
if (!sLoaded || sLoading) return;
LogWriter.log(TAG, "onContactChanged: scheduling reload");
new Thread(() -> {
try { Thread.sleep(2000); } catch (InterruptedException ignored) {}
sLoaded = false;
loadContacts();
}, "leshao-contact-change").start();
}
private static long getCurrentUin() {
try {
android.content.Context ctx = ContextManager.getAppContext();
if (ctx == null) return -1;
SharedPreferences sp = ctx.getSharedPreferences("system_config_prefs", 0);
Object uv = sp.getAll().get("default_uin");
if (uv == null) return -1;
return Long.parseLong(uv.toString());
} catch (Throwable t) { return -1; }
}
public static int categorize(String wxid, int type) {
if (wxid == null) return CAT_EXCLUDED;
if ("filehelper".equals(wxid)) return CAT_SPECIAL;
if (wxid.endsWith("@chatroom")) return CAT_GROUP;
if (wxid.startsWith("gh_")) return CAT_OFFICIAL;
if (wxid.endsWith("@openim")) return CAT_OPENIM;
if (wxid.endsWith("@app") || wxid.endsWith("@talkroom")
|| wxid.endsWith("@lbsroom") || wxid.endsWith("@stranger")) return CAT_EXCLUDED;
if (type == 0) return CAT_FRIEND;
if (type == 1 || type == 2 || type == 3 || type == 4) return CAT_EXCLUDED;
return CAT_EXCLUDED;
}
private static final int CAT_FRIEND = 0;
private static final int CAT_GROUP = 1;
private static final int CAT_OFFICIAL = 2;
private static final int CAT_SPECIAL = 3;
private static final int CAT_OPENIM = 4;
private static final int CAT_EXCLUDED = 5;
private static final int CAT_SYSTEM = 6;
private static final int CAT_STRANGER = 7;
public static void init() {
if (sListenerRegistered) return;
sListenerRegistered = true;
DatabaseProvider.setOnDbReadyListener((db, pwd) -> {
if (sLoaded) return;
LogWriter.log(TAG, "DB ready callback, loading contacts...");
loadContacts();
});
LogWriter.log(TAG, "init: DB ready listener registered");
}
public static boolean loadContacts() {
if (sLoaded) return true;
if (sLoading) return false;
sLoading = true;
LogWriter.log(TAG, "loadContacts START");
try {
// Strategy A: 直接打开 EnMicroMsg.db,反射 ka5.f.s()(最可靠,0 延迟)
LogWriter.log(TAG, "Strategy A: trying direct DB (ka5.f.s)...");
if (loadViaDirectDb()) {
sLoaded = true; sLoading = false;
LogWriter.log(TAG, "loadContacts OK via Strategy A (direct DB)");
return true;
}
// Strategy B: 反射遍历 model.aj(纯内存,零延迟,无需 Hook)
LogWriter.log(TAG, "Strategy B: trying model.aj reflection...");
if (loadViaModelAj()) {
sLoaded = true; sLoading = false;
LogWriter.log(TAG, "loadContacts OK via Strategy B (model.aj reflection)");
return true;
}
// Strategy C: Messaging plugin via findKernelClass
LogWriter.log(TAG, "Strategy C: trying findKernelClass...");
if (loadViaMessagingPlugin()) {
sLoaded = true; sLoading = false;
LogWriter.log(TAG, "loadContacts OK via Strategy C (messaging plugin)");
return true;
}
// Strategy D: DatabaseProvider hooks(最终兜底)
LogWriter.log(TAG, "Strategy D: waiting for DB hooks (max 15s)...");
Object db = waitForDatabase(15000);
LogWriter.log(TAG, "Strategy D: waitForDatabase returned " + (db != null ? "DB" : "null"));
if (db != null && tryQueries(db)) {
sLoaded = true; sLoading = false;
LogWriter.log(TAG, "loadContacts OK via Strategy D (DB hooks)");
return true;
}
LogWriter.log(TAG, "loadContacts FAILED: all strategies exhausted");
sLoading = false;
return false;
} catch (Throwable t) {
LogWriter.log(TAG, "loadContacts ERROR: " + t.getClass().getSimpleName() + ": " + t.getMessage());
sLoading = false;
return false;
}
}
private static boolean tryQueries(Object db) {
return queryContacts(db, "SELECT username, nickname, conRemark, alias, type, verifyFlag"
+ " FROM rcontact"
+ " WHERE deleteFlag = 0"
+ " AND (type = 0 OR username LIKE '%@chatroom')"
+ " ORDER BY CASE WHEN username LIKE '%@chatroom' THEN 1 ELSE 0 END,"
+ " nickname");
}
private static Object waitForDatabase(long timeoutMs) {
long deadline = System.currentTimeMillis() + timeoutMs;
while (System.currentTimeMillis() < deadline) {
Object db = DatabaseProvider.getDatabase();
if (db != null) return db;
try { Thread.sleep(300); } catch (InterruptedException ignored) {}
}
return DatabaseProvider.getDatabase();
}
// ===== Strategy A: ka5.f.s 打开 + Cursor 原生 API + type=0 & verifyFlag>0 =====
private static boolean loadViaDirectDb() {
ClassLoader cl = ContextManager.getClassLoader();
android.content.Context ctx = ContextManager.getAppContext();
if (cl == null || ctx == null) return false;
try {
SharedPreferences sp = ctx.getSharedPreferences("system_config_prefs", 0);
Object uv = sp.getAll().get("default_uin");
if (uv == null) return false;
long uin = Long.parseLong(uv.toString());
LogWriter.log(TAG, "Strategy A: uin=" + uin);
String imei = "1234567890ABCDEF";
try {
String s = (String) cl.loadClass("wo.w0").getMethod("g", boolean.class).invoke(null, true);
if (s != null && !s.isEmpty()) imei = s;
} catch (Throwable e) {}
String dbPath = getDbPath(cl, ctx, uin);
if (dbPath == null) return false;
String pwd = md5(imei + String.valueOf(uin)).substring(0, 7);
// 打开数据库
Class<?> ka5f = cl.loadClass("ka5.f");
Object db = XposedHelpers.callStaticMethod(ka5f, "s", dbPath, pwd, 0, true);
if (db == null) { LogWriter.log(TAG, "Strategy A: ka5.f.s returned null"); return false; }
LogWriter.log(TAG, "Strategy A: DB opened via ka5.f.s");
boolean result = queryContactsWcdb(db);
try { XposedHelpers.callMethod(db, "c"); } catch (Throwable ignored) {}
return result;
} catch (Throwable e) {
LogWriter.log(TAG, "Strategy A ERROR: " + e.getClass().getSimpleName() + ": " + e.getMessage());
return false;
}
}
private static boolean queryContactsWcdb(Object db) {
List<Contact> all = new ArrayList<>();
List<Contact> friends = new ArrayList<>();
List<Contact> groups = new ArrayList<>();
Cursor c = null;
try {
// 好友: type=0 + verifyFlag>0 = 真实好友, 排除fake_/公众号/群聊
String friendsSql = "SELECT * FROM rcontact"
+ " WHERE type = 0 AND verifyFlag > 0 AND deleteFlag = 0"
+ " AND username NOT LIKE '%@chatroom'"
+ " AND username NOT LIKE 'gh_%'"
+ " ORDER BY CASE WHEN conRemark IS NOT NULL AND conRemark != '' THEN 0 ELSE 1 END,"
+ " nickname";
c = (Cursor) XposedHelpers.callMethod(db, "u", friendsSql, null);
while (c.moveToNext()) {
String wxid = c.getString(c.getColumnIndex("username"));
if (wxid == null || wxid.isEmpty()) continue;
int type = c.getInt(c.getColumnIndex("type"));
int verifyFlag = c.getInt(c.getColumnIndex("verifyFlag"));
String nickname = c.getString(c.getColumnIndex("nickname"));
String alias = c.getString(c.getColumnIndex("alias"));
String remark = c.getString(c.getColumnIndex("conRemark"));
Contact contact = new Contact(wxid, nickname, remark, alias, type, 0, 0);
contact.verifyFlag = verifyFlag;
all.add(contact);
friends.add(contact);
}
c.close();
c = null;
// 群聊
String groupsSql = "SELECT username, nickname, conRemark, type, createTime"
+ " FROM rcontact"
+ " WHERE username LIKE '%@chatroom' AND deleteFlag = 0"
+ " ORDER BY nickname";
c = (Cursor) XposedHelpers.callMethod(db, "u", groupsSql, null);
while (c.moveToNext()) {
String wxid = c.getString(c.getColumnIndex("username"));
if (wxid == null || wxid.isEmpty()) continue;
int type = c.getInt(c.getColumnIndex("type"));
String nickname = c.getString(c.getColumnIndex("nickname"));
String remark = c.getString(c.getColumnIndex("conRemark"));
Contact contact = new Contact(wxid, nickname, remark, null, type, 0, 0);
all.add(contact);
groups.add(contact);
}
c.close();
LogWriter.log(TAG, "queryContactsWcdb: friends=" + friends.size()
+ " groups=" + groups.size() + " total=" + all.size());
if (all.isEmpty()) return false;
sAllContacts = all; sFriends = friends; sGroups = groups;
return true;
} catch (Throwable e) {
LogWriter.log(TAG, "queryContactsWcdb ERROR: " + e.getClass().getSimpleName() + ": " + e.getMessage());
return false;
} finally {
if (c != null) try { c.close(); } catch (Throwable ignored) {}
}
}
private static String computeDisplayName(String remark, String alias, String nick, String wxid) {
if (remark != null && !remark.isEmpty()) return remark;
if (alias != null && !alias.isEmpty() && !alias.startsWith("wxid_")) return alias;
if (nick != null && !nick.isEmpty()) return nick;
return wxid;
}
private static String[] getImeiCandidates(ClassLoader cl) {
java.util.List<String> list = new java.util.ArrayList<>();
// 候选1: wo.w0.g(true) — 设备 IMEI
try {
Class<?> wo = cl.loadClass("wo.w0");
Method g = wo.getDeclaredMethod("g", boolean.class);
String imei = (String) g.invoke(null, true);
if (imei != null && !imei.isEmpty() && !imei.equals("1234567890ABCDEF")) {
list.add(imei);
}
} catch (Throwable e) {}
// 候选2: 微信硬编码兜底密码
list.add("1234567890ABCDEF");
// 候选3: IMEI 兜底值
list.add("000000000000000");
list.add("");
return list.toArray(new String[0]);
}
private static String calcPassword(ClassLoader cl, String imei, long uin) {
String input = imei + uin;
// 方法1: 反射 kk.k.g(byte[]) 计算 MD5
try {
Class<?> kk = cl.loadClass("kk.k");
Method g = kk.getDeclaredMethod("g", byte[].class);
String full = (String) g.invoke(null, (Object) input.getBytes("UTF-8"));
return full.substring(0, 7);
} catch (Throwable e) {}
// 方法2: JDK MD5 兜底
return md5(input).substring(0, 7);
}
private static String getDbPath(ClassLoader cl, android.content.Context ctx, long uin) {
try {
// 方法1: 反射 mp0.b.X() + hm0.b0.e(int)
Class<?> mp0b = cl.loadClass("mp0.b");
Method X = mp0b.getDeclaredMethod("X");
String base = (String) X.invoke(null);
Class<?> hm0b0 = cl.loadClass("hm0.b0");
Method e = hm0b0.getDeclaredMethod("e", int.class);
String hash = (String) e.invoke(null, (int) uin);
return base + "MicroMsg/" + hash + "/EnMicroMsg.db";
} catch (Throwable ex) {}
// 方法2: 手动拼接路径
try {
String base = ctx.getFilesDir().getParentFile().getAbsolutePath() + "/";
return base + "MicroMsg/" + md5("mm" + uin) + "/EnMicroMsg.db";
} catch (Throwable e) {
return null;
}
}
private static String md5(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] d = md.digest(input.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte b : d) sb.append(String.format("%02x", b));
return sb.toString();
} catch (Throwable e) { return ""; }
}
// ===== Strategy B: 反射遍历 com.tencent.mm.model.aj 自动发现方法(无需 Hook,零延迟)=====
private static boolean loadViaModelAj() {
ClassLoader cl = ContextManager.getClassLoader();
if (cl == null) return false;
try {
Class<?> ajCls = cl.loadClass("com.tencent.mm.model.aj");
if (ajCls == null) {
LogWriter.log(TAG, "Strategy B: class com.tencent.mm.model.aj not found");
return false;
}
// 遍历所有静态方法,逐个尝试调用,找到返回会话存储对象的方法
java.lang.reflect.Method[] methods = ajCls.getDeclaredMethods();
for (java.lang.reflect.Method m : methods) {
if (!java.lang.reflect.Modifier.isStatic(m.getModifiers())) continue;
if (m.getParameterTypes().length != 0) continue;
Class<?> rt = m.getReturnType();
if (rt == void.class || rt == int.class || rt == long.class
|| rt == boolean.class || rt == String.class || rt.isPrimitive()) continue;
Object convStg;
try {
convStg = m.invoke(null);
} catch (Throwable e) { continue; }
if (convStg == null) continue;
// 检查这个对象是否有 getAll/values/getMap 之类的方法来获取全部会话
Object allConvs = discoverGetAll(convStg);
if (allConvs == null) continue;
// 尝试从会话中提取联系人
List<Contact> all = new ArrayList<>();
List<Contact> friends = new ArrayList<>();
List<Contact> groups = new ArrayList<>();
if (allConvs instanceof Map) {
Map<?, ?> convMap = (Map<?, ?>) allConvs;
LogWriter.log(TAG, "Strategy B: found via " + m.getName() + "(), Map size=" + convMap.size());
for (Object conv : convMap.values()) {
addConvEntry(conv, all, friends, groups);
}
} else if (allConvs instanceof Iterable) {
int cnt = 0;
for (Object conv : (Iterable<?>) allConvs) {
if (addConvEntry(conv, all, friends, groups)) cnt++;
}
LogWriter.log(TAG, "Strategy B: found via " + m.getName() + "(), Iterable size=" + cnt);
} else {
continue;
}
if (all.isEmpty()) continue;
sAllContacts = all; sFriends = friends; sGroups = groups;
LogWriter.log(TAG, "Strategy B OK: all=" + all.size() + " f=" + friends.size() + " g=" + groups.size()
+ " via method=" + m.getName());
return true;
}
LogWriter.log(TAG, "Strategy B: tried " + methods.length + " static methods, none returned valid conv storage");
return false;
} catch (Throwable e) {
LogWriter.log(TAG, "Strategy B ERROR: " + e.getClass().getSimpleName() + ": " + e.getMessage());
return false;
}
}
private static Object discoverGetAll(Object obj) {
// 先检查常见方法名
for (String mn : new String[]{"getAll", "bLw", "aOB", "values", "getMap",
"bLx", "bLy", "aOC", "aOD", "getValues", "toMap", "asMap", "entrySet"}) {
try {
Object result = XposedHelpers.callMethod(obj, mn);
if (result != null && (result instanceof Map || result instanceof Iterable)) {
return result;
}
} catch (Throwable e) {}
}
// 遍历所有无参方法
for (java.lang.reflect.Method m : obj.getClass().getDeclaredMethods()) {
if (m.getParameterTypes().length != 0) continue;
Class<?> rt = m.getReturnType();
if (rt == void.class || rt.isPrimitive()) continue;
try {
Object result = m.invoke(obj);
if (result instanceof Map) return result;
if (result instanceof Iterable && ((Iterable<?>) result).iterator().hasNext()) return result;
} catch (Throwable e) {}
}
return null;
}
private static boolean addConvEntry(Object conv, List<Contact> all, List<Contact> friends, List<Contact> groups) {
try {
String wxid = resolveObjWxid(conv);
if (skipWxid(wxid)) return false;
if (!wxid.endsWith("@chatroom")) return false;
String name = resolveObjName(conv);
if (name == null || name.isEmpty()) name = wxid;
Contact c = new Contact(wxid, name, name, wxid, 1);
all.add(c);
groups.add(c);
return true;
} catch (Throwable e) { return false; }
}
// ===== Strategy C: Messaging plugin via findKernelClass (V21 Strategy 3) =====
private static boolean loadViaMessagingPlugin() {
ClassLoader cl = ContextManager.getClassLoader();
if (cl == null) return false;
try {
Class<?> kernelCls = findKernelClass();
if (kernelCls == null) {
LogWriter.log(TAG, "Strategy C: kernel class not found");
return false;
}
String[] msgPluginClasses = {
"com.tencent.mm.plugin.messenger.foundation.a.n",
"com.tencent.mm.plugin.messenger.foundation.a.m",
"com.tencent.mm.plugin.messenger.foundation.a$n",
"com.tencent.mm.plugin.messenger.foundation.a$m",
};
Object msgSvc = null;
for (String pcn : msgPluginClasses) {
try {
Class<?> pcls = cl.loadClass(pcn);
msgSvc = XposedHelpers.callStaticMethod(kernelCls, "ax", pcls);
break;
} catch (Throwable e) {}
}
if (msgSvc == null) {
LogWriter.log(TAG, "Strategy C: msg service not found");
return false;
}
Object convStg = null;
for (String mn : new String[]{"getConversationStg", "bLx", "bLy", "aOC", "getConvStorage"}) {
try { convStg = XposedHelpers.callMethod(msgSvc, mn); break; }
catch (Throwable e) {}
}
if (convStg == null) {
LogWriter.log(TAG, "Strategy C: conv storage not found");
return false;
}
Object allConvs = null;
for (String mn : new String[]{"getAll", "bLw", "aOB", "values", "getMap"}) {
try { allConvs = XposedHelpers.callMethod(convStg, mn); break; }
catch (Throwable e) {}
}
if (allConvs == null) {
LogWriter.log(TAG, "Strategy C: allConvs not found");
return false;
}
List<Contact> all = new ArrayList<>();
List<Contact> friends = new ArrayList<>();
List<Contact> groups = new ArrayList<>();
if (allConvs instanceof Map) {
Map<?, ?> convMap = (Map<?, ?>) allConvs;
LogWriter.log(TAG, "Strategy C: Map count=" + convMap.size());
for (Object conv : convMap.values()) {
addConvEntry(conv, all, friends, groups);
}
} else {
LogWriter.log(TAG, "Strategy C: unsupported allConvs type: " + allConvs.getClass().getName());
return false;
}
if (all.isEmpty()) return false;
sAllContacts = all; sFriends = friends; sGroups = groups;
LogWriter.log(TAG, "Strategy C OK: all=" + all.size() + " f=" + friends.size() + " g=" + groups.size());
return true;
} catch (Throwable e) {
LogWriter.log(TAG, "Strategy C ERROR: " + e.getClass().getSimpleName() + ": " + e.getMessage());
return false;
}
}
private static Class<?> sCachedKernelClass = null;
private static Class<?> findKernelClass() {
if (sCachedKernelClass != null) return sCachedKernelClass;
ClassLoader cl = ContextManager.getClassLoader();
String apkPath = ContextManager.getApkPath();
if (cl == null) return null;
String[] names = {
"h","g","i","j","f","e","d","c","b","a",
"k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"aa","ab","ac","ad","ae","af","ag","ah",
"Core","Kernel","MMCore","MMKernel","App","MMApp",
"kernel","plugin","service","Platform","SdkPlatform",
};
String[] pkgs = {"com.tencent.mm.kernel.", "com.tencent.mm.app."};
for (String pkg : pkgs) {
for (String name : names) {
try {
Class<?> c = cl.loadClass(pkg + name);
for (Method m : c.getDeclaredMethods()) {
if (Modifier.isStatic(m.getModifiers())
&& m.getParameterTypes().length == 1
&& m.getParameterTypes()[0] == Class.class) {
sCachedKernelClass = c;
LogWriter.log(TAG, "findKernel: FOUND " + pkg + name + " method=" + m.getName());
return c;
}
}
} catch (Throwable ignored) {}
}
}
if (apkPath != null) {
try {
DexFile df = new DexFile(apkPath);
Enumeration<String> entries = df.entries();
int scanned = 0;
while (entries.hasMoreElements()) {
String cn = entries.nextElement();
if (cn.startsWith("com.tencent.mm.kernel.") || cn.startsWith("com.tencent.mm.app.")) {
scanned++;
try {
Class<?> c = df.loadClass(cn, cl);
for (Method m : c.getDeclaredMethods()) {
if (Modifier.isStatic(m.getModifiers())
&& m.getParameterTypes().length == 1
&& m.getParameterTypes()[0] == Class.class) {
sCachedKernelClass = c;
LogWriter.log(TAG, "findKernel: DexFile FOUND " + cn + " method=" + m.getName());
df.close();
return c;
}
}
} catch (Throwable ignored) {}
}
}
df.close();
LogWriter.log(TAG, "findKernel: DexFile scanned=" + scanned + " no match");
} catch (Throwable e) {
LogWriter.log(TAG, "findKernel: DexFile error: " + e.getMessage());
}
}
return null;
}
// ===== SQL 查询 =====
private static boolean queryContacts(Object db, String sql) {
List<Contact> all = new ArrayList<>();
List<Contact> friends = new ArrayList<>();
List<Contact> groups = new ArrayList<>();
Object cursor = null;
try {
cursor = XposedHelpers.callMethod(db, "rawQuery", sql, null);
int ciU = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "username");
int ciA = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "alias");
int ciR = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "conRemark");
int ciN = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "nickname");
int ciT = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "type");
LogWriter.log(TAG, "queryContacts columns: u=" + ciU + " r=" + ciR + " n=" + ciN
+ " a=" + ciA + " t=" + ciT);
int fb = 0, gb = 0;
while ((Boolean) XposedHelpers.callMethod(cursor, "moveToNext")) {
String wxid = colStr(cursor, ciU);
int type = colInt(cursor, ciT);
int cat = categorize(wxid, type);
if (cat == CAT_OFFICIAL || cat == CAT_EXCLUDED || cat == CAT_SPECIAL) continue;
Contact c = new Contact(wxid, colStr(cursor, ciN), colStr(cursor, ciR), colStr(cursor, ciA), type, 0, 0);
all.add(c);
if (cat == CAT_GROUP) { groups.add(c); gb++; }
else { friends.add(c); fb++; }
}
XposedHelpers.callMethod(cursor, "close");
cursor = null;
LogWriter.log(TAG, "queryContacts OK: all=" + all.size() + " f=" + fb + " g=" + gb);
if (all.isEmpty()) return false;
sAllContacts = all; sFriends = friends; sGroups = groups;
return true;
} catch (Throwable e) {
LogWriter.log(TAG, "queryContacts ERROR: " + e.getClass().getSimpleName() + ": " + e.getMessage());
return false;
} finally {
if (cursor != null) {
try { XposedHelpers.callMethod(cursor, "close"); } catch (Throwable ignored) {}
}
}
}
// ===== 工具方法 =====
private static String resolveObjWxid(Object obj) {
if (obj == null) return null;
// 先尝试常见名称
String[] getters = {"getWxid", "getUsername", "getChatRoomName", "getChatroomName",
"getRoomId", "getTalker", "bLp", "aOM", "getWxId", "field_username",
"getWxusername", "getStrangerName", "getEncryptUsername"};
for (String mn : getters) {
try { String r = (String) obj.getClass().getMethod(mn).invoke(obj);
if (r != null && !r.isEmpty()) return r; }
catch (Throwable e) {}
}
// 遍历所有返回 String 的无参方法
for (java.lang.reflect.Method m : obj.getClass().getDeclaredMethods()) {
if (m.getParameterTypes().length != 0) continue;
if (m.getReturnType() != String.class) continue;
try {
String r = (String) m.invoke(obj);
if (r != null && !r.isEmpty() && r.length() > 4) {
// wxid 特征: 包含 @chatroom 或长度适中
if (r.contains("@") || (r.length() >= 6 && r.length() <= 64)) return r;
}
} catch (Throwable e) {}
}
return null;
}
private static String resolveObjName(Object obj) {
if (obj == null) return null;
String[] getters = {"getRemarkName", "getNickname", "getDisplayName", "getConRemark",
"getName", "getShowName", "getAlias", "field_nickname", "field_conRemark"};
for (String mn : getters) {
try {
Object r = obj.getClass().getMethod(mn).invoke(obj);
if (r instanceof String && !((String) r).isEmpty()) return (String) r;
} catch (Throwable e) {}
}
// 遍历所有返回 String 的无参方法
for (java.lang.reflect.Method m : obj.getClass().getDeclaredMethods()) {
if (m.getParameterTypes().length != 0) continue;
if (m.getReturnType() != String.class) continue;
try {
String r = (String) m.invoke(obj);
if (r != null && !r.isEmpty() && r.length() > 1 && r.length() < 128
&& !r.startsWith("wxid_") && !r.contains("@chatroom") && !r.contains("@")) {
return r;
}
} catch (Throwable e) {}
}
return null;
}
private static boolean skipWxid(String wxid) {
if (wxid == null || wxid.isEmpty()) return true;
if ("filehelper".equals(wxid)) return true;
if ("weixin".equals(wxid)) return true;
if ("notifymessage".equals(wxid)) return true;
if ("medianote".equals(wxid)) return true;
if ("wechat".equals(wxid)) return true;
if ("tmessage".equals(wxid)) return true;
if ("qmessage".equals(wxid)) return true;
if ("floatbottle".equals(wxid)) return true;
if ("newsapp".equals(wxid)) return true;
if ("blog_app".equals(wxid)) return true;
if ("masssendapp".equals(wxid)) return true;
if ("meishiapp".equals(wxid)) return true;
if ("fmessage".equals(wxid)) return true;
if ("voipapp".equals(wxid)) return true;
if ("officialaccounts".equals(wxid)) return true;
if ("helper_entry".equals(wxid)) return true;
if ("pc_share".equals(wxid)) return true;
if ("cardpackage".equals(wxid)) return true;
if ("googlecontact".equals(wxid)) return true;
if ("linkedincontact".equals(wxid)) return true;
if ("mobileconta".equals(wxid)) return true;
if (wxid.startsWith("gh_")) return true;
if (wxid.contains("@lbsroom")) return true;
if (wxid.contains("@openim")) return true;
if (wxid.contains("@im.chatroom")) return true;
if (wxid.startsWith("qqmail_")) return true;
return false;
}
public static String queryNickFromDB(String wxid) {
if (wxid == null || wxid.isEmpty()) return null;
String cached = sNickCache.get(wxid);
if (cached != null) return cached;
String name = null;
Object db = ensureDirDb();
if (db != null) {
Object cursor = null;
try {
cursor = XposedHelpers.callMethod(db, "u",
"SELECT conRemark, nickname FROM rcontact WHERE username=?",
new String[]{wxid});
if (cursor != null) {
int ciR = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "conRemark");
int ciN = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "nickname");
while ((Boolean) XposedHelpers.callMethod(cursor, "moveToNext")) {
String r = colStr(cursor, ciR);
String n = colStr(cursor, ciN);
if (r != null && !r.isEmpty()) name = r;
else if (n != null && !n.isEmpty()) name = n;
break;
}
XposedHelpers.callMethod(cursor, "close");
}
} catch (Throwable t) {
LogWriter.log(TAG, "queryNick[dir] err: " + t.getMessage());
} finally {
if (cursor != null) {
try { XposedHelpers.callMethod(cursor, "close"); } catch (Throwable ignored) {}
}
}
}
if (name == null) {
Object ddb = DatabaseProvider.getDatabase();
if (ddb != null) {
Object cursor = null;
try {
cursor = XposedHelpers.callMethod(ddb, "rawQuery",
"SELECT conRemark, nickname FROM rcontact WHERE username=?",
new String[]{wxid});
if (cursor != null) {
int ciR = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "conRemark");
int ciN = (Integer) XposedHelpers.callMethod(cursor, "getColumnIndex", "nickname");
while ((Boolean) XposedHelpers.callMethod(cursor, "moveToNext")) {
String r = colStr(cursor, ciR);
String n = colStr(cursor, ciN);
if (r != null && !r.isEmpty()) name = r;
else if (n != null && !n.isEmpty()) name = n;
break;
}
XposedHelpers.callMethod(cursor, "close");
}
} catch (Throwable t) {
LogWriter.log(TAG, "queryNick[dbp] err: " + t.getMessage());
} finally {
if (cursor != null) {
try { XposedHelpers.callMethod(cursor, "close"); } catch (Throwable ignored) {}
}
}
}
}
if (name == null) name = "";
sNickCache.put(wxid, name);
if (name.isEmpty()) {
LogWriter.log(TAG, "queryNick: " + truncate(wxid) + " -> (not found)");
}
return name.isEmpty() ? null : name;
}
private static Object ensureDirDb() {
if (sDirDb != null) return sDirDb;
ClassLoader cl = ContextManager.getClassLoader();
if (cl == null) return null;
synchronized (sDirLock) {
if (sDirDb != null) return sDirDb;
try {
android.content.Context ctx = ContextManager.getAppContext();
if (ctx == null) {
LogWriter.log(TAG, "ensureDirDb: Context is null");
return null;
}
SharedPreferences sp = ctx.getSharedPreferences("system_config_prefs", 0);
Object uv = sp.getAll().get("default_uin");
if (uv == null) {
LogWriter.log(TAG, "ensureDirDb: uin not found");
return null;
}
long uin = Long.parseLong(uv.toString());
String dbPath = getDbPath(cl, ctx, uin);
if (dbPath == null) {
LogWriter.log(TAG, "ensureDirDb: dbPath is null");
return null;
}
String[] imeiCandidates = getImeiCandidates(cl);
for (String imei : imeiCandidates) {
if (imei == null || imei.isEmpty()) continue;
String password = calcPassword(cl, imei, uin);
if (password == null || password.length() != 7) continue;
Object db = null;
try {
Method sMethod = cl.loadClass("ka5.f").getMethod("s",
String.class, String.class, int.class, boolean.class);
db = sMethod.invoke(null, dbPath, password, 0, true);
} catch (Throwable e) {}
if (db != null) {
sDirDb = db;
LogWriter.log(TAG, "ensureDirDb OK");
return db;
}
}
LogWriter.log(TAG, "ensureDirDb: all password candidates failed");
} catch (Throwable t) {
LogWriter.log(TAG, "ensureDirDb FAIL: " + t.getMessage());
}
return null;
}
}
private static String truncate(String s) {
return s == null ? "" : s.length() > 30 ? s.substring(0, 27) + "..." : s;
}
private static String colStr(Object cursor, int idx) {
if (idx < 0) return "";
try { return (String) XposedHelpers.callMethod(cursor, "getString", idx); } catch (Throwable t) { return ""; }
}
private static int colInt(Object cursor, int idx) {
if (idx < 0) return 0;
try { return (Integer) XposedHelpers.callMethod(cursor, "getInt", idx); } catch (Throwable t) { return 0; }
}
}