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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
//! Personal WeChat (个人微信) channel driver via Tencent ilink API.
//!
//! Uses the same backend as the official `openclaw-weixin` plugin:
//! Base URL: https://ilinkai.weixin.qq.com
//!
//! Flow:
//! 1. QR code login: get_bot_qrcode → scan → get_qrcode_status → bot_token
//! 2. Long-poll: getupdates with get_updates_buf cursor
//! 3. Send: sendmessage with to_user_id + content
//!
//! Config in openclaw.json:
//! channels.wechat.enabled: true
use std::{sync::Arc, time::Duration};
use aes::cipher::{BlockEncrypt, KeyInit};
use anyhow::{Context, Result, bail};
use base64::Engine;
use futures::future::BoxFuture;
use md5::{Digest, Md5};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::time::sleep;
use tracing::{debug, error, info, warn};
use super::{Channel, OutboundMessage};
use crate::channel::chunker::{ChunkConfig, chunk_text};
const ILINK_BASE_URL: &str = "https://ilinkai.weixin.qq.com";
const DEFAULT_BOT_TYPE: &str = "3";
const LONG_POLL_TIMEOUT_MS: u64 = 35_000;
const SEND_TIMEOUT_MS: u64 = 15_000;
/// Build the common ilink API headers.
fn ilink_headers(token: &str, body_len: usize) -> reqwest::header::HeaderMap {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().expect("valid hardcoded header value"));
headers.insert("AuthorizationType", "ilink_bot_token".parse().expect("valid hardcoded header value"));
headers.insert("Content-Length", body_len.to_string().parse().expect("valid Content-Length"));
if !token.is_empty() {
headers.insert("Authorization", format!("Bearer {token}").parse().expect("valid Authorization header"));
}
// X-WECHAT-UIN: random uint32 → decimal string → base64 (simple inline)
let uin: u32 = rand::random();
let uin_str = uin.to_string();
// Minimal base64 encode for a short decimal string
const B64: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut b64 = String::new();
for chunk in uin_str.as_bytes().chunks(3) {
let b0 = chunk[0] as u32;
let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
let t = (b0 << 16) | (b1 << 8) | b2;
b64.push(B64[((t >> 18) & 0x3F) as usize] as char);
b64.push(B64[((t >> 12) & 0x3F) as usize] as char);
b64.push(if chunk.len() > 1 {
B64[((t >> 6) & 0x3F) as usize] as char
} else {
'='
});
b64.push(if chunk.len() > 2 {
B64[(t & 0x3F) as usize] as char
} else {
'='
});
}
headers.insert("X-WECHAT-UIN", b64.parse().expect("valid base64 header value"));
headers
}
// ---------------------------------------------------------------------------
// API types
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
struct QrCodeResponse {
qrcode: Option<String>,
qrcode_img_content: Option<String>,
}
#[derive(Debug, Deserialize)]
struct QrStatusResponse {
status: Option<String>,
bot_token: Option<String>,
ilink_bot_id: Option<String>,
ilink_user_id: Option<String>,
}
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
struct GetUpdatesResponse {
ret: Option<i32>,
msgs: Option<Vec<WeixinMessage>>,
get_updates_buf: Option<String>,
}
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
struct WeixinMessage {
from_user_id: Option<String>,
to_user_id: Option<String>,
message_type: Option<i32>,
message_state: Option<i32>,
item_list: Option<Vec<MessageItem>>,
context_token: Option<String>,
}
// Message item types (ilink API):
// 0 = NONE, 1 = TEXT, 2 = IMAGE, 3 = VOICE, 4 = FILE, 5 = VIDEO
#[derive(Debug, Clone, Deserialize)]
struct MessageItem {
#[serde(rename = "type")]
item_type: Option<i32>,
text_item: Option<TextItem>,
voice_item: Option<VoiceItem>,
file_item: Option<FileItem>,
image_item: Option<ImageItem>,
video_item: Option<VideoItem>,
}
#[derive(Debug, Clone, Deserialize)]
struct TextItem {
text: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
struct VoiceItem {
voice_url: Option<String>,
/// Voice-to-text result from WeChat (if available, skip transcription).
text: Option<String>,
/// ilink v2: nested media object with encrypt_query_param
media: Option<MediaRef>,
}
#[derive(Debug, Clone, Deserialize)]
struct MediaRef {
encrypt_query_param: Option<String>,
aes_key: Option<String>,
}
/// Default WeChat CDN base URL for media download.
const WECHAT_CDN_BASE: &str = "https://novac2c.cdn.weixin.qq.com/c2c";
/// Media source: direct URL or CDN media (encrypt_query_param + aes_key).
#[derive(Debug)]
enum MediaSource {
Url(String),
Cdn { encrypt_query_param: String, aes_key: String },
}
#[derive(Debug, Clone, Deserialize)]
struct FileItem {
file_url: Option<String>,
file_name: Option<String>,
media: Option<MediaRef>,
}
#[derive(Debug, Clone, Deserialize)]
struct ImageItem {
image_url: Option<String>,
/// Top-level hex AES key (image-specific, takes priority over media.aes_key).
aeskey: Option<String>,
/// ilink v2: nested media object with encrypt_query_param
media: Option<MediaRef>,
}
#[derive(Debug, Clone, Deserialize)]
struct VideoItem {
media: Option<MediaRef>,
}
#[allow(dead_code)]
#[derive(Debug, Serialize)]
struct SendMessageReq {
to_user_id: String,
content: String,
msg_type: i32,
base_info: serde_json::Value,
}
/// Response from ilink/bot/getuploadurl.
/// API may return either `upload_param` (raw param) or `upload_full_url` (full CDN URL).
#[derive(Debug, Deserialize)]
struct GetUploadUrlResponse {
upload_param: Option<String>,
/// Some API versions return the full upload URL instead of just the param.
upload_full_url: Option<String>,
#[allow(dead_code)]
thumb_upload_param: Option<String>,
}
/// Info about a successfully uploaded file on the WeChat CDN.
#[derive(Debug)]
#[allow(dead_code)]
struct UploadedFileInfo {
/// CDN download encrypted_query_param (returned by CDN after upload).
download_param: String,
/// AES-128-ECB key as hex string (32 hex chars = 16 bytes).
aes_key_hex: String,
/// Plaintext file size in bytes.
file_size: usize,
/// Ciphertext (AES-padded) file size in bytes.
file_size_ciphertext: usize,
}
/// ilink media type for getuploadurl.
#[derive(Debug, Clone, Copy)]
#[repr(i32)]
#[allow(dead_code)]
enum UploadMediaType {
Image = 1,
#[allow(dead_code)]
Video = 2,
File = 3,
#[allow(dead_code)]
Voice = 4,
}
const UPLOAD_MAX_RETRIES: u32 = 3;
// ---------------------------------------------------------------------------
// WeChatPersonalChannel
// ---------------------------------------------------------------------------
pub struct WeChatPersonalChannel {
base_url: String,
bot_token: String,
client: Client,
#[allow(clippy::type_complexity)]
on_message: Arc<dyn Fn(String, String, Vec<crate::agent::registry::ImageAttachment>, Vec<crate::agent::registry::FileAttachment>) + Send + Sync>,
}
/// Sentinel prefix used in the bail message produced by
/// `WeChatPersonalChannel::check_send_ret`. Callers compare against this
/// to distinguish a notify-side rejection (don't retry, emit fallback)
/// from a genuine network / 5xx failure (do retry).
const NOTIFY_REJECTED_PREFIX: &str = "WECHAT_NOTIFY_REJECTED:";
impl WeChatPersonalChannel {
/// Create from a saved bot_token (after QR login).
pub fn new(bot_token: String, on_message: Arc<dyn Fn(String, String, Vec<crate::agent::registry::ImageAttachment>, Vec<crate::agent::registry::FileAttachment>) + Send + Sync>) -> Self {
Self {
base_url: ILINK_BASE_URL.to_owned(),
bot_token,
client: crate::config::build_proxy_client()
.timeout(Duration::from_millis(LONG_POLL_TIMEOUT_MS + 5000))
.build()
.expect("http client"),
on_message,
}
}
/// Override the ilink API base URL. Used for testing with a mock server.
pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = base_url.into().trim_end_matches('/').to_owned();
self
}
// -----------------------------------------------------------------------
// QR code login (static — used before creating the channel)
// -----------------------------------------------------------------------
/// Fetch a fresh login QR code from ilink. Returns (qrcode_url, qrcode_token).
///
/// The url is what the user must scan; the token is what callers poll
/// `get_qrcode_status` with.
async fn fetch_qr_login(client: &Client) -> Result<(String, String)> {
let url = format!(
"{}/ilink/bot/get_bot_qrcode?bot_type={}",
ILINK_BASE_URL, DEFAULT_BOT_TYPE
);
let resp: QrCodeResponse = client
.post(&url)
.header("Content-Type", "application/json")
.body("{}")
.send()
.await?
.json()
.await?;
let qrcode = resp.qrcode.context("no qrcode in response")?;
// qrcode_img_content is the URL to display as QR code (for scanning).
// qrcode is the token to poll get_qrcode_status with.
let qrcode_url = resp
.qrcode_img_content
.filter(|s| !s.is_empty())
.unwrap_or_else(|| format!("https://login.weixin.qq.com/qrcode/{}", qrcode));
Ok((qrcode_url, qrcode))
}
/// Start QR code login and render it in the terminal (iTerm2 inline image
/// or Unicode fallback). Returns (qrcode_url, session_qrcode) for polling.
pub async fn start_qr_login(client: &Client) -> Result<(String, String)> {
let (qrcode_url, qrcode) = Self::fetch_qr_login(client).await?;
crate::channel::auth::display_qr_terminal(&qrcode_url)?;
Ok((qrcode_url, qrcode))
}
/// Start QR code login silently — write the QR PNG to a temp path without
/// any terminal output or image-viewer popup. Returns (qrcode_url, qrcode).
///
/// Used by Tauri-spawned `rsclaw channels login --quiet` and the
/// `/api/v1/channels/wechat/qr-login` HTTP endpoint, where stdout is null
/// and the desktop UI displays the PNG itself.
pub async fn start_qr_login_silent(client: &Client) -> Result<(String, String)> {
let (qrcode_url, qrcode) = Self::fetch_qr_login(client).await?;
crate::channel::auth::save_qr_to_path(&qrcode_url)?;
Ok((qrcode_url, qrcode))
}
/// Poll for QR code scan result. Returns (bot_token, bot_id) on success.
pub async fn wait_qr_login(client: &Client, qrcode: &str) -> Result<(String, String)> {
let url = format!(
"{}/ilink/bot/get_qrcode_status?qrcode={}",
ILINK_BASE_URL, qrcode
);
println!("Waiting for WeChat scan...");
for attempt in 0..60 {
let resp: QrStatusResponse = client
.post(&url)
.header("Content-Type", "application/json")
.body("{}")
.timeout(Duration::from_millis(LONG_POLL_TIMEOUT_MS))
.send()
.await?
.json()
.await?;
match resp.status.as_deref() {
Some("confirmed") => {
let token = resp.bot_token.context("no bot_token after confirmed")?;
let bot_id = resp
.ilink_bot_id
.context("no ilink_bot_id after confirmed")?;
info!(bot_id = %bot_id, "WeChat login confirmed");
// Save token
crate::channel::auth::save_token(
"wechat",
&json!({
"bot_token": token,
"ilink_bot_id": bot_id,
"ilink_user_id": resp.ilink_user_id,
}),
)?;
return Ok((token, bot_id));
}
Some("scaned") => {
if attempt == 0 {
println!("Scanned! Please confirm on your phone...");
}
}
Some("expired") => {
bail!("QR code expired");
}
_ => {}
}
sleep(Duration::from_secs(2)).await;
}
bail!("QR login timed out (2 minutes)")
}
/// Single-shot poll for QR scan status. Returns:
/// - Ok(Some((bot_token, bot_id))) if confirmed
/// - Ok(None) if still waiting/scanned
/// - Err if expired or failed
pub async fn poll_qr_status(client: &Client, qrcode: &str) -> Result<Option<(String, String)>> {
let url = format!(
"{}/ilink/bot/get_qrcode_status?qrcode={}",
ILINK_BASE_URL, qrcode
);
let resp: QrStatusResponse = client
.post(&url)
.header("Content-Type", "application/json")
.body("{}")
.timeout(Duration::from_millis(LONG_POLL_TIMEOUT_MS))
.send()
.await?
.json()
.await?;
match resp.status.as_deref() {
Some("confirmed") => {
let token = resp.bot_token.context("no bot_token after confirmed")?;
let bot_id = resp
.ilink_bot_id
.context("no ilink_bot_id after confirmed")?;
crate::channel::auth::save_token(
"wechat",
&json!({
"bot_token": token,
"ilink_bot_id": bot_id,
"ilink_user_id": resp.ilink_user_id,
}),
)?;
Ok(Some((token, bot_id)))
}
Some("expired") => bail!("QR code expired"),
_ => Ok(None), // waiting or scanned
}
}
// -----------------------------------------------------------------------
// Message sending
// -----------------------------------------------------------------------
/// Inspect a sendmessage HTTP-200 response body for the ilink `ret` code.
///
/// Wechat's ilink protocol returns `{"ret": -2, ...}` for messages it
/// accepts at HTTP level but refuses to deliver (anti-spam, invalid
/// media reference, similar). Treating this as Ok silently loses the
/// message; treating it as a hard task failure misrepresents what
/// happened (the upstream work, e.g. video gen, actually succeeded).
/// We bail with the `WECHAT_NOTIFY_REJECTED` prefix below so callers
/// can recognise the case and emit a delivery-only fallback rather
/// than re-running the task.
fn check_send_ret(label: &str, resp_body: &str) -> Result<()> {
let parsed: serde_json::Value = match serde_json::from_str(resp_body) {
Ok(v) => v,
Err(_) => return Ok(()), // empty body or non-JSON = treat as ok
};
let ret = parsed.get("ret").and_then(|v| v.as_i64()).unwrap_or(0);
if ret == 0 {
return Ok(());
}
warn!(
label = %label,
ret = ret,
body = %resp_body,
"wechat: ilink ret != 0 — message rejected by upstream (notify failure)"
);
bail!("{NOTIFY_REJECTED_PREFIX}ret={ret}");
}
async fn send_text(&self, to_user_id: &str, text: &str) -> Result<()> {
let url = format!("{}/ilink/bot/sendmessage", self.base_url);
let client_id = uuid::Uuid::new_v4().to_string();
let body = json!({
"msg": {
"from_user_id": "",
"to_user_id": to_user_id,
"client_id": client_id,
"message_type": 2,
"message_state": 2,
"item_list": [{
"type": 1,
"text_item": { "text": text }
}]
},
"base_info": base_info(),
});
let body_str = serde_json::to_string(&body).unwrap_or_default();
let headers = ilink_headers(&self.bot_token, body_str.len());
let resp = self
.client
.post(&url)
.headers(headers)
.timeout(Duration::from_millis(SEND_TIMEOUT_MS))
.body(body_str)
.send()
.await?;
let status = resp.status();
let resp_body = resp.text().await.unwrap_or_default();
info!(status = %status, resp = %resp_body, "wechat: sendmessage response");
if !status.is_success() {
bail!("sendmessage failed: {status} {resp_body}");
}
Self::check_send_ret("send_text", &resp_body)?;
Ok(())
}
// -----------------------------------------------------------------------
// Long-polling
// -----------------------------------------------------------------------
async fn poll_loop(self: Arc<Self>) -> Result<()> {
let mut updates_buf = String::new();
// Try to load saved state
if let Some(saved) = crate::channel::auth::load_token("wechat")
&& let Some(buf) = saved.get("get_updates_buf").and_then(|v| v.as_str())
{
updates_buf = buf.to_owned();
debug!(
buf_len = updates_buf.len(),
"restored updates_buf from saved state"
);
}
info!("WeChat personal long-poll loop started");
loop {
match self.get_updates(&updates_buf).await {
Ok(resp) => {
if let Some(new_buf) = resp.get_updates_buf {
updates_buf = new_buf;
}
if let Some(msgs) = resp.msgs {
info!(count = msgs.len(), "wechat: received updates");
for msg in &msgs {
// Log raw item types for debugging
if let Some(items) = &msg.item_list {
for item in items {
debug!(
item_type = ?item.item_type,
has_text = item.text_item.is_some(),
has_voice = item.voice_item.is_some(),
has_file = item.file_item.is_some(),
has_image = item.image_item.is_some(),
"wechat: message item"
);
}
}
}
for msg in msgs {
let from = msg.from_user_id.unwrap_or_default();
// message_type: 1 = user, 2 = bot (skip bot messages to avoid echo)
if msg.message_type == Some(2) {
continue;
}
// Process items: text, voice, image, file, video
let items = msg.item_list.as_deref().unwrap_or(&[]);
// 1. Text (type 1)
if let Some(t) = items.iter().find_map(|i| {
i.text_item.as_ref().and_then(|t| t.text.clone())
}) {
if !from.is_empty() && !t.is_empty() {
info!(from = %from, text_len = t.len(), "wechat: text message");
(self.on_message)(from.clone(), t, vec![], vec![]);
}
continue;
}
// 2. Voice (type 3) -- prefer WeChat STT, else download+decode+transcribe
if let Some(v) = items.iter().find_map(|i| i.voice_item.as_ref()) {
// WeChat's own speech-to-text
if let Some(stt) = &v.text {
if !stt.is_empty() {
info!(chars = stt.len(), "wechat: using WeChat voice-to-text");
if !from.is_empty() {
// Tag the text so the agent enables
// voice-reply mode for this turn —
// channel-side STT bypasses the
// agent's media_files audio detection.
let tagged = format!("[__VOICE_INPUT__]\n{stt}");
(self.on_message)(from.clone(), tagged, vec![], vec![]);
}
continue;
}
}
// Download and transcribe
let src = resolve_media_source_voice(v);
if let Some(src) = src {
let audio = self.download_media_source(&src).await;
match audio {
Ok(bytes) => {
match crate::channel::transcription::transcribe_audio(
&self.client, &bytes, "voice.silk", "audio/silk",
).await {
Ok(t) if !t.is_empty() => {
info!(chars = t.len(), "wechat: voice transcribed");
if !from.is_empty() {
let tagged = format!("[__VOICE_INPUT__]\n{t}");
(self.on_message)(from.clone(), tagged, vec![], vec![]);
}
}
Ok(_) => warn!("wechat: voice transcription returned empty"),
Err(e) => warn!("wechat: voice transcription failed: {e:#}"),
}
}
Err(e) => warn!("wechat: voice download failed: {e:#}"),
}
}
continue;
}
// 3. Image (type 2)
if let Some(img) = items.iter().find_map(|i| i.image_item.as_ref()) {
let src = resolve_media_source_image(img);
debug!(
has_image_url = img.image_url.is_some(),
has_media = img.media.is_some(),
has_aeskey = img.aeskey.is_some(),
has_src = src.is_some(),
"wechat: image item"
);
if let Some(src) = src {
match self.download_media_source(&src).await {
Ok(bytes) => {
let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
let data_url = format!("data:image/jpeg;base64,{b64}");
let images = vec![crate::agent::registry::ImageAttachment {
data: data_url,
mime_type: "image/jpeg".to_string(),
}];
info!(size = bytes.len(), "wechat: image received");
if !from.is_empty() {
(self.on_message)(from.clone(), crate::i18n::t("describe_image", crate::i18n::default_lang()), images, vec![]);
}
}
Err(e) => warn!("wechat: image download failed: {e:#}"),
}
}
continue;
}
// 4. File (type 4) -- pass raw bytes as FileAttachment
if let Some(f) = items.iter().find_map(|i| i.file_item.as_ref()) {
let src = resolve_media_source_file(f);
if let Some(src) = src {
match self.download_media_source(&src).await {
Ok(bytes) => {
let fname = f.file_name.as_deref().unwrap_or("file.bin");
info!(size = bytes.len(), fname, "wechat: file received, routing to agent");
let fa = crate::agent::registry::FileAttachment {
filename: fname.to_owned(),
data: bytes,
mime_type: "application/octet-stream".to_owned(),
};
if !from.is_empty() {
(self.on_message)(from.clone(), String::new(), vec![], vec![fa]);
}
}
Err(e) => warn!("wechat: file download failed: {e:#}"),
}
}
continue;
}
// 5. Video (type 5) -- download, decrypt, save as file
if let Some(vid) = items.iter().find_map(|i| i.video_item.as_ref()) {
if let Some(m) = &vid.media {
if let Some(param) = &m.encrypt_query_param {
let aes_key = m.aes_key.clone().unwrap_or_default();
let src = MediaSource::Cdn {
encrypt_query_param: param.clone(),
aes_key,
};
match self.download_media_source(&src).await {
Ok(bytes) => {
info!(size = bytes.len(), "wechat: video downloaded");
// Send as both ImageAttachment (for vision models
// that support video) and FileAttachment (for
// audio transcription fallback on other models).
use base64::Engine;
let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
let data_uri = format!("data:video/mp4;base64,{b64}");
let img = crate::agent::registry::ImageAttachment {
data: data_uri,
mime_type: "video/mp4".to_owned(),
};
let fa = crate::agent::registry::FileAttachment {
filename: "video.mp4".to_owned(),
data: bytes,
mime_type: "video/mp4".to_owned(),
};
if !from.is_empty() {
(self.on_message)(from.clone(), crate::i18n::t("describe_video", crate::i18n::default_lang()), vec![img], vec![fa]);
}
}
Err(e) => warn!("wechat: video download failed: {e:#}"),
}
}
}
continue;
}
debug!("wechat: unhandled message item types: {:?}", items.iter().map(|i| i.item_type).collect::<Vec<_>>());
}
}
}
Err(e) => {
warn!("wechat getupdates error: {e:#}");
sleep(Duration::from_secs(5)).await;
}
}
}
}
async fn get_updates(&self, updates_buf: &str) -> Result<GetUpdatesResponse> {
let url = format!("{}/ilink/bot/getupdates", self.base_url);
let body = json!({
"get_updates_buf": updates_buf,
"base_info": base_info(),
});
let body_str = serde_json::to_string(&body).unwrap_or_default();
let headers = ilink_headers(&self.bot_token, body_str.len());
debug!(buf_len = updates_buf.len(), "wechat: calling getupdates");
let resp = self
.client
.post(&url)
.headers(headers)
.timeout(Duration::from_millis(LONG_POLL_TIMEOUT_MS + 5000))
.body(body_str)
.send()
.await?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
info!(status = %status, body = &text[..text.len().min(200)], "wechat: getupdates error");
bail!("getupdates failed: {status} {text}");
}
let parsed: GetUpdatesResponse = serde_json::from_str(&text).with_context(|| {
format!(
"wechat: parse getupdates response: {}",
&text[..text.len().min(300)]
)
})?;
let msg_count = parsed.msgs.as_ref().map(|m| m.len()).unwrap_or(0);
if msg_count > 0 {
info!(msgs = msg_count, "wechat: received updates");
}
Ok(parsed)
}
/// Download media from WeChat CDN and decrypt with AES-128-ECB.
///
/// Flow: GET cdn_url?encrypted_query_param=... -> AES-128-ECB decrypt -> raw bytes
async fn download_cdn_media(&self, encrypt_query_param: &str, aes_key_b64: &str) -> Result<Vec<u8>> {
use aes::cipher::{BlockDecrypt, KeyInit};
let url = format!(
"{}/download?encrypted_query_param={}",
WECHAT_CDN_BASE,
percent_encode(encrypt_query_param),
);
debug!(
url_len = url.len(),
param_len = encrypt_query_param.len(),
aes_key_len = aes_key_b64.len(),
"wechat: CDN download attempt"
);
let resp = self
.client
.get(&url)
.timeout(Duration::from_secs(30))
.send()
.await?;
let status = resp.status();
if !status.is_success() {
let text = resp.text().await.unwrap_or_default();
warn!(
status = %status,
body = &text[..text.len().min(500)],
param_len = encrypt_query_param.len(),
has_aes_key = !aes_key_b64.is_empty(),
"wechat: CDN download failed"
);
bail!("CDN download failed: {status} {}", &text[..text.len().min(200)]);
}
let encrypted = resp.bytes().await?;
info!(size = encrypted.len(), "wechat: CDN download ok");
if aes_key_b64.is_empty() {
// No AES key -- return raw bytes (might already be decrypted)
return Ok(encrypted.to_vec());
}
// Decode AES key: base64 -> try as hex string (voice/video) or raw 16 bytes (image)
let key_decoded = base64::engine::general_purpose::STANDARD
.decode(aes_key_b64)
.context("invalid base64 aes_key")?;
let key_bytes: Vec<u8> = if key_decoded.len() == 32 {
// It's a hex string of 16 bytes: "aabbccdd..." -> [0xaa, 0xbb, ...]
(0..16)
.map(|i| {
let hex = std::str::from_utf8(&key_decoded[i * 2..i * 2 + 2])
.unwrap_or("00");
u8::from_str_radix(hex, 16).unwrap_or(0)
})
.collect()
} else if key_decoded.len() == 16 {
// Raw 16 bytes
key_decoded
} else {
bail!("unexpected aes_key length: {} (expected 16 or 32)", key_decoded.len());
};
// AES-128-ECB decryption
let cipher = aes::Aes128::new_from_slice(&key_bytes)
.context("AES key init failed")?;
let mut data = encrypted.to_vec();
// Pad to 16-byte boundary if needed
let pad = (16 - data.len() % 16) % 16;
data.extend(std::iter::repeat(0u8).take(pad));
for chunk in data.chunks_mut(16) {
let block = aes::Block::from_mut_slice(chunk);
cipher.decrypt_block(block);
}
// Remove PKCS7 padding
if let Some(&last) = data.last() {
let pad_len = last as usize;
if pad_len > 0 && pad_len <= 16 && data.len() >= pad_len {
let valid = data[data.len() - pad_len..].iter().all(|&b| b == last);
if valid {
data.truncate(data.len() - pad_len);
}
}
}
info!(decrypted_size = data.len(), "wechat: media decrypted");
Ok(data)
}
/// Download from either a URL or CDN media source.
async fn download_media_source(&self, src: &MediaSource) -> Result<Vec<u8>> {
match src {
MediaSource::Url(url) => {
crate::channel::transcription::download_file(&self.client, url).await
}
MediaSource::Cdn { encrypt_query_param, aes_key } => {
self.download_cdn_media(encrypt_query_param, aes_key).await
}
}
}
// -----------------------------------------------------------------------
// CDN upload (mirror of download_cdn_media)
// -----------------------------------------------------------------------
/// AES-128-ECB encrypt with PKCS7 padding (mirror of decryption in download_cdn_media).
fn aes_ecb_encrypt(plaintext: &[u8], key: &[u8; 16]) -> Vec<u8> {
let cipher = aes::Aes128::new_from_slice(key).expect("valid 16-byte key");
// PKCS7 padding
let pad_len = 16 - (plaintext.len() % 16);
let mut data = plaintext.to_vec();
data.extend(std::iter::repeat(pad_len as u8).take(pad_len));
// Encrypt each 16-byte block in-place
for chunk in data.chunks_mut(16) {
let block = aes::Block::from_mut_slice(chunk);
cipher.encrypt_block(block);
}
data
}
/// Compute AES-128-ECB ciphertext size (PKCS7 padding to 16-byte boundary).
fn aes_ecb_padded_size(plaintext_size: usize) -> usize {
((plaintext_size + 1 + 15) / 16) * 16
}
/// Call ilink/bot/getuploadurl to get an upload_param for CDN upload.
async fn get_upload_url(
&self,
filekey: &str,
media_type: UploadMediaType,
to_user_id: &str,
rawsize: usize,
rawfilemd5: &str,
filesize: usize,
aeskey_hex: &str,
) -> Result<GetUploadUrlResponse> {
let url = format!("{}/ilink/bot/getuploadurl", self.base_url);
let body = json!({
"filekey": filekey,
"media_type": media_type as i32,
"to_user_id": to_user_id,
"rawsize": rawsize,
"rawfilemd5": rawfilemd5,
"filesize": filesize,
"no_need_thumb": true,
"aeskey": aeskey_hex,
"base_info": base_info(),
});
let body_str = serde_json::to_string(&body).unwrap_or_default();
let headers = ilink_headers(&self.bot_token, body_str.len());
let resp = self
.client
.post(&url)
.headers(headers)
.timeout(Duration::from_millis(SEND_TIMEOUT_MS))
.body(body_str)
.send()
.await
.context("getuploadurl request failed")?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
bail!("getuploadurl failed: {status} {}", &text[..text.len().min(300)]);
}
debug!(response = &text[..text.len().min(500)], "wechat: getuploadurl response");
let parsed: GetUploadUrlResponse = serde_json::from_str(&text)
.with_context(|| format!("parse getuploadurl response: {}", &text[..text.len().min(300)]))?;
if parsed.upload_param.is_none() {
warn!(response = &text[..text.len().min(500)], "wechat: getuploadurl returned no upload_param");
}
Ok(parsed)
}
/// Upload a buffer to the WeChat CDN with AES-128-ECB encryption.
///
/// Returns the CDN download `encrypted_query_param` from the `x-encrypted-param`
/// response header.
async fn upload_to_cdn_url(
&self,
plaintext: &[u8],
cdn_url: &str,
aes_key: &[u8; 16],
) -> Result<String> {
let ciphertext = Self::aes_ecb_encrypt(plaintext, aes_key);
debug!(
ciphertext_len = ciphertext.len(),
"wechat: CDN upload POST"
);
let mut last_err: Option<anyhow::Error> = None;
for attempt in 1..=UPLOAD_MAX_RETRIES {
let resp = self
.client
.post(cdn_url)
.header("Content-Type", "application/octet-stream")
.timeout(Duration::from_secs(120))
.body(ciphertext.clone())
.send()
.await;
let resp = match resp {
Ok(r) => r,
Err(e) => {
error!(attempt, "wechat: CDN upload network error: {e:#}");
last_err = Some(e.into());
continue;
}
};
let status = resp.status();
if status.as_u16() >= 400 && status.as_u16() < 500 {
let err_msg = resp
.headers()
.get("x-error-message")
.and_then(|v| v.to_str().ok())
.map(String::from)
.unwrap_or_else(|| resp.status().to_string());
bail!("CDN upload client error {status}: {err_msg}");
}
if status.as_u16() != 200 {
let err_msg = resp
.headers()
.get("x-error-message")
.and_then(|v| v.to_str().ok())
.map(String::from)
.unwrap_or_else(|| format!("status {status}"));
error!(attempt, "wechat: CDN upload server error: {err_msg}");
last_err = Some(anyhow::anyhow!("CDN upload server error: {err_msg}"));
continue;
}
// Success: extract download param from x-encrypted-param header
let download_param = resp
.headers()
.get("x-encrypted-param")
.and_then(|v| v.to_str().ok())
.map(String::from)
.context("CDN upload response missing x-encrypted-param header")?;
debug!(attempt, "wechat: CDN upload success");
return Ok(download_param);
}
Err(last_err.unwrap_or_else(|| anyhow::anyhow!("CDN upload failed after {UPLOAD_MAX_RETRIES} attempts")))
}
/// Full upload pipeline: read bytes -> hash -> gen keys -> getuploadurl -> CDN upload.
async fn upload_media(
&self,
plaintext: &[u8],
to_user_id: &str,
media_type: UploadMediaType,
) -> Result<UploadedFileInfo> {
let rawsize = plaintext.len();
let rawfilemd5 = hex::encode(Md5::digest(plaintext));
let filesize = Self::aes_ecb_padded_size(rawsize);
// Random filekey (32 hex chars) and AES key (16 bytes)
let filekey = hex::encode(rand::random::<[u8; 16]>());
let aes_key: [u8; 16] = rand::random();
let aes_key_hex = hex::encode(aes_key);
debug!(
rawsize,
filesize,
md5 = %rawfilemd5,
filekey = %filekey,
"wechat: upload_media starting"
);
// Step 1: get upload_param from ilink API
let upload_resp = self
.get_upload_url(&filekey, media_type, to_user_id, rawsize, &rawfilemd5, filesize, &aes_key_hex)
.await?;
// API may return upload_param (raw) or upload_full_url (full CDN URL).
let (cdn_upload_url, _upload_param_for_download) = if let Some(p) = upload_resp.upload_param.clone() {
// Build URL ourselves.
let url = format!(
"{}/upload?encrypted_query_param={}&filekey={}",
WECHAT_CDN_BASE,
percent_encode(&p),
percent_encode(&filekey),
);
(url, p)
} else if let Some(full_url) = upload_resp.upload_full_url {
// Use the full URL directly, add filekey if missing.
let url = if full_url.contains("filekey=") {
full_url.clone()
} else {
format!("{}&filekey={}", full_url, percent_encode(&filekey))
};
// Extract param for download_param response parsing.
let param = upload_resp.upload_param.unwrap_or_default();
(url, param)
} else {
bail!("getuploadurl returned neither upload_param nor upload_full_url");
};
// Step 2: AES encrypt + POST to CDN
let download_param = self
.upload_to_cdn_url(plaintext, &cdn_upload_url, &aes_key)
.await?;
info!(
filekey = %filekey,
rawsize,
filesize,
"wechat: media upload complete"
);
Ok(UploadedFileInfo {
download_param,
aes_key_hex,
file_size: rawsize,
file_size_ciphertext: filesize,
})
}
// -----------------------------------------------------------------------
// Outbound image/file sending
// -----------------------------------------------------------------------
/// Send an image message referencing a previously uploaded file.
async fn send_image_message(
&self,
to_user_id: &str,
uploaded: &UploadedFileInfo,
) -> Result<()> {
let url = format!("{}/ilink/bot/sendmessage", self.base_url);
let client_id = uuid::Uuid::new_v4().to_string();
// Convert hex aeskey string to base64 (encode the hex string as UTF-8 bytes,
// NOT hex-decoded -- matches openclaw's Buffer.from(hexstr).toString("base64"))
let aes_key_b64 = base64::engine::general_purpose::STANDARD.encode(uploaded.aes_key_hex.as_bytes());
let body = json!({
"msg": {
"from_user_id": "",
"to_user_id": to_user_id,
"client_id": client_id,
"message_type": 2,
"message_state": 2,
"item_list": [{
"type": 2,
"image_item": {
"media": {
"encrypt_query_param": uploaded.download_param,
"aes_key": aes_key_b64,
"encrypt_type": 1
},
"mid_size": uploaded.file_size_ciphertext
}
}]
},
"base_info": base_info(),
});
let body_str = serde_json::to_string(&body).unwrap_or_default();
let headers = ilink_headers(&self.bot_token, body_str.len());
let resp = self
.client
.post(&url)
.headers(headers)
.timeout(Duration::from_millis(SEND_TIMEOUT_MS))
.body(body_str)
.send()
.await?;
let status = resp.status();
let resp_body = resp.text().await.unwrap_or_default();
if !status.is_success() {
bail!("send image message failed: {status} {resp_body}");
}
info!(status = %status, resp = %resp_body, "wechat: send_image_message response");
Self::check_send_ret("send_image_message", &resp_body)?;
Ok(())
}
/// Parse a base64 data URI or raw URL image, upload to CDN, and send as image message.
async fn send_outbound_image(&self, to_user_id: &str, image_data_uri: &str) -> Result<()> {
// Decode base64 data URI: "data:image/png;base64,<data>"
// Or download from a plain URL.
let image_bytes = if let Some(rest) = image_data_uri.strip_prefix("data:") {
// data:<mime>;base64,<payload>
let b64_start = rest.find(",").context("invalid data URI: no comma")?;
let payload = &rest[b64_start + 1..];
base64::engine::general_purpose::STANDARD
.decode(payload)
.context("decode base64 image payload")?
} else {
// Treat as URL -- download it
crate::channel::transcription::download_file(&self.client, image_data_uri).await?
};
if image_bytes.is_empty() {
bail!("empty image payload");
}
let uploaded = self
.upload_media(&image_bytes, to_user_id, UploadMediaType::Image)
.await?;
self.send_image_message(to_user_id, &uploaded).await
}
/// Send a file attachment message referencing a previously uploaded file.
async fn send_file_message(
&self,
to_user_id: &str,
file_name: &str,
uploaded: &UploadedFileInfo,
) -> Result<()> {
let url = format!("{}/ilink/bot/sendmessage", self.base_url);
let client_id = uuid::Uuid::new_v4().to_string();
// base64 encode the hex string (as openclaw voice/file aes_key format)
let aes_key_b64 = base64::engine::general_purpose::STANDARD.encode(uploaded.aes_key_hex.as_bytes());
let body = json!({
"msg": {
"from_user_id": "",
"to_user_id": to_user_id,
"client_id": client_id,
"message_type": 2,
"message_state": 2,
"item_list": [{
"type": 4,
"file_item": {
"media": {
"encrypt_query_param": uploaded.download_param,
"aes_key": aes_key_b64,
"encrypt_type": 1
},
"file_name": file_name,
"len": uploaded.file_size.to_string()
}
}]
},
"base_info": base_info(),
});
let body_str = serde_json::to_string(&body).unwrap_or_default();
let headers = ilink_headers(&self.bot_token, body_str.len());
let resp = self
.client
.post(&url)
.headers(headers)
.timeout(Duration::from_millis(SEND_TIMEOUT_MS))
.body(body_str)
.send()
.await?;
let status = resp.status();
let resp_body = resp.text().await.unwrap_or_default();
if !status.is_success() {
bail!("send file message failed: {status} {resp_body}");
}
info!(status = %status, resp = %resp_body, "wechat: send_file_message ok");
Self::check_send_ret("send_file_message", &resp_body)?;
Ok(())
}
/// Convert audio bytes (mp3/wav/ogg) to SILK v3 format for WeChat voice messages.
/// Uses ffmpeg to decode to raw PCM (s16le, mono, 24kHz), then silk-rs to encode.
/// Returns (silk_bytes, duration_ms).
///
/// Currently unused — WeChat voice delivery is staged but not wired into
/// the channel send path yet. See project_wechat_voice.md.
#[allow(dead_code)]
fn convert_to_silk(audio_bytes: &[u8], ext: &str) -> Result<(Vec<u8>, u64)> {
let tmp_src = std::env::temp_dir().join(format!(
"wechat_src_{}.{}",
chrono::Utc::now().timestamp_millis(),
ext
));
let tmp_pcm = std::env::temp_dir().join(format!(
"wechat_pcm_{}.pcm",
chrono::Utc::now().timestamp_millis()
));
std::fs::write(&tmp_src, audio_bytes)?;
// ffmpeg: decode to raw PCM s16le mono 24kHz
let ffmpeg_bin = crate::agent::platform::detect_ffmpeg().unwrap_or_else(|| "ffmpeg".to_owned());
let output = std::process::Command::new(&ffmpeg_bin)
.args([
"-i", &tmp_src.to_string_lossy(),
"-y", "-f", "s16le", "-ar", "24000", "-ac", "1",
&tmp_pcm.to_string_lossy(),
])
.output()
.context("ffmpeg not available for PCM conversion")?;
let _ = std::fs::remove_file(&tmp_src);
if !output.status.success() {
let _ = std::fs::remove_file(&tmp_pcm);
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("ffmpeg PCM conversion failed: {stderr}");
}
let pcm_bytes = std::fs::read(&tmp_pcm)?;
let _ = std::fs::remove_file(&tmp_pcm);
if pcm_bytes.is_empty() {
bail!("ffmpeg produced empty PCM output");
}
// Encode PCM to SILK v3 (Tencent format)
let silk_bytes = silk_rs::encode_silk(&pcm_bytes, 24000, 25000, true)
.map_err(|e| anyhow::anyhow!("silk encode failed: {e:?}"))?;
// Duration from PCM: samples = pcm_bytes / 2 (s16le), rate = 24000
let duration_ms = (pcm_bytes.len() as u64 * 1000) / (24000 * 2);
let duration_ms = duration_ms.max(1000);
info!(pcm_len = pcm_bytes.len(), silk_len = silk_bytes.len(), duration_ms, "wechat: converted audio to silk");
Ok((silk_bytes, duration_ms))
}
/// Send a voice message referencing a previously uploaded voice file.
/// Companion to `convert_to_silk` — wired in when WeChat voice delivery ships.
#[allow(dead_code)]
async fn send_voice_message(
&self,
to_user_id: &str,
uploaded: &UploadedFileInfo,
duration_ms: u64,
) -> Result<()> {
let url = format!("{}/ilink/bot/sendmessage", self.base_url);
let client_id = uuid::Uuid::new_v4().to_string();
// base64 encode the hex string (as openclaw voice/file aes_key format)
let aes_key_b64 = base64::engine::general_purpose::STANDARD.encode(uploaded.aes_key_hex.as_bytes());
let body = json!({
"msg": {
"from_user_id": "",
"to_user_id": to_user_id,
"client_id": client_id,
"message_type": 2,
"message_state": 2,
"item_list": [{
"type": 3,
"voice_item": {
"media": {
"encrypt_query_param": uploaded.download_param,
"aes_key": aes_key_b64,
"encrypt_type": 1
},
"playtime": duration_ms
}
}]
},
"base_info": base_info(),
});
let body_str = serde_json::to_string(&body).unwrap_or_default();
info!(body = %body_str, "wechat: sending voice message");
let headers = ilink_headers(&self.bot_token, body_str.len());
let resp = self
.client
.post(&url)
.headers(headers)
.timeout(Duration::from_millis(SEND_TIMEOUT_MS))
.body(body_str)
.send()
.await?;
let status = resp.status();
let resp_body = resp.text().await.unwrap_or_default();
if !status.is_success() {
bail!("send voice message failed: {status} {resp_body}");
}
info!(status = %status, resp = %resp_body, "wechat: send_voice_message response");
Self::check_send_ret("send_voice_message", &resp_body)?;
Ok(())
}
/// Send a video message referencing a previously uploaded video file.
async fn send_video_message(
&self,
to_user_id: &str,
uploaded: &UploadedFileInfo,
) -> Result<()> {
let url = format!("{}/ilink/bot/sendmessage", self.base_url);
let client_id = uuid::Uuid::new_v4().to_string();
// base64 encode the hex string (as openclaw media aes_key format)
let aes_key_b64 = base64::engine::general_purpose::STANDARD.encode(uploaded.aes_key_hex.as_bytes());
let body = json!({
"msg": {
"from_user_id": "",
"to_user_id": to_user_id,
"client_id": client_id,
"message_type": 2,
"message_state": 2,
"item_list": [{
"type": 5,
"video_item": {
"media": {
"encrypt_query_param": uploaded.download_param,
"aes_key": aes_key_b64,
"encrypt_type": 1
},
"video_size": uploaded.file_size_ciphertext
}
}]
},
"base_info": base_info(),
});
let body_str = serde_json::to_string(&body).unwrap_or_default();
info!(body = %body_str, "wechat: sending video message");
let headers = ilink_headers(&self.bot_token, body_str.len());
let resp = self
.client
.post(&url)
.headers(headers)
.timeout(Duration::from_millis(SEND_TIMEOUT_MS))
.body(body_str)
.send()
.await?;
let status = resp.status();
let resp_body = resp.text().await.unwrap_or_default();
if !status.is_success() {
bail!("send video message failed: {status} {resp_body}");
}
info!(status = %status, resp = %resp_body, "wechat: send_video_message response");
Self::check_send_ret("send_video_message", &resp_body)?;
Ok(())
}
}
/// Wrap an audio file in a minimal black-screen MP4 so WeChat clients
/// render it as a playable video bubble.
///
/// WeChat ilink's silk + send_voice_message path returns 200 OK at the
/// API layer but the Mac/Windows/iOS clients don't show the result as a
/// voice message. The video path works reliably across clients, at the
/// cost of a few hundred KB of black-frame H.264 overhead.
///
/// Requires `ffmpeg` on PATH. Output: 320x240 black frame + AAC audio,
/// `+faststart` for streaming-friendly playback.
async fn audio_to_video_mp4(audio_bytes: &[u8], filename: &str) -> anyhow::Result<Vec<u8>> {
use anyhow::Context;
let tmp_dir = tempfile::tempdir().context("create temp dir for audio→mp4")?;
let ext = std::path::Path::new(filename)
.extension()
.and_then(|s| s.to_str())
.unwrap_or("wav");
let in_path = tmp_dir.path().join(format!("audio.{ext}"));
let out_path = tmp_dir.path().join("voice.mp4");
std::fs::write(&in_path, audio_bytes).context("write audio to temp file")?;
let output = tokio::process::Command::new("ffmpeg")
.args([
"-y",
"-loglevel",
"error",
// Synthetic black video, 1 fps is enough — we only need *something*
// for clients that gate on a video stream. yuv420p is required for
// H.264 to play back on iOS/macOS WeChat clients.
"-f",
"lavfi",
"-i",
"color=c=black:s=320x240:r=1",
"-i",
in_path.to_string_lossy().as_ref(),
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-tune",
"stillimage",
"-preset",
"ultrafast",
"-c:a",
"aac",
"-b:a",
"96k",
"-shortest",
"-movflags",
"+faststart",
out_path.to_string_lossy().as_ref(),
])
.output()
.await
.context("spawn ffmpeg")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!(
"ffmpeg audio→mp4 failed (exit {}): {}",
output.status,
stderr.trim()
);
}
let bytes = std::fs::read(&out_path).context("read mp4 output")?;
Ok(bytes)
}
/// Resolve media source from VoiceItem.
fn resolve_media_source_voice(v: &VoiceItem) -> Option<MediaSource> {
if let Some(url) = &v.voice_url {
return Some(MediaSource::Url(url.clone()));
}
if let Some(m) = &v.media {
if let Some(param) = &m.encrypt_query_param {
return Some(MediaSource::Cdn {
encrypt_query_param: param.clone(),
aes_key: m.aes_key.clone().unwrap_or_default(),
});
}
}
None
}
/// Resolve media source from ImageItem (hex aeskey -> base64 conversion).
fn resolve_media_source_image(img: &ImageItem) -> Option<MediaSource> {
if let Some(url) = &img.image_url {
return Some(MediaSource::Url(url.clone()));
}
if let Some(m) = &img.media {
if let Some(param) = &m.encrypt_query_param {
let key = if let Some(hex_key) = &img.aeskey {
// Image aeskey is hex -> convert to base64 for AES
let bytes: Vec<u8> = (0..hex_key.len() / 2)
.filter_map(|i| u8::from_str_radix(&hex_key[i * 2..i * 2 + 2], 16).ok())
.collect();
base64::engine::general_purpose::STANDARD.encode(&bytes)
} else {
m.aes_key.clone().unwrap_or_default()
};
return Some(MediaSource::Cdn {
encrypt_query_param: param.clone(),
aes_key: key,
});
}
}
None
}
/// Resolve media source from FileItem.
fn resolve_media_source_file(f: &FileItem) -> Option<MediaSource> {
if let Some(url) = &f.file_url {
return Some(MediaSource::Url(url.clone()));
}
if let Some(m) = &f.media {
if let Some(param) = &m.encrypt_query_param {
return Some(MediaSource::Cdn {
encrypt_query_param: param.clone(),
aes_key: m.aes_key.clone().unwrap_or_default(),
});
}
}
None
}
// ---------------------------------------------------------------------------
// Channel trait
// ---------------------------------------------------------------------------
impl Channel for WeChatPersonalChannel {
fn name(&self) -> &str {
"wechat"
}
fn send(&self, msg: OutboundMessage) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
let chunk_cfg = ChunkConfig {
max_chars: 4096,
..Default::default()
};
if !msg.text.trim().is_empty() {
let chunks = chunk_text(&msg.text, &chunk_cfg);
for (i, chunk) in chunks.iter().enumerate() {
match self.send_text(&msg.target_id, chunk).await {
Ok(()) => {}
Err(e) if e.to_string().starts_with(NOTIFY_REJECTED_PREFIX) => {
// Wechat refused this chunk (anti-spam etc).
// Don't propagate — `send_with_retry` would
// re-clone the OutboundMessage and re-send
// every prior chunk, image, and file. Log
// and move on to whatever's left.
warn!(chunk = i, "wechat: text chunk rejected by upstream: {e:#}");
}
Err(e) => return Err(e),
}
}
}
// Upload and send each image
for (i, image_data_uri) in msg.images.iter().enumerate() {
match self.send_outbound_image(&msg.target_id, image_data_uri).await {
Ok(()) => info!(index = i, "wechat: image sent"),
Err(e) => warn!(index = i, "wechat: image send failed: {e:#}"),
}
}
// Send file attachments (audio files -> voice message, others -> file message)
for (idx, (filename, mime, path_or_url)) in msg.files.iter().enumerate() {
let bytes = if path_or_url.starts_with("http://") || path_or_url.starts_with("https://") {
match self.client.get(path_or_url.as_str()).send().await {
Ok(resp) if resp.status().is_success() => {
match resp.bytes().await {
Ok(b) if !b.is_empty() => b.to_vec(),
_ => { warn!(index = idx, "wechat: empty file download"); continue; }
}
}
_ => { warn!(index = idx, "wechat: file download failed: {path_or_url}"); continue; }
}
} else {
match std::fs::read(path_or_url) {
Ok(b) => b,
Err(e) => { warn!(index = idx, "wechat: failed to read file {path_or_url}: {e}"); continue; }
}
};
// Audio files: WeChat ilink's silk + send_voice_message flow
// returns 200 OK at the API layer but the client doesn't
// render the resulting message as a voice bubble (likely
// payload mismatch — ilink isn't documented). Workaround:
// wrap the audio in a minimal black-frame MP4 and send as
// video. WeChat plays MP4s inline with full transport
// controls so the user effectively gets a playable bubble.
let is_audio = crate::channel::is_audio_attachment(mime, filename);
if is_audio {
let mp4_result = audio_to_video_mp4(&bytes, filename).await;
let video_sent = match mp4_result {
Ok(mp4_bytes) => {
match self
.upload_media(&mp4_bytes, &msg.target_id, UploadMediaType::Video)
.await
{
Ok(uploaded) => match self
.send_video_message(&msg.target_id, &uploaded)
.await
{
Ok(()) => {
info!(
index = idx,
filename = %filename,
wav_bytes = bytes.len(),
mp4_bytes = mp4_bytes.len(),
"wechat: audio sent as video"
);
true
}
Err(e) => {
warn!(
index = idx,
"wechat: send_video_message for audio failed (fall back to file): {e:#}"
);
false
}
},
Err(e) => {
warn!(
index = idx,
"wechat: audio→video upload failed (fall back to file): {e:#}"
);
false
}
}
}
Err(e) => {
warn!(
index = idx,
"wechat: ffmpeg audio→mp4 failed (fall back to file): {e:#}"
);
false
}
};
if video_sent {
continue;
}
// Fall through to File-attachment send below.
}
// Video files: upload as Video type and send as video message
let is_video = mime.starts_with("video/")
|| filename.ends_with(".mp4")
|| filename.ends_with(".mov")
|| filename.ends_with(".avi")
|| filename.ends_with(".mkv");
if is_video {
let mut sent = false;
match self.upload_media(&bytes, &msg.target_id, UploadMediaType::Video).await {
Ok(uploaded) => {
match self.send_video_message(&msg.target_id, &uploaded).await {
Ok(()) => {
info!(index = idx, filename = %filename, "wechat: video sent");
sent = true;
}
Err(e) => {
warn!(index = idx, "wechat: send video message failed: {e:#}");
}
}
}
Err(e) => {
warn!(index = idx, "wechat: video upload failed: {e:#}");
}
}
// Fallback: wechat's CDN periodically 5xx's video uploads
// (or times out). Don't leave the user staring at silence —
// tell them where the file is and that we can ship it
// somewhere else (e.g. publish to douyin) without re-running.
if !sent {
let mb_str = format!("{:.1}", bytes.len() as f64 / 1_048_576.0);
let fallback_text = crate::i18n::t_fmt(
"wechat_video_notify_failed",
crate::i18n::default_lang(),
&[
("filename", filename.as_str()),
("mb", &mb_str),
("path", path_or_url.as_str()),
],
);
if let Err(send_err) = self.send_text(&msg.target_id, &fallback_text).await {
warn!(index = idx, "wechat: video fallback text also failed: {send_err:#}");
}
}
continue;
}
// Other files: upload as File type and send as file message
match self.upload_media(&bytes, &msg.target_id, UploadMediaType::File).await {
Ok(uploaded) => {
if let Err(e) = self.send_file_message(&msg.target_id, filename, &uploaded).await {
warn!(index = idx, "wechat: send file message failed: {e:#}");
} else {
info!(index = idx, filename = %filename, "wechat: file sent");
}
}
Err(e) => {
warn!(index = idx, "wechat: file upload failed: {e:#}");
}
}
}
Ok(())
})
}
fn run(self: Arc<Self>) -> BoxFuture<'static, Result<()>> {
Box::pin(async move { self.poll_loop().await })
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/// Percent-encode a string matching JS `encodeURIComponent` behavior.
///
/// JS encodeURIComponent preserves: A-Z a-z 0-9 - _ . ~ ! ' ( ) *
/// Everything else is percent-encoded as %XX (uppercase hex).
fn percent_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len() * 3);
for b in s.bytes() {
match b {
b'A'..=b'Z'
| b'a'..=b'z'
| b'0'..=b'9'
| b'-'
| b'_'
| b'.'
| b'~'
| b'!'
| b'\''
| b'('
| b')'
| b'*' => {
out.push(b as char);
}
_ => {
out.push_str(&format!("%{:02X}", b));
}
}
}
out
}
fn base_info() -> serde_json::Value {
json!({
"channel_version": env!("CARGO_PKG_VERSION")
})
}
// ---------------------------------------------------------------------------
// Tests (require mock_wechat.py running on port 19987)
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
fn init_crypto() {
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
}
/// Build a WeChatPersonalChannel pointing at the mock server.
fn mock_channel(received: Arc<Mutex<Vec<String>>>) -> Arc<WeChatPersonalChannel> {
let rx = Arc::clone(&received);
let on_message = Arc::new(move |_from: String, text: String, _images: Vec<crate::agent::registry::ImageAttachment>, _files: Vec<crate::agent::registry::FileAttachment>| {
rx.lock().unwrap().push(text);
});
Arc::new(
WeChatPersonalChannel::new("mock-token".to_owned(), on_message)
.with_base_url("http://127.0.0.1:19987"),
)
}
/// Verify `with_base_url` overrides the default.
#[test]
fn with_base_url_overrides_default() {
init_crypto();
let ch = WeChatPersonalChannel::new(
"tok".to_owned(),
Arc::new(|_, _, _, _| {}),
)
.with_base_url("http://127.0.0.1:19987");
assert_eq!(ch.base_url, "http://127.0.0.1:19987");
}
/// Verify trailing slash is stripped.
#[test]
fn with_base_url_strips_trailing_slash() {
init_crypto();
let ch = WeChatPersonalChannel::new(
"tok".to_owned(),
Arc::new(|_, _, _, _| {}),
)
.with_base_url("http://127.0.0.1:19987/");
assert_eq!(ch.base_url, "http://127.0.0.1:19987");
}
// -------------------------------------------------------------------
// Unit tests (no network required)
// -------------------------------------------------------------------
/// percent_encode must match JS encodeURIComponent behavior.
/// JS encodeURIComponent preserves: A-Z a-z 0-9 - _ . ~ ! ' ( ) *
#[test]
fn percent_encode_matches_js_encode_uri_component() {
// Base64 string with +, =, /
let input = "abc+def/ghi=jkl==";
let encoded = percent_encode(input);
assert_eq!(encoded, "abc%2Bdef%2Fghi%3Djkl%3D%3D");
// Characters that JS encodeURIComponent preserves (should NOT be encoded)
let preserved = "ABCxyz019-_.~!'()*";
assert_eq!(percent_encode(preserved), preserved);
// Space and special chars must be encoded
assert_eq!(percent_encode(" "), "%20");
assert_eq!(percent_encode("@"), "%40");
assert_eq!(percent_encode("#"), "%23");
assert_eq!(percent_encode("&"), "%26");
// Full base64-like param
let b64 = "dGVzdA==";
assert_eq!(percent_encode(b64), "dGVzdA%3D%3D");
}
/// AES-128-ECB encrypt then decrypt roundtrip must recover original plaintext.
#[test]
fn aes_ecb_encrypt_decrypt_roundtrip() {
use aes::cipher::{BlockDecrypt, KeyInit};
let key: [u8; 16] = [
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF,
];
let plaintext = b"Hello, WeChat CDN AES-128-ECB test data!";
// Encrypt (uses PKCS7 padding)
let ciphertext = WeChatPersonalChannel::aes_ecb_encrypt(plaintext, &key);
// Ciphertext length should be padded to 16-byte boundary
assert_eq!(ciphertext.len() % 16, 0);
assert_ne!(&ciphertext[..], &plaintext[..]);
// Decrypt (mirror of download_cdn_media logic)
let cipher = aes::Aes128::new_from_slice(&key).unwrap();
let mut data = ciphertext.clone();
for chunk in data.chunks_mut(16) {
let block = aes::Block::from_mut_slice(chunk);
cipher.decrypt_block(block);
}
// Remove PKCS7 padding
if let Some(&last) = data.last() {
let pad_len = last as usize;
if pad_len > 0 && pad_len <= 16 && data.len() >= pad_len {
let valid = data[data.len() - pad_len..].iter().all(|&b| b == last);
if valid {
data.truncate(data.len() - pad_len);
}
}
}
assert_eq!(&data, plaintext);
}
/// AES-128-ECB encrypt with known values to verify ciphertext.
#[test]
fn aes_ecb_encrypt_known_vector() {
// 16 bytes of plaintext (no padding needed beyond PKCS7)
let key: [u8; 16] = [0u8; 16];
let plaintext = [0u8; 16];
let ciphertext = WeChatPersonalChannel::aes_ecb_encrypt(&plaintext, &key);
// With PKCS7, 16 bytes of input gets 16 bytes padding -> 32 bytes ciphertext
assert_eq!(ciphertext.len(), 32);
}
/// aes_ecb_padded_size matches openclaw's Math.ceil((size + 1) / 16) * 16.
#[test]
fn aes_ecb_padded_size_matches_openclaw() {
// openclaw: Math.ceil((plaintextSize + 1) / 16) * 16
assert_eq!(WeChatPersonalChannel::aes_ecb_padded_size(0), 16);
assert_eq!(WeChatPersonalChannel::aes_ecb_padded_size(1), 16);
assert_eq!(WeChatPersonalChannel::aes_ecb_padded_size(15), 16);
assert_eq!(WeChatPersonalChannel::aes_ecb_padded_size(16), 32);
assert_eq!(WeChatPersonalChannel::aes_ecb_padded_size(31), 32);
assert_eq!(WeChatPersonalChannel::aes_ecb_padded_size(32), 48);
assert_eq!(WeChatPersonalChannel::aes_ecb_padded_size(100), 112);
}
/// AES key parsing: hex string (32 chars) -> 16 raw bytes.
/// openclaw: parseAesKey decodes base64 -> if 32 ASCII hex chars -> parse hex -> 16 bytes.
/// rsclaw: download_cdn_media does the same.
#[test]
fn aes_key_hex_to_bytes() {
let hex_key = "00112233445566778899aabbccddeeff";
assert_eq!(hex_key.len(), 32);
// Parse hex -> raw bytes (same as rsclaw's download_cdn_media logic)
let key_bytes: Vec<u8> = (0..16)
.map(|i| {
let hex = &hex_key[i * 2..i * 2 + 2];
u8::from_str_radix(hex, 16).unwrap()
})
.collect();
assert_eq!(key_bytes.len(), 16);
assert_eq!(key_bytes[0], 0x00);
assert_eq!(key_bytes[1], 0x11);
assert_eq!(key_bytes[15], 0xFF);
}
/// Image aeskey conversion: hex -> base64(raw bytes).
/// openclaw: Buffer.from(img.aeskey, "hex").toString("base64")
/// rsclaw: resolve_media_source_image does the same.
#[test]
fn aes_key_hex_to_base64_conversion() {
let hex_key = "00112233445566778899aabbccddeeff";
// rsclaw conversion (same as resolve_media_source_image)
let bytes: Vec<u8> = (0..hex_key.len() / 2)
.filter_map(|i| u8::from_str_radix(&hex_key[i * 2..i * 2 + 2], 16).ok())
.collect();
let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
// Verify: base64-decode should give 16 raw bytes
let decoded = base64::engine::general_purpose::STANDARD.decode(&b64).unwrap();
assert_eq!(decoded.len(), 16);
assert_eq!(decoded, bytes);
// And those bytes should match hex parsing
assert_eq!(hex::encode(&decoded), hex_key);
}
/// base64(hex string) -> base64(raw bytes) key conversion.
/// openclaw parseAesKey: decode base64 -> if 32 hex chars -> parse to 16 bytes.
#[test]
fn aes_key_base64_hex_roundtrip() {
let hex_key = "aabbccdd11223344aabbccdd11223344";
// base64 encode the hex string (as openclaw voice/file aes_key format)
let b64_of_hex = base64::engine::general_purpose::STANDARD
.encode(hex_key.as_bytes());
// Decode base64 -> get 32-byte hex string
let decoded = base64::engine::general_purpose::STANDARD
.decode(&b64_of_hex)
.unwrap();
assert_eq!(decoded.len(), 32);
// It's ASCII hex -> parse to 16 raw bytes (rsclaw download_cdn_media logic)
let ascii = std::str::from_utf8(&decoded).unwrap();
assert!(ascii.chars().all(|c| c.is_ascii_hexdigit()));
let key_bytes: Vec<u8> = (0..16)
.map(|i| u8::from_str_radix(&ascii[i * 2..i * 2 + 2], 16).unwrap())
.collect();
assert_eq!(key_bytes.len(), 16);
assert_eq!(hex::encode(&key_bytes), hex_key);
}
/// resolve_media_source_image: prefers image_url, then media with aeskey conversion.
#[test]
fn resolve_media_source_image_prefers_url() {
let img = ImageItem {
image_url: Some("https://example.com/img.jpg".to_string()),
aeskey: None,
media: Some(MediaRef {
encrypt_query_param: Some("param123".to_string()),
aes_key: Some("key123".to_string()),
}),
};
match resolve_media_source_image(&img) {
Some(MediaSource::Url(url)) => assert_eq!(url, "https://example.com/img.jpg"),
other => panic!("expected Url, got {:?}", other),
}
}
/// resolve_media_source_image: with media.encrypt_query_param + aeskey hex conversion.
#[test]
fn resolve_media_source_image_cdn_with_hex_aeskey() {
let hex_key = "aabbccdd11223344aabbccdd11223344";
let img = ImageItem {
image_url: None,
aeskey: Some(hex_key.to_string()),
media: Some(MediaRef {
encrypt_query_param: Some("encrypted_param_value".to_string()),
aes_key: Some("media_aes_key_ignored".to_string()),
}),
};
match resolve_media_source_image(&img) {
Some(MediaSource::Cdn { encrypt_query_param, aes_key }) => {
assert_eq!(encrypt_query_param, "encrypted_param_value");
// aes_key should be base64 of the raw bytes parsed from hex
let decoded = base64::engine::general_purpose::STANDARD.decode(&aes_key).unwrap();
assert_eq!(decoded.len(), 16);
assert_eq!(hex::encode(&decoded), hex_key);
}
other => panic!("expected Cdn, got {:?}", other),
}
}
/// resolve_media_source_image: with media only (no aeskey), uses media.aes_key directly.
#[test]
fn resolve_media_source_image_cdn_media_aes_key() {
let img = ImageItem {
image_url: None,
aeskey: None,
media: Some(MediaRef {
encrypt_query_param: Some("param_xyz".to_string()),
aes_key: Some("base64_media_key".to_string()),
}),
};
match resolve_media_source_image(&img) {
Some(MediaSource::Cdn { encrypt_query_param, aes_key }) => {
assert_eq!(encrypt_query_param, "param_xyz");
assert_eq!(aes_key, "base64_media_key");
}
other => panic!("expected Cdn, got {:?}", other),
}
}
/// resolve_media_source_image: no image_url, no media -> None.
#[test]
fn resolve_media_source_image_returns_none() {
let img = ImageItem {
image_url: None,
aeskey: None,
media: None,
};
assert!(resolve_media_source_image(&img).is_none());
}
/// GetUploadUrlResponse deserialization with upload_param.
#[test]
fn get_upload_url_response_with_upload_param() {
let json = r#"{"upload_param": "abc123", "thumb_upload_param": "thumb456"}"#;
let resp: GetUploadUrlResponse = serde_json::from_str(json).unwrap();
assert_eq!(resp.upload_param.as_deref(), Some("abc123"));
assert_eq!(resp.thumb_upload_param.as_deref(), Some("thumb456"));
assert!(resp.upload_full_url.is_none());
}
/// GetUploadUrlResponse deserialization with upload_full_url.
#[test]
fn get_upload_url_response_with_upload_full_url() {
let json = r#"{"upload_full_url": "https://cdn.example.com/upload?encrypted_query_param=xyz%3D%3D&filekey=abc"}"#;
let resp: GetUploadUrlResponse = serde_json::from_str(json).unwrap();
assert!(resp.upload_param.is_none());
assert_eq!(
resp.upload_full_url.as_deref(),
Some("https://cdn.example.com/upload?encrypted_query_param=xyz%3D%3D&filekey=abc")
);
}
/// CDN download URL construction matches openclaw cdn-url.ts buildCdnDownloadUrl.
#[test]
fn cdn_download_url_construction() {
let param = "some+param/with=chars";
let url = format!(
"{}/download?encrypted_query_param={}",
WECHAT_CDN_BASE,
percent_encode(param),
);
assert_eq!(
url,
"https://novac2c.cdn.weixin.qq.com/c2c/download?encrypted_query_param=some%2Bparam%2Fwith%3Dchars"
);
}
/// CDN upload URL construction matches openclaw cdn-url.ts buildCdnUploadUrl.
#[test]
fn cdn_upload_url_construction() {
let upload_param = "enc+param==";
let filekey = "abc123def456";
let url = format!(
"{}/upload?encrypted_query_param={}&filekey={}",
WECHAT_CDN_BASE,
percent_encode(upload_param),
percent_encode(filekey),
);
assert_eq!(
url,
"https://novac2c.cdn.weixin.qq.com/c2c/upload?encrypted_query_param=enc%2Bparam%3D%3D&filekey=abc123def456"
);
}
/// Extract encrypted_query_param from upload_full_url for CDN URL construction.
#[test]
fn cdn_url_from_upload_full_url_extract_param() {
let full_url = "https://cdn.example.com/upload?encrypted_query_param=xyz%3D%3D&extra=1";
// When upload_full_url is provided, it is used directly (with filekey appended if missing)
let filekey = "myfilekey";
let url = if full_url.contains("filekey=") {
full_url.to_string()
} else {
format!("{}&filekey={}", full_url, percent_encode(filekey))
};
assert_eq!(url, "https://cdn.example.com/upload?encrypted_query_param=xyz%3D%3D&extra=1&filekey=myfilekey");
// When filekey is already present
let full_url2 = "https://cdn.example.com/upload?encrypted_query_param=abc&filekey=existing";
let url2 = if full_url2.contains("filekey=") {
full_url2.to_string()
} else {
format!("{}&filekey={}", full_url2, percent_encode(filekey))
};
assert_eq!(url2, "https://cdn.example.com/upload?encrypted_query_param=abc&filekey=existing");
}
// -------------------------------------------------------------------
// Integration tests (require mock_wechat.py on port 19987)
// -------------------------------------------------------------------
/// Call getupdates against mock_wechat.py and expect 2 messages on first call.
///
/// Run: python3 /tmp/mock_wechat.py (in a separate terminal)
/// Then: cargo test -p rsclaw wechat::tests::mock_getupdates -- --ignored
#[tokio::test]
#[ignore]
async fn mock_getupdates_returns_messages() {
let received = Arc::new(Mutex::new(Vec::<String>::new()));
let ch = mock_channel(Arc::clone(&received));
let resp = ch.get_updates("").await.expect("getupdates failed");
let msgs = resp.msgs.unwrap_or_default();
assert_eq!(msgs.len(), 2, "expected 2 mock messages on first call");
// First message should be a text item
let first = &msgs[0];
let items = first.item_list.as_deref().unwrap_or(&[]);
let text = items
.iter()
.find_map(|i| i.text_item.as_ref().and_then(|t| t.text.as_deref()))
.expect("first message should have text_item");
assert_eq!(text, "Hello from mock WeChat");
// Second message should be a voice item
let second = &msgs[1];
let items2 = second.item_list.as_deref().unwrap_or(&[]);
let voice = items2
.iter()
.find_map(|i| i.voice_item.as_ref())
.expect("second message should have voice_item");
assert_eq!(voice.text.as_deref(), Some("Transcribed voice text"));
}
/// Call getupdates twice; second call should return empty msgs.
///
/// Run: python3 /tmp/mock_wechat.py (restart before test)
/// Then: cargo test -p rsclaw wechat::tests::mock_getupdates_empty_second -- --ignored
#[tokio::test]
#[ignore]
async fn mock_getupdates_empty_second_call() {
let received = Arc::new(Mutex::new(Vec::<String>::new()));
let ch = mock_channel(Arc::clone(&received));
let first = ch.get_updates("").await.expect("first call failed");
let buf = first.get_updates_buf.unwrap_or_default();
let second = ch.get_updates(&buf).await.expect("second call failed");
let msgs = second.msgs.unwrap_or_default();
assert!(msgs.is_empty(), "second call should return no messages");
}
/// Send a text reply to the mock server.
///
/// Run: python3 /tmp/mock_wechat.py
/// Then: cargo test -p rsclaw wechat::tests::mock_send_text -- --ignored
#[tokio::test]
#[ignore]
async fn mock_send_text() {
let ch = WeChatPersonalChannel::new(
"mock-token".to_owned(),
Arc::new(|_, _, _, _| {}),
)
.with_base_url("http://127.0.0.1:19987");
ch.send_text("user_abc", "Hello from rsclaw test")
.await
.expect("send_text failed");
}
}