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
//! DingTalk (钉钉) bot channel driver.
//!
//! Implements the DingTalk Robot API for receiving and sending messages.
//!
//! Features:
//! - Access token management with auto-refresh (2-hour TTL).
//! - Stream Mode WebSocket for receiving inbound messages (no public URL
//! needed).
//! - Send replies via robot batch-send API.
//! - Voice message download and transcription via shared Whisper module.
//! - Text chunking (20000-char limit).
use std::{
sync::Arc,
time::{Duration, Instant},
};
use anyhow::{Context, Result, bail};
use futures::{SinkExt as _, StreamExt as _, future::BoxFuture};
use reqwest::Client;
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::{sync::RwLock, time::sleep};
use tokio_tungstenite::{connect_async, tungstenite::Message as WsMessage};
use tracing::{debug, error, info, warn};
use super::{Channel, OutboundMessage};
use crate::channel::{
chunker::{BreakPreference, ChunkConfig, chunk_text},
telegram::RetryConfig,
};
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const DINGTALK_OAPI_BASE: &str = "https://oapi.dingtalk.com";
const DINGTALK_API_BASE: &str = "https://api.dingtalk.com";
/// DingTalk single-message text limit.
const DINGTALK_CHUNK_LIMIT: usize = 20_000;
/// Access token refresh margin -- refresh 5 minutes before actual expiry.
const TOKEN_REFRESH_MARGIN: Duration = Duration::from_secs(300);
// ---------------------------------------------------------------------------
// API response types
// ---------------------------------------------------------------------------
#[derive(Debug, Deserialize)]
struct TokenResponse {
#[serde(default)]
access_token: String,
#[serde(default)]
expires_in: u64,
#[serde(default)]
errcode: i64,
#[serde(default)]
errmsg: Option<String>,
}
#[derive(Debug, Deserialize)]
struct StreamConnectResponse {
endpoint: Option<String>,
ticket: Option<String>,
}
#[derive(Debug, Deserialize)]
struct FileDownloadResponse {
#[serde(rename = "downloadUrl")]
download_url: Option<String>,
}
// ---------------------------------------------------------------------------
// Cached access token
// ---------------------------------------------------------------------------
#[derive(Debug)]
struct CachedToken {
token: String,
obtained_at: Instant,
expires_in: Duration,
}
impl CachedToken {
fn is_expired(&self) -> bool {
self.obtained_at.elapsed() + TOKEN_REFRESH_MARGIN >= self.expires_in
}
}
// ---------------------------------------------------------------------------
// DingTalkChannel
// ---------------------------------------------------------------------------
pub struct DingTalkChannel {
app_key: String,
app_secret: String,
robot_code: String,
api_base: String,
oapi_base: String,
client: Client,
retry: RetryConfig,
token_cache: RwLock<Option<CachedToken>>,
/// Callback: (sender_id, text, conversation_id, is_group, images).
#[allow(clippy::type_complexity)]
on_message: Arc<
dyn Fn(String, String, String, bool, Vec<crate::agent::registry::ImageAttachment>)
+ Send
+ Sync,
>,
}
impl DingTalkChannel {
pub fn new(
app_key: impl Into<String>,
app_secret: impl Into<String>,
robot_code: impl Into<String>,
api_base: Option<String>,
oapi_base: Option<String>,
on_message: Arc<
dyn Fn(String, String, String, bool, Vec<crate::agent::registry::ImageAttachment>)
+ Send
+ Sync,
>,
) -> Self {
Self {
app_key: app_key.into(),
app_secret: app_secret.into(),
robot_code: robot_code.into(),
api_base: api_base.unwrap_or_else(|| DINGTALK_API_BASE.to_owned()),
oapi_base: oapi_base.unwrap_or_else(|| DINGTALK_OAPI_BASE.to_owned()),
client: crate::config::build_proxy_client()
.timeout(Duration::from_secs(30))
.build()
.expect("reqwest client"),
retry: RetryConfig::default(),
token_cache: RwLock::new(None),
on_message,
}
}
// -----------------------------------------------------------------------
// Access token management
// -----------------------------------------------------------------------
/// Get a valid access token, refreshing if expired.
async fn get_access_token(&self) -> Result<String> {
// Fast path: read lock.
{
let cache = self.token_cache.read().await;
if let Some(ref cached) = *cache
&& !cached.is_expired()
{
return Ok(cached.token.clone());
}
}
// Slow path: write lock + refresh.
let mut cache = self.token_cache.write().await;
// Double-check after acquiring write lock.
if let Some(ref cached) = *cache
&& !cached.is_expired()
{
return Ok(cached.token.clone());
}
let url = format!(
"{}/gettoken?appkey={}&appsecret={}",
self.oapi_base, self.app_key, self.app_secret
);
let resp: TokenResponse = self
.client
.get(&url)
.send()
.await
.context("DingTalk gettoken request")?
.json()
.await
.context("DingTalk gettoken parse")?;
if resp.errcode != 0 {
bail!(
"DingTalk gettoken error {}: {}",
resp.errcode,
resp.errmsg.unwrap_or_default()
);
}
let token = resp.access_token.clone();
*cache = Some(CachedToken {
token: resp.access_token,
obtained_at: Instant::now(),
expires_in: Duration::from_secs(resp.expires_in),
});
info!(
"DingTalk access token refreshed (expires in {}s)",
resp.expires_in
);
Ok(token)
}
// -----------------------------------------------------------------------
// Send message
// -----------------------------------------------------------------------
/// Send a text message to a user (1:1) via robot batch-send API.
async fn send_text_to_user(&self, user_id: &str, text: &str) -> Result<()> {
let token = self.get_access_token().await?;
let url = format!("{}/v1.0/robot/oToMessages/batchSend", self.api_base);
let body = json!({
"robotCode": self.robot_code,
"userIds": [user_id],
"msgKey": "sampleText",
"msgParam": serde_json::to_string(&json!({ "content": text }))?,
});
for attempt in 0..self.retry.attempts {
let resp = self
.client
.post(&url)
.header("x-acs-dingtalk-access-token", &token)
.json(&body)
.send()
.await
.context("DingTalk batchSend request")?;
let status = resp.status();
if status.as_u16() == 429 {
let delay = backoff_delay(attempt, &self.retry);
warn!(attempt, ?delay, "DingTalk rate limit, backing off");
sleep(delay).await;
continue;
}
if !status.is_success() {
let err = resp.text().await.unwrap_or_default();
return Err(anyhow::anyhow!("DingTalk batchSend failed {status}: {err}"));
}
return Ok(());
}
Err(anyhow::anyhow!(
"DingTalk batchSend failed after {} attempts",
self.retry.attempts
))
}
/// Send a text message to a group conversation.
async fn send_text_to_group(&self, open_conversation_id: &str, text: &str) -> Result<()> {
let token = self.get_access_token().await?;
let url = format!("{}/v1.0/robot/groupMessages/send", self.api_base);
let body = json!({
"robotCode": self.robot_code,
"openConversationId": open_conversation_id,
"msgKey": "sampleText",
"msgParam": serde_json::to_string(&json!({ "content": text }))?,
});
for attempt in 0..self.retry.attempts {
let resp = self
.client
.post(&url)
.header("x-acs-dingtalk-access-token", &token)
.json(&body)
.send()
.await
.context("DingTalk groupMessages/send request")?;
let status = resp.status();
if status.as_u16() == 429 {
let delay = backoff_delay(attempt, &self.retry);
warn!(
attempt,
?delay,
"DingTalk group send rate limit, backing off"
);
sleep(delay).await;
continue;
}
if !status.is_success() {
let err = resp.text().await.unwrap_or_default();
return Err(anyhow::anyhow!(
"DingTalk groupMessages/send failed {status}: {err}"
));
}
return Ok(());
}
Err(anyhow::anyhow!(
"DingTalk groupMessages/send failed after {} attempts",
self.retry.attempts
))
}
// -----------------------------------------------------------------------
// Voice / file download
// -----------------------------------------------------------------------
/// Download a voice file from DingTalk via the robot messageFiles API.
async fn download_voice(&self, download_code: &str) -> Result<Vec<u8>> {
let token = self.get_access_token().await?;
let url = format!("{}/v1.0/robot/messageFiles/download", self.api_base);
let body = json!({
"downloadCode": download_code,
"robotCode": self.robot_code,
});
let resp = self
.client
.post(&url)
.header("x-acs-dingtalk-access-token", &token)
.json(&body)
.send()
.await
.context("DingTalk messageFiles/download request")?;
if !resp.status().is_success() {
let status = resp.status();
let err = resp.text().await.unwrap_or_default();
bail!("DingTalk voice download failed {status}: {err}");
}
let download_info: FileDownloadResponse =
resp.json().await.context("DingTalk voice download parse")?;
let download_url = download_info
.download_url
.context("DingTalk voice download: no downloadUrl in response")?;
let audio_bytes = self.client.get(&download_url).send().await?.bytes().await?;
debug!(size = audio_bytes.len(), "DingTalk voice file downloaded");
Ok(audio_bytes.to_vec())
}
/// Download and transcribe a voice message.
async fn transcribe_voice(&self, download_code: &str) -> Result<String> {
let audio_bytes = self.download_voice(download_code).await?;
crate::channel::transcription::transcribe_audio(
&self.client,
&audio_bytes,
"voice.amr",
"audio/amr",
)
.await
}
/// Download a media file (picture/video/file) via DingTalk robot messageFiles API.
async fn download_media_file(&self, download_code: &str) -> Result<Vec<u8>> {
let token = self.get_access_token().await?;
let url = format!("{}/v1.0/robot/messageFiles/download", self.api_base);
let body = json!({
"downloadCode": download_code,
"robotCode": self.robot_code,
});
let resp = self
.client
.post(&url)
.header("x-acs-dingtalk-access-token", &token)
.json(&body)
.send()
.await
.context("DingTalk media download request")?;
if !resp.status().is_success() {
let status = resp.status();
let err = resp.text().await.unwrap_or_default();
bail!("DingTalk media download failed {status}: {err}");
}
let download_info: FileDownloadResponse =
resp.json().await.context("DingTalk media download parse")?;
let download_url = download_info
.download_url
.context("DingTalk media download: no downloadUrl in response")?;
let media_bytes = self.client.get(&download_url).send().await?.bytes().await?;
debug!(size = media_bytes.len(), "DingTalk media file downloaded");
Ok(media_bytes.to_vec())
}
// -----------------------------------------------------------------------
// Stream Mode — WebSocket connection
// -----------------------------------------------------------------------
/// Open a Stream Mode connection and return the WebSocket endpoint +
/// ticket.
async fn open_stream_connection(&self) -> Result<(String, String)> {
let token = self.get_access_token().await?;
let url = format!("{}/v1.0/gateway/connections/open", self.api_base);
let body = json!({
"clientId": self.app_key,
"clientSecret": self.app_secret,
"subscriptions": [
{
"type": "CALLBACK",
"topic": "/v1.0/im/bot/messages/get"
},
{
"type": "EVENT",
"topic": "*"
}
],
});
let resp = self
.client
.post(&url)
.header("x-acs-dingtalk-access-token", &token)
.json(&body)
.send()
.await
.context("DingTalk stream connection open")?;
if !resp.status().is_success() {
let status = resp.status();
let err = resp.text().await.unwrap_or_default();
bail!("DingTalk stream open failed {status}: {err}");
}
let info: StreamConnectResponse = resp
.json()
.await
.context("DingTalk stream connection parse")?;
let endpoint = info
.endpoint
.context("DingTalk stream: no endpoint in response")?;
let ticket = info
.ticket
.context("DingTalk stream: no ticket in response")?;
Ok((endpoint, ticket))
}
/// Process a single inbound event from the Stream Mode WebSocket.
async fn handle_stream_event(&self, data: &Value) {
// DingTalk stream events have a "headers" + "data" structure.
// The actual message payload is in "data".
let payload = if let Some(d) = data.get("data") {
// data field may be a JSON string that needs parsing.
if let Some(s) = d.as_str() {
match serde_json::from_str::<Value>(s) {
Ok(v) => v,
Err(e) => {
warn!("DingTalk: failed to parse event data string: {e}");
return;
}
}
} else {
d.clone()
}
} else {
data.clone()
};
// Extract message fields.
let sender_id = payload
.get("senderStaffId")
.or_else(|| payload.get("senderId"))
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let conversation_id = payload
.get("conversationId")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_owned();
let is_group = payload
.get("conversationType")
.and_then(|v| v.as_str())
.map(|t| t == "2")
.unwrap_or(false);
let msg_type = payload
.get("msgtype")
.or_else(|| payload.get("msgType"))
.and_then(|v| v.as_str())
.unwrap_or("text");
let mut images: Vec<crate::agent::registry::ImageAttachment> = Vec::new();
let text = match msg_type {
"text" => {
// Text content can be in text.content or msgContent.
let content = payload
.get("text")
.and_then(|t| t.get("content"))
.and_then(|v| v.as_str())
.or_else(|| payload.get("msgContent").and_then(|v| v.as_str()));
match content {
Some(t) if !t.trim().is_empty() => t.trim().to_owned(),
_ => return,
}
}
"audio" | "voice" => {
let download_code = payload
.get("content")
.and_then(|c| c.get("downloadCode"))
.and_then(|v| v.as_str());
match download_code {
Some(code) => match self.transcribe_voice(code).await {
Ok(t) => {
info!("DingTalk voice transcribed ({} chars)", t.len());
t
}
Err(e) => {
warn!("DingTalk voice transcription failed: {e:#}");
return;
}
},
None => {
warn!("DingTalk audio message missing downloadCode");
return;
}
}
}
"picture" | "richText" => {
let download_code = payload
.get("content")
.and_then(|c| c.get("downloadCode"))
.and_then(|v| v.as_str());
match download_code {
Some(code) => match self.download_media_file(code).await {
Ok(bytes) => {
use base64::Engine;
let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);
images.push(crate::agent::registry::ImageAttachment {
data: format!("data:image/png;base64,{b64}"),
mime_type: "image/png".to_owned(),
});
info!(size = bytes.len(), "DingTalk image downloaded");
String::new()
}
Err(e) => {
warn!("DingTalk image download failed: {e:#}");
return;
}
},
None => {
// Try direct picture URL from content
let pic_url = payload
.get("content")
.and_then(|c| {
c.get("pictureDownloadUrl").or_else(|| c.get("downloadUrl"))
})
.and_then(|v| v.as_str());
match pic_url {
Some(url) => match crate::channel::transcription::download_file(
&self.client,
url,
)
.await
{
Ok(bytes) => {
use base64::Engine;
let b64 =
base64::engine::general_purpose::STANDARD.encode(&bytes);
images.push(crate::agent::registry::ImageAttachment {
data: format!("data:image/png;base64,{b64}"),
mime_type: "image/png".to_owned(),
});
String::new()
}
Err(e) => {
warn!("DingTalk image URL download failed: {e:#}");
return;
}
},
None => {
warn!("DingTalk picture message missing downloadCode and URL");
return;
}
}
}
}
}
"video" => {
let download_code = payload
.get("content")
.and_then(|c| c.get("downloadCode"))
.and_then(|v| v.as_str());
match download_code {
Some(code) => match self.download_media_file(code).await {
Ok(bytes) => {
match dingtalk_extract_audio_and_transcribe(&self.client, &bytes).await
{
Ok(t) if !t.is_empty() => {
info!(chars = t.len(), "DingTalk video audio transcribed");
t
}
Ok(_) => {
warn!("DingTalk video transcription returned empty");
return;
}
Err(e) => {
warn!("DingTalk video transcription failed: {e:#}");
return;
}
}
}
Err(e) => {
warn!("DingTalk video download failed: {e:#}");
return;
}
},
None => {
warn!("DingTalk video message missing downloadCode");
return;
}
}
}
"file" => {
let download_code = payload
.get("content")
.and_then(|c| c.get("downloadCode"))
.and_then(|v| v.as_str());
let filename = payload
.get("content")
.and_then(|c| c.get("fileName"))
.and_then(|v| v.as_str())
.unwrap_or("file");
match download_code {
Some(code) => match self.download_media_file(code).await {
Ok(bytes) => {
if is_text_file(filename) {
match String::from_utf8(bytes) {
Ok(content) => {
info!(name = filename, "DingTalk text file received");
format!("[File: {filename}]\n{content}")
}
Err(_) => {
debug!("DingTalk file is not valid UTF-8: {filename}");
return;
}
}
} else {
debug!("DingTalk: non-text file ignored: {filename}");
return;
}
}
Err(e) => {
warn!("DingTalk file download failed: {e:#}");
return;
}
},
None => {
warn!("DingTalk file message missing downloadCode");
return;
}
}
}
other => {
debug!("DingTalk: ignoring message type '{other}'");
return;
}
};
if sender_id.is_empty() || (text.is_empty() && images.is_empty()) {
return;
}
debug!(
sender = %sender_id,
conversation = %conversation_id,
is_group,
"DingTalk message received"
);
(self.on_message)(sender_id, text, conversation_id, is_group, images);
}
/// Run the Stream Mode WebSocket loop (reconnects on failure).
async fn stream_loop(self: &Arc<Self>) -> Result<()> {
loop {
match self.run_single_stream().await {
Ok(()) => {
info!("DingTalk stream connection closed, reconnecting...");
}
Err(e) => {
error!("DingTalk stream error: {e:#}");
}
}
sleep(Duration::from_secs(5)).await;
}
}
/// Run a single Stream Mode WebSocket connection until it closes or errors.
async fn run_single_stream(self: &Arc<Self>) -> Result<()> {
let (endpoint, ticket) = self.open_stream_connection().await?;
// Append ticket as query parameter.
let ws_url = if endpoint.contains('?') {
format!("{}&ticket={}", endpoint, ticket)
} else {
format!("{}?ticket={}", endpoint, ticket)
};
info!(endpoint = %ws_url, "DingTalk Stream Mode connecting...");
let (ws_stream, _) = connect_async(&ws_url)
.await
.context("DingTalk WebSocket connect")?;
info!("DingTalk Stream Mode connected");
let (mut write, mut read) = ws_stream.split();
// Keep-alive ping interval.
let ping_interval = Duration::from_secs(30);
let mut ping_timer = tokio::time::interval(ping_interval);
ping_timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
// Skip the first immediate tick.
ping_timer.tick().await;
// Idle timeout: if no message received for 90s, reconnect.
let mut idle_deadline = tokio::time::Instant::now() + Duration::from_secs(90);
loop {
tokio::select! {
msg = read.next() => {
idle_deadline = tokio::time::Instant::now() + Duration::from_secs(90);
match msg {
Some(Ok(WsMessage::Text(text))) => {
debug!(text_len = text.len(), preview = &text[..text.len().min(200)], "DingTalk: WS text frame received");
match serde_json::from_str::<Value>(&text) {
Ok(event) => {
// Check if this is a system ping/pong.
let event_type = event
.get("headers")
.and_then(|h| h.get("topic"))
.and_then(|v| v.as_str())
.unwrap_or("");
if event_type == "ping" {
// Respond with a pong ack.
let msg_id = event
.get("headers")
.and_then(|h| h.get("messageId"))
.and_then(|v| v.as_str())
.unwrap_or("");
let ack = json!({
"code": 200,
"headers": {
"contentType": "application/json",
"messageId": msg_id,
},
"message": "OK",
"data": "",
});
let _ = write.send(WsMessage::Text(ack.to_string().into())).await;
debug!("DingTalk: pong sent for messageId={msg_id}");
continue;
}
// Send acknowledgment for the event.
let msg_id = event
.get("headers")
.and_then(|h| h.get("messageId"))
.and_then(|v| v.as_str())
.unwrap_or("");
if !msg_id.is_empty() {
let ack = json!({
"code": 200,
"headers": {
"contentType": "application/json",
"messageId": msg_id,
},
"message": "OK",
"data": "",
});
let _ = write.send(WsMessage::Text(ack.to_string().into())).await;
}
self.handle_stream_event(&event).await;
}
Err(e) => {
warn!("DingTalk: invalid JSON from stream: {e}");
}
}
}
Some(Ok(WsMessage::Ping(data))) => {
let _ = write.send(WsMessage::Pong(data)).await;
}
Some(Ok(WsMessage::Close(_))) => {
info!("DingTalk: WebSocket close frame received");
break;
}
Some(Err(e)) => {
warn!("DingTalk: WebSocket read error: {e}");
break;
}
None => {
info!("DingTalk: WebSocket stream ended");
break;
}
_ => {}
}
}
_ = ping_timer.tick() => {
// Send a keep-alive ping.
if write.send(WsMessage::Ping(vec![].into())).await.is_err() {
warn!("DingTalk: failed to send ping, reconnecting");
break;
}
}
_ = tokio::time::sleep_until(idle_deadline) => {
warn!("DingTalk: WS idle timeout (90s), reconnecting");
break;
}
}
}
Ok(())
}
}
// ---------------------------------------------------------------------------
// Channel trait implementation
// ---------------------------------------------------------------------------
impl Channel for DingTalkChannel {
fn name(&self) -> &str {
"dingtalk"
}
fn send(&self, msg: OutboundMessage) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
let chunk_cfg = ChunkConfig {
max_chars: DINGTALK_CHUNK_LIMIT,
min_chars: 1,
break_preference: BreakPreference::Paragraph,
};
let chunks = chunk_text(&msg.text, &chunk_cfg);
for chunk in chunks.iter().filter(|c| !c.trim().is_empty()) {
if msg.is_group {
self.send_text_to_group(&msg.target_id, chunk).await?;
} else {
self.send_text_to_user(&msg.target_id, chunk).await?;
}
}
for image_data in &msg.images {
use base64::Engine;
let (mime, b64) =
if let Some(rest) = image_data.strip_prefix("data:image/png;base64,") {
("image/png", rest)
} else if let Some(rest) = image_data.strip_prefix("data:image/jpeg;base64,") {
("image/jpeg", rest)
} else if let Some(rest) = image_data.strip_prefix("data:image/webp;base64,") {
("image/webp", rest)
} else {
warn!("DingTalk: unrecognised image data URI prefix, skipping");
continue;
};
let bytes = match base64::engine::general_purpose::STANDARD.decode(b64) {
Ok(b) if !b.is_empty() => b,
_ => {
warn!("DingTalk: failed to decode base64 image, skipping");
continue;
}
};
let filename = if mime == "image/jpeg" {
"image.jpg"
} else {
"image.png"
};
// Upload image to DingTalk via OAPI media/upload.
// The endpoint requires the access_token as a query parameter.
let token = self.get_access_token().await?;
let part = match reqwest::multipart::Part::bytes(bytes)
.file_name(filename)
.mime_str(mime)
{
Ok(p) => p,
Err(e) => {
warn!("DingTalk: failed to build multipart part: {e}");
continue;
}
};
let form = reqwest::multipart::Form::new()
.text("type", "image")
.part("media", part);
let upload_url = format!("{}/media/upload", self.oapi_base);
let upload_resp = self
.client
.post(&upload_url)
.query(&[("access_token", token.as_str())])
.multipart(form)
.send()
.await;
let media_id = match upload_resp {
Ok(r) => match r.json::<serde_json::Value>().await {
Ok(body) => {
if let Some(id) = body.get("media_id").and_then(|v| v.as_str()) {
id.to_owned()
} else {
warn!("DingTalk: media upload response missing media_id: {body}");
continue;
}
}
Err(e) => {
warn!("DingTalk: failed to parse media upload response: {e}");
continue;
}
},
Err(e) => {
warn!("DingTalk: media upload request failed: {e}");
continue;
}
};
// Send image message via robot.
// DingTalk `sampleImageMsg` uses `photoURL` which accepts a media_id
// returned by media/upload (valid for 3 days).
let token2 = self.get_access_token().await?;
let msg_param = json!({ "photoURL": media_id }).to_string();
let send_result = if msg.is_group {
self.client
.post(format!("{}/v1.0/robot/groupMessages/send", self.api_base))
.header("x-acs-dingtalk-access-token", &token2)
.json(&json!({
"robotCode": self.robot_code,
"openConversationId": msg.target_id,
"msgKey": "sampleImageMsg",
"msgParam": msg_param,
}))
.send()
.await
} else {
self.client
.post(format!(
"{}/v1.0/robot/oToMessages/batchSend",
self.api_base
))
.header("x-acs-dingtalk-access-token", &token2)
.json(&json!({
"robotCode": self.robot_code,
"userIds": [msg.target_id],
"msgKey": "sampleImageMsg",
"msgParam": msg_param,
}))
.send()
.await
};
match send_result {
Ok(r) if r.status().is_success() => {
debug!("DingTalk: image message sent");
}
Ok(r) => {
let status = r.status();
let err = r.text().await.unwrap_or_default();
warn!("DingTalk: image send failed {status}: {err}");
}
Err(e) => {
warn!("DingTalk: image send request failed: {e}");
}
}
}
// Send file attachments
for (filename, mime, path_or_url) in &msg.files {
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!("DingTalk: empty file download"); continue; }
}
}
_ => { warn!("DingTalk: file download failed: {path_or_url}"); continue; }
}
} else {
match std::fs::read(path_or_url) {
Ok(b) => b,
Err(e) => { warn!("DingTalk: failed to read file {path_or_url}: {e}"); continue; }
}
};
let token = self.get_access_token().await?;
let part = match reqwest::multipart::Part::bytes(bytes)
.file_name(filename.clone())
.mime_str(mime)
{
Ok(p) => p,
Err(e) => { warn!("DingTalk: multipart error: {e}"); continue; }
};
// Detect media type for upload
let upload_type = if mime.starts_with("video/") { "video" }
else if mime.starts_with("audio/") { "voice" }
else if mime.starts_with("image/") { "image" }
else { "file" };
let form = reqwest::multipart::Form::new()
.text("type", upload_type.to_owned())
.part("media", part);
let upload_url = format!("{}/media/upload", self.oapi_base);
let upload_resp = self.client
.post(&upload_url)
.query(&[("access_token", token.as_str())])
.multipart(form)
.send()
.await;
let media_id = match upload_resp {
Ok(r) => match r.json::<serde_json::Value>().await {
Ok(body) => {
if let Some(id) = body.get("media_id").and_then(|v| v.as_str()) {
id.to_owned()
} else {
warn!("DingTalk: file upload missing media_id: {body}");
continue;
}
}
Err(e) => { warn!("DingTalk: file upload parse error: {e}"); continue; }
},
Err(e) => { warn!("DingTalk: file upload failed: {e}"); continue; }
};
let token2 = self.get_access_token().await?;
// Build msgKey and msgParam based on media type
let (msg_key, msg_param) = if mime.starts_with("video/") {
("sampleVideo", json!({
"videoMediaId": media_id,
"videoType": filename.rsplit('.').next().unwrap_or("mp4"),
}).to_string())
} else if mime.starts_with("audio/") {
("sampleAudio", json!({
"mediaId": media_id,
}).to_string())
} else {
let file_ext = filename.rsplit('.').next().unwrap_or("").to_owned();
("sampleFile", json!({
"mediaId": media_id,
"fileName": filename,
"fileType": file_ext,
}).to_string())
};
let send_result = if msg.is_group {
self.client
.post(format!("{}/v1.0/robot/groupMessages/send", self.api_base))
.header("x-acs-dingtalk-access-token", &token2)
.json(&json!({
"robotCode": self.robot_code,
"openConversationId": msg.target_id,
"msgKey": msg_key,
"msgParam": msg_param,
}))
.send()
.await
} else {
self.client
.post(format!("{}/v1.0/robot/oToMessages/batchSend", self.api_base))
.header("x-acs-dingtalk-access-token", &token2)
.json(&json!({
"robotCode": self.robot_code,
"userIds": [msg.target_id],
"msgKey": msg_key,
"msgParam": msg_param,
}))
.send()
.await
};
match send_result {
Ok(r) if r.status().is_success() => {
debug!("DingTalk: file sent: {filename}");
}
Ok(r) => {
let status = r.status();
let err = r.text().await.unwrap_or_default();
warn!("DingTalk: file send failed {status}: {err}");
}
Err(e) => {
warn!("DingTalk: file send request failed: {e}");
}
}
}
Ok(())
})
}
fn run(self: Arc<Self>) -> BoxFuture<'static, Result<()>> {
Box::pin(async move {
info!("DingTalk Stream Mode loop started");
self.stream_loop().await
})
}
}
// ---------------------------------------------------------------------------
// Retry helper (re-use from telegram module)
// ---------------------------------------------------------------------------
fn backoff_delay(attempt: u32, config: &RetryConfig) -> Duration {
let base = config.min_delay_ms as f64 * 2f64.powi(attempt as i32);
let clamped = base.min(config.max_delay_ms as f64);
let jitter = clamped * config.jitter * rand::random::<f64>();
Duration::from_millis((clamped + jitter) as u64)
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn is_text_file(name: &str) -> bool {
let exts = [
".txt", ".md", ".csv", ".json", ".toml", ".yaml", ".yml", ".xml", ".html", ".rs", ".py",
".js", ".ts", ".go", ".sh", ".log", ".conf", ".cfg",
];
exts.iter().any(|e| name.ends_with(e))
}
/// Extract audio track from video bytes via ffmpeg, then transcribe.
async fn dingtalk_extract_audio_and_transcribe(
client: &Client,
video_bytes: &[u8],
) -> Result<String> {
let tmp_dir = std::env::temp_dir();
let video_path = tmp_dir.join(format!("rsclaw_dt_video_{}.mp4", uuid::Uuid::new_v4()));
let audio_path = tmp_dir.join(format!("rsclaw_dt_video_{}.ogg", uuid::Uuid::new_v4()));
std::fs::write(&video_path, video_bytes)?;
let ffmpeg_bin = crate::agent::platform::detect_ffmpeg().unwrap_or_else(|| "ffmpeg".to_owned());
let status = tokio::process::Command::new(&ffmpeg_bin)
.args([
"-y",
"-i",
video_path.to_str().unwrap_or(""),
"-vn",
"-acodec",
"libopus",
audio_path.to_str().unwrap_or(""),
])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.await;
let _ = std::fs::remove_file(&video_path);
if !status.map(|s| s.success()).unwrap_or(false) {
let _ = std::fs::remove_file(&audio_path);
bail!("ffmpeg failed to extract audio from video");
}
let audio_bytes = std::fs::read(&audio_path)?;
let _ = std::fs::remove_file(&audio_path);
crate::channel::transcription::transcribe_audio(
client,
&audio_bytes,
"video_audio.ogg",
"audio/ogg",
)
.await
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
fn init_crypto() {
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
}
#[test]
fn channel_name() {
init_crypto();
let ch = DingTalkChannel::new(
"key",
"secret",
"robot_code",
None,
None,
Arc::new(|_, _, _, _, _| {}),
);
assert_eq!(ch.name(), "dingtalk");
}
#[test]
fn chunk_limit() {
assert_eq!(DINGTALK_CHUNK_LIMIT, 20_000);
}
#[test]
fn token_expiry_check() {
let cached = CachedToken {
token: "test".to_owned(),
obtained_at: Instant::now() - Duration::from_secs(7200),
expires_in: Duration::from_secs(7200),
};
assert!(
cached.is_expired(),
"token obtained 2h ago should be expired"
);
let fresh = CachedToken {
token: "test".to_owned(),
obtained_at: Instant::now(),
expires_in: Duration::from_secs(7200),
};
assert!(
!fresh.is_expired(),
"freshly obtained token should not be expired"
);
}
#[test]
fn backoff_increases() {
let cfg = RetryConfig::default();
let d0 = backoff_delay(0, &cfg).as_millis();
let d1 = backoff_delay(1, &cfg).as_millis();
assert!(d1 >= d0, "backoff should increase");
}
}