aboutsummaryrefslogtreecommitdiffstats
path: root/src/teamspeak/mod.rs
blob: beb3f4480f078a5acbaa2721735dde02ad8e97db (plain) (blame)
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
use std::sync::{Arc, RwLock};

use futures::stream::StreamExt;
use tokio::sync::mpsc::UnboundedSender;

use tsclientlib::data::exts::{M2BClientEditExt, M2BClientUpdateExt};
use tsclientlib::{
    events::Event,
    sync::{SyncConnection, SyncConnectionHandle, SyncStreamItem},
    ChannelId, ClientId, ConnectOptions, DisconnectOptions, MessageTarget, OutCommandExt, Reason,
};

use log::{debug, error};

use crate::bot::{Message, MusicBotMessage};

mod bbcode;

pub use bbcode::*;

#[derive(Clone)]
pub struct TeamSpeakConnection {
    handle: SyncConnectionHandle,
}

fn get_message(event: &Event) -> Option<MusicBotMessage> {
    use tsclientlib::events::{PropertyId, PropertyValue};

    match event {
        Event::Message {
            target,
            invoker: sender,
            message: msg,
        } => Some(MusicBotMessage::TextMessage(Message {
            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(
        tx: Arc<RwLock<UnboundedSender<MusicBotMessage>>>,
        options: ConnectOptions,
    ) -> Result<TeamSpeakConnection, tsclientlib::Error> {
        let conn = options.connect()?;
        let conn = SyncConnection::from(conn);
        let mut handle = conn.get_handle();

        tokio::spawn(conn.for_each(move |i| {
            let tx = tx.clone();
            async move {
                match i {
                    Ok(SyncStreamItem::ConEvents(events)) => {
                        for event in &events {
                            if let Some(msg) = get_message(event) {
                                let tx = tx.read().expect("RwLock was not poisoned");
                                // Ignore the result because the receiver might get dropped first.
                                let _ = tx.send(msg);
                            }
                        }
                    }
                    Err(e) => error!("Error occured during event reading: {}", e),
                    Ok(SyncStreamItem::DisconnectedTemporarily) => debug!("Temporary disconnect!"),
                    _ => (),
                }
            }
        }));

        handle.wait_until_connected().await?;

        let mut chandle = handle.clone();
        chandle
            .with_connection(|mut conn| {
                conn.get_state()
                    .expect("is connected")
                    .server
                    .set_subscribed(true)
                    .send(&mut conn)
                    .unwrap()
            })
            .await
            .unwrap();

        Ok(TeamSpeakConnection { handle })
    }

    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,
            });

        self.handle
            .with_connection(|conn| {
                if let Err(e) = conn
                    .get_tsproto_client_mut()
                    .expect("can get tsproto client")
                    .send_packet(packet)
                {
                    error!("Failed to send voice packet: {}", e);
                }
            })
            .await
            .unwrap();
    }

    pub async fn channel_of_user(&mut self, id: ClientId) -> Option<ChannelId> {
        self.handle
            .with_connection(move |conn| {
                conn.get_state()
                    .expect("can get state")
                    .clients
                    .get(&id)
                    .map(|c| c.channel)
            })
            .await
            .unwrap()
    }

    pub async fn channel_path_of_user(&mut self, id: ClientId) -> Option<String> {
        self.handle
            .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)
                    .expect("can find user channel");

                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)
                        .expect("can find user channel");
                    names.push(&channel.name);
                }

                let mut path = String::new();
                while let Some(name) = names.pop() {
                    path.push_str(name);
                }

                Some(path)
            })
            .await
            .unwrap()
    }

    pub async fn my_channel(&mut self) -> ChannelId {
        self.handle
            .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
            .unwrap()
    }

    pub async fn my_id(&mut self) -> ClientId {
        self.handle
            .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
            .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) {
        self.handle
            .with_connection(move |mut conn| {
                conn.get_state()
                    .expect("can get state")
                    .client_update()
                    .set_name(&name)
                    .send(&mut conn)
                    .map_err(|e| error!("Failed to set nickname: {}", e))
            })
            .await
            .unwrap()
            .unwrap();
    }

    pub async fn set_description(&mut self, desc: String) {
        self.handle
            .with_connection(move |mut conn| {
                let state = conn.get_state().expect("can get state");
                let _ = state
                    .clients
                    .get(&state.own_client)
                    .expect("can get myself")
                    .edit()
                    .set_description(&desc)
                    .send(&mut conn)
                    .map_err(|e| error!("Failed to change description: {}", e));
            })
            .await
            .unwrap()
    }

    pub async fn send_message_to_channel(&mut self, text: String) {
        self.handle
            .with_connection(move |mut conn| {
                let _ = conn
                    .get_state()
                    .expect("can get state")
                    .send_message(MessageTarget::Channel, &text)
                    .send(&mut conn)
                    .map_err(|e| error!("Failed to send message: {}", e));
            })
            .await
            .unwrap()
    }

    pub async fn send_message_to_user(&mut self, client: ClientId, text: String) {
        self.handle
            .with_connection(move |mut conn| {
                let _ = conn
                    .get_state()
                    .expect("can get state")
                    .send_message(MessageTarget::Client(client), &text)
                    .send(&mut conn)
                    .map_err(|e| error!("Failed to send message: {}", e));
            })
            .await
            .unwrap()
    }

    pub async fn subscribe(&mut self, id: ChannelId) {
        self.handle
            .with_connection(move |mut conn| {
                let channel = match conn.get_state().expect("can get state").channels.get(&id) {
                    Some(c) => c,
                    None => {
                        error!("Failed to find channel to subscribe to");
                        return;
                    }
                };

                if let Err(e) = channel.set_subscribed(true).send(&mut conn) {
                    error!("Failed to send subscribe packet: {}", e);
                }
            })
            .await
            .unwrap()
    }

    pub async fn disconnect(&mut self, reason: &str) {
        let opt = DisconnectOptions::new()
            .reason(Reason::Clientdisconnect)
            .message(reason);
        self.handle.disconnect(opt).await.unwrap();
    }
}