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
|
use futures::stream::StreamExt;
use xtra::{Actor, Handler, WeakAddress};
use tsclientlib::data::exts::{M2BClientEditExt, M2BClientUpdateExt};
use tsclientlib::{
events::Event,
sync::{SyncConnection, SyncConnectionHandle, SyncStreamItem},
ChannelId, ClientId, ConnectOptions, DisconnectOptions, MessageTarget, OutCommandExt, Reason,
};
use slog::{debug, error, info, trace, Logger};
use crate::bot::{ChatMessage, MusicBotMessage};
mod bbcode;
pub use bbcode::*;
#[derive(Clone)]
pub struct TeamSpeakConnection {
handle: Option<SyncConnectionHandle>,
logger: Logger,
}
fn get_message(event: &Event) -> Option<MusicBotMessage> {
use tsclientlib::events::{PropertyId, PropertyValue};
match event {
Event::Message {
target,
invoker: sender,
message: msg,
} => Some(MusicBotMessage::TextMessage(ChatMessage {
target: *target,
invoker: sender.clone(),
text: msg.clone(),
})),
Event::PropertyAdded {
id: property,
invoker: _,
extra: _,
} => match property {
PropertyId::Channel(id) => Some(MusicBotMessage::ChannelAdded(*id)),
PropertyId::Client(id) => Some(MusicBotMessage::ClientAdded(*id)),
_ => None,
},
Event::PropertyChanged {
id: property,
old: from,
invoker: _,
extra: _,
} => match property {
PropertyId::ClientChannel(client) => {
if let PropertyValue::ChannelId(from) = from {
Some(MusicBotMessage::ClientChannel {
client: *client,
old_channel: *from,
})
} else {
None
}
}
_ => None,
},
Event::PropertyRemoved {
id: property,
old: client,
invoker: _,
extra: _,
} => match property {
PropertyId::Client(id) => {
if let PropertyValue::Client(client) = client {
Some(MusicBotMessage::ClientDisconnected {
id: *id,
client: Box::new(client.clone()),
})
} else {
None
}
}
_ => None,
},
_ => None,
}
}
impl TeamSpeakConnection {
pub async fn new(logger: Logger) -> Result<TeamSpeakConnection, tsclientlib::Error> {
Ok(TeamSpeakConnection {
handle: None,
logger,
})
}
pub fn connect_for_bot<T: Actor + Handler<MusicBotMessage>>(
&mut self,
options: ConnectOptions,
bot: WeakAddress<T>,
) -> Result<(), tsclientlib::Error> {
info!(self.logger, "Starting TeamSpeak connection");
let conn = options.connect()?;
let mut conn = SyncConnection::from(conn);
let handle = conn.get_handle();
self.handle = Some(handle);
let ev_logger = self.logger.clone();
tokio::spawn(async move {
while let Some(item) = conn.next().await {
use SyncStreamItem::*;
match item {
Ok(ConEvents(events)) => {
for event in &events {
if let Some(msg) = get_message(event) {
tokio::spawn(bot.send(msg));
}
}
}
Err(e) => error!(ev_logger, "Error occured during event reading: {}", e),
Ok(DisconnectedTemporarily(r)) => {
debug!(ev_logger, "Temporary disconnect"; "reason" => ?r)
}
Ok(Audio(_)) => {
trace!(ev_logger, "Audio received");
}
Ok(IdentityLevelIncreasing(_)) => {
trace!(ev_logger, "Identity level increasing");
}
Ok(IdentityLevelIncreased) => {
trace!(ev_logger, "Identity level increased");
}
Ok(NetworkStatsUpdated) => {
trace!(ev_logger, "Network stats updated");
}
}
}
});
let mut handle = self.handle.clone();
tokio::spawn(async move {
handle
.as_mut()
.expect("connect_for_bot was called")
.wait_until_connected()
.await
.unwrap();
handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(|mut conn| {
conn.get_state()
.expect("can get state")
.server
.set_subscribed(true)
.send(&mut conn)
})
.await
.and_then(|v| v)
.unwrap();
});
Ok(())
}
pub async fn send_audio_packet(&mut self, samples: &[u8]) {
let packet =
tsproto_packets::packets::OutAudio::new(&tsproto_packets::packets::AudioData::C2S {
id: 0,
codec: tsproto_packets::packets::CodecType::OpusMusic,
data: samples,
});
if let Err(e) = self
.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |conn| {
conn.get_tsproto_client_mut()
.expect("can get tsproto client")
.send_packet(packet)
})
.await
{
error!(self.logger, "Failed to send voice packet: {}", e);
}
}
pub async fn channel_of_user(&mut self, id: ClientId) -> Option<ChannelId> {
self.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |conn| {
conn.get_state()
.expect("can get state")
.clients
.get(&id)
.map(|c| c.channel)
})
.await
.map_err(|e| error!(self.logger, "Failed to get channel of user"; "error" => %e))
.ok()
.and_then(|v| v)
}
pub async fn channel_path_of_user(&mut self, id: ClientId) -> Option<String> {
self.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |conn| {
let state = conn.get_state().expect("can get state");
let channel_id = state.clients.get(&id)?.channel;
let mut channel = state.channels.get(&channel_id)?;
let mut names = vec![&channel.name[..]];
// Channel 0 is the root channel
while channel.parent != ChannelId(0) {
names.push("/");
channel = state.channels.get(&channel.parent)?;
names.push(&channel.name);
}
let mut path = String::new();
while let Some(name) = names.pop() {
path.push_str(name);
}
Some(path)
})
.await
.map_err(|e| error!(self.logger, "Failed to get channel path of user"; "error" => %e))
.ok()
.and_then(|v| v)
}
pub async fn current_channel(&mut self) -> Option<ChannelId> {
self.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |conn| {
let state = conn.get_state().expect("can get state");
state
.clients
.get(&state.own_client)
.expect("can find myself")
.channel
})
.await
.map_err(|e| error!(self.logger, "Failed to get channel"; "error" => %e))
.ok()
}
pub async fn my_id(&mut self) -> ClientId {
self.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |conn| conn.get_state().expect("can get state").own_client)
.await
.unwrap()
}
pub async fn user_count(&mut self, channel: ChannelId) -> u32 {
self.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |conn| {
let state = conn.get_state().expect("can get state");
let mut count = 0;
for client in state.clients.values() {
if client.channel == channel {
count += 1;
}
}
count
})
.await
.unwrap()
}
pub async fn set_nickname(&mut self, name: String) {
if let Err(e) = self
.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |mut conn| {
conn.get_state()
.expect("can get state")
.client_update()
.set_name(&name)
.send(&mut conn)
})
.await
.and_then(|v| v)
{
error!(self.logger, "Failed to set nickname: {}", e);
}
}
pub async fn set_description(&mut self, desc: String) {
if let Err(e) = self
.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |mut conn| {
let state = conn.get_state().expect("can get state");
state
.clients
.get(&state.own_client)
.expect("can get myself")
.edit()
.set_description(&desc)
.send(&mut conn)
})
.await
.and_then(|v| v)
{
error!(self.logger, "Failed to change description: {}", e);
}
}
pub async fn send_message_to_channel(&mut self, text: String) {
if let Err(e) = self
.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |mut conn| {
conn.get_state()
.expect("can get state")
.send_message(MessageTarget::Channel, &text)
.send(&mut conn)
})
.await
.and_then(|v| v)
{
error!(self.logger, "Failed to send message: {}", e);
}
}
pub async fn send_message_to_user(&mut self, client: ClientId, text: String) {
if let Err(e) = self
.handle
.as_mut()
.expect("connect_for_bot was called")
.with_connection(move |mut conn| {
conn.get_state()
.expect("can get state")
.send_message(MessageTarget::Client(client), &text)
.send(&mut conn)
})
.await
.and_then(|v| v)
{
error!(self.logger, "Failed to send message: {}", e);
}
}
pub async fn disconnect(&mut self, reason: &str) -> Result<(), tsclientlib::Error> {
let opt = DisconnectOptions::new()
.reason(Reason::Clientdisconnect)
.message(reason);
self.handle
.as_mut()
.expect("connect_for_bot was called")
.disconnect(opt)
.await
}
}
|