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
use flate2::write::ZlibDecoder;
use futures::{lock::Mutex, stream::SplitSink, SinkExt, StreamExt};
use handle::{LiveCmdHandle, LiveCmdHandleOP, LiveCmdHandleRAW};
use proto::{
CGuard, CLike, CSendGift, CSuperChat, CSuperChatDel, LiveOpenPlatformCmd, RawProto, CDM,
LIVE_OPEN_PLATFORM_GUARD, LIVE_OPEN_PLATFORM_LIKE, LIVE_OPEN_PLATFORM_SEND_GIFT,
LIVE_OPEN_PLATFORM_SUPER_CHAT, LIVE_OPEN_PLATFORM_SUPER_CHAT_DEL,
};
use serde_json::Value;
use std::io::prelude::*;
use std::sync::Arc;
use tokio::{net::TcpStream, time::Duration};
use tokio_tungstenite::{
connect_async,
tungstenite::{http::Uri, Message},
MaybeTlsStream, WebSocketStream,
};
use crate::proto::LIVE_OPEN_PLATFORM_DM;
pub mod handle;
pub mod proto;
pub mod test_handle;
pub struct CmdAgent {
is_working: bool,
pub params: CmdAgentParams,
pub raw_handles: Arc<Mutex<Vec<Arc<dyn LiveCmdHandleRAW>>>>,
pub op_handles: Arc<Mutex<Vec<Arc<dyn LiveCmdHandleOP>>>>,
pub cmd_handles: Arc<Mutex<Vec<Arc<dyn LiveCmdHandle>>>>,
}
#[derive(Debug, Clone, Default)]
pub struct CmdAgentParams {
pub auth_body: String,
pub server_url: String,
pub app_id: i64,
pub user_code: String,
}
type Writer = SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>;
impl CmdAgent {
pub fn new(params: CmdAgentParams) -> Self {
CmdAgent {
params,
is_working: false,
raw_handles: Arc::new(Mutex::new(Vec::new())),
op_handles: Arc::new(Mutex::new(Vec::new())),
cmd_handles: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn is_working(&self) -> bool {
self.is_working
}
pub async fn start(&mut self) {
//构建websocket客户端
let server_uri = match Uri::try_from(self.params.server_url.clone()) {
Ok(uri) => uri,
Err(e) => {
eprintln!("Invalid URI {} {:?}", e, self.params);
return;
}
};
let (ws_stream, _) = match connect_async(server_uri).await {
Ok(result) => result,
Err(e) => {
eprintln!("WebSocket connection failed {} {:?}", e, self.params);
return;
}
};
let (writer, read) = ws_stream.split();
// 接收消息
let raw_handles = Arc::clone(&self.raw_handles);
let op_handles = Arc::clone(&self.op_handles);
let cmd_handles = Arc::clone(&self.cmd_handles);
let agent_params = self.params.clone();
tokio::spawn(async move {
let mut reader = read;
while let Some(message) = reader.next().await {
match message {
Ok(msg) => {
if let Message::Binary(bytes) = msg {
let raw_handles = Arc::clone(&raw_handles);
let op_handles = Arc::clone(&op_handles);
let cmd_handles = Arc::clone(&cmd_handles);
handle(
bytes,
&raw_handles,
&op_handles,
&cmd_handles,
agent_params.clone(),
)
.await;
} else if let Message::Ping(_p) = msg {
} else {
eprintln!("No Binary Data {:?}", msg);
}
}
Err(e) => eprintln!("Failed to receive {e}"),
}
}
});
// 发送AUTH包
let writer = self.send_auth(writer).await;
if writer.is_err() {
eprintln!("Failed auth {:?}", self.params);
return;
}
// 发送心跳
let mut writer = writer.unwrap();
let agent_params = self.params.clone();
tokio::spawn(async move {
loop {
println!("cmd heartbeat");
let proto = RawProto::new(2, Vec::new());
let result = writer.send(Message::Binary(proto.clone().into())).await;
if result.is_err() {
eprintln!("Failed to send message {:?} {:?}", proto, agent_params);
}
tokio::time::sleep(Duration::from_secs(30)).await;
}
});
//正常运行标识
self.is_working = true;
}
async fn send_auth(
&self,
mut write: Writer,
) -> Result<Writer, tokio_tungstenite::tungstenite::Error> {
write
.send(Message::Binary(
RawProto::new(7, self.params.auth_body.clone().as_bytes().to_vec()).into(),
))
.await?;
Ok(write)
}
}
///消息处理
#[allow(unused_must_use, clippy::let_underscore_future)]
async fn handle(
bytes: Vec<u8>,
raw_handles: &Arc<Mutex<Vec<Arc<dyn LiveCmdHandleRAW>>>>,
op_handles: &Arc<Mutex<Vec<Arc<dyn LiveCmdHandleOP>>>>,
cmd_handles: &Arc<Mutex<Vec<Arc<dyn LiveCmdHandle>>>>,
params: CmdAgentParams,
) {
//处理原始数据
for raw in raw_handles.lock().await.iter() {
let bytes = bytes.clone();
let params = params.clone();
raw.handle(bytes, params).await;
}
//处理Proto数据
if let Ok(proto) = RawProto::try_from(bytes) {
if proto.version == 2 {
//处理压缩
let mut writer = Vec::new();
let mut z = ZlibDecoder::new(writer);
let r = z.write_all(&proto.body);
if r.is_err() {
return;
}
let r = z.finish();
if r.is_err() {
return;
}
writer = r.unwrap();
//递归消息处理
handle(writer, raw_handles, op_handles, cmd_handles, params.clone());
return;
}
for op in op_handles.lock().await.iter() {
let proto: RawProto = proto.clone();
let params = params.clone();
op.handle(proto, params).await;
}
//弹幕消息包
if proto.operation == 5 {
//处理解析后的Cmd
match String::from_utf8(proto.body) {
Ok(json) => match serde_json::from_str::<Value>(&json) {
Ok(v) => {
if let Some((_, v)) = v.as_object().and_then(|m| m.iter().next()) {
if let Some(cmd) = v.as_str() {
match cmd {
LIVE_OPEN_PLATFORM_DM => {
if let Ok(pcmd) =
serde_json::from_str::<LiveOpenPlatformCmd<CDM>>(&json)
{
for handle in cmd_handles.lock().await.iter() {
let params = params.clone();
handle.handle_dm(pcmd.data.clone(), params).await;
}
}
}
LIVE_OPEN_PLATFORM_SEND_GIFT => {
if let Ok(pcmd) =
serde_json::from_str::<LiveOpenPlatformCmd<CSendGift>>(
&json,
)
{
for handle in cmd_handles.lock().await.iter() {
let params = params.clone();
handle
.handle_send_gift(pcmd.data.clone(), params)
.await;
}
}
}
LIVE_OPEN_PLATFORM_SUPER_CHAT => {
if let Ok(pcmd) =
serde_json::from_str::<LiveOpenPlatformCmd<CSuperChat>>(
&json,
)
{
for handle in cmd_handles.lock().await.iter() {
let params = params.clone();
handle
.handle_super_chat(pcmd.data.clone(), params)
.await;
}
}
}
LIVE_OPEN_PLATFORM_SUPER_CHAT_DEL => {
if let Ok(pcmd) = serde_json::from_str::<
LiveOpenPlatformCmd<CSuperChatDel>,
>(
&json
) {
for handle in cmd_handles.lock().await.iter() {
let params = params.clone();
handle
.handle_super_chat_del(
pcmd.data.clone(),
params,
)
.await;
}
}
}
LIVE_OPEN_PLATFORM_GUARD => {
if let Ok(pcmd) =
serde_json::from_str::<LiveOpenPlatformCmd<CGuard>>(
&json,
)
{
for handle in cmd_handles.lock().await.iter() {
let params = params.clone();
handle
.handle_guard(pcmd.data.clone(), params)
.await;
}
}
}
LIVE_OPEN_PLATFORM_LIKE => {
if let Ok(pcmd) =
serde_json::from_str::<LiveOpenPlatformCmd<CLike>>(
&json,
)
{
for handle in cmd_handles.lock().await.iter() {
let params = params.clone();
handle.handle_like(pcmd.data.clone(), params).await;
}
}
}
_ => eprintln!("Unkonw Cmd {cmd}"),
}
}
}
}
Err(e) => eprintln!("Json Decode Error {e} {json}"),
},
Err(e) => eprintln!("Body From utf8 Error {e}"),
}
}
}
}
#[cfg(test)]
mod tests {
use crate::{test_handle::TestHandler, CmdAgent, CmdAgentParams};
use std::sync::Arc;
use tokio::time::Duration;
#[tokio::test]
async fn test_agent() {
let mut agent = CmdAgent::new(CmdAgentParams {
auth_body: "".to_string(),
server_url: "".to_string(),
..Default::default()
});
let handle = Arc::new(TestHandler {});
let raw = Arc::clone(&handle);
agent.raw_handles.lock().await.push(raw);
let op = Arc::clone(&handle);
agent.op_handles.lock().await.push(op);
let cmd = Arc::clone(&handle);
agent.cmd_handles.lock().await.push(cmd);
agent.start().await;
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
}
}
#[tokio::test]
async fn mult_test() {
tokio::spawn(async {
loop {
tokio::time::sleep(Duration::from_secs(3)).await;
println!("loop1 turn");
for i in 0..2 {
tokio::spawn(async move {
println!("inner:{}", i);
});
}
eprintln!("loop failed something!");
println!("loop1 turn end");
}
});
tokio::spawn(async {
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
println!("loop2 turn");
println!("loop2 end");
}
});
for _ in 0..2 {
println!("main loop");
tokio::time::sleep(Duration::from_secs(60)).await;
}
}
}