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
//! Ts3 query library  
//! Small, bare-metal ts query lib without any callback support currently.
//!
//! A connectivity checking wrapper is available under [managed](managed) when enabling its feature.
//!
//! # Examples
//! Simple auth + clients of a server group
//! ```rust,no_run
//! use ts3_query::*;
//!
//! # fn main() -> Result<(),Ts3Error> {
//! let mut client = QueryClient::new("localhost:10011")?;
//!
//! client.login("serveradmin", "password")?;
//! client.select_server_by_port(9987)?;
//!
//! let group_clients = client.servergroup_client_cldbids(7)?;
//! println!("Got clients in group 7: {:?}",group_clients);
//!
//! client.logout()?;
//! # Ok(())
//! # }
//!
//! ```
//!
//! Cloning a channel
//! ```rust, no_run
//! use ts3_query::*;
//!
//! # fn main() -> Result<(),Ts3Error> {
//! let mut client = QueryClient::new("localhost:10011")?;
//! client.login("serveradmin", "password")?;
//! client.select_server_by_port(9987)?;
//!
//! let channels = client.channels_full()?;
//! if let Some(channel) = channels.first() {
//!     client.create_channel(&ChannelEdit {
//!         channel_name: Some("Cloned channel".to_owned()),
//!         ..ChannelEdit::from(channel)
//!     })?;
//! }
//! # Ok(())
//! # }
//! ```
//!
//! Using the raw interface for setting client descriptions.
//! ```rust,no_run
//! use ts3_query::*;
//!
//! # fn main() -> Result<(),Ts3Error> {
//! let mut client = QueryClient::new("localhost:10011")?;
//!
//! client.login("serveradmin", "password")?;
//! client.select_server_by_port(9987)?;
//!
//! // escape things like string args, not required for clid
//! // as it's not user input/special chars in this case
//! let cmd = format!("clientedit clid={} client_description={}",
//!  7, raw::escape_arg("Some Description!")
//! );
//! // we don't expect any value returned
//! let _ = client.raw_command(&cmd)?;
//!
//! client.logout()?;
//! # Ok(())
//! # }
//! ```
//!
//! Raw interface example retrieving online client names
//! ```rust,no_run
//! use ts3_query::*;
//! use std::collections::HashSet;
//!
//! # fn main() -> Result<(),Ts3Error> {
//! let mut client = QueryClient::new("localhost:10011")?;
//!
//! client.login("serveradmin", "password")?;
//! client.select_server_by_port(9987)?;
//!
//! let mut res = raw::parse_multi_hashmap(client.raw_command("clientlist")?, false);
//! let names = res
//!     .into_iter()
//!     .map(|mut e| e.remove("client_nickname")
//!     // ignore empty value & unescape
//!     .unwrap().map(raw::unescape_val)
//!      // may want to catch this in a real application
//!         .unwrap())
//!     .collect::<HashSet<String>>();
//! println!("{:?}",names);
//! client.logout()?;
//! # Ok(())
//! # }
//! ```
#![cfg_attr(docsrs, feature(doc_cfg))]

use snafu::{Backtrace, OptionExt, ResultExt, Snafu};
use std::collections::HashMap;
use std::fmt::{Debug, Write as FmtWrite};
use std::io::{self, BufRead, BufReader, Write};
use std::net::{Shutdown, TcpStream, ToSocketAddrs};
use std::string::FromUtf8Error;
use std::time::Duration;

mod data;
#[cfg_attr(docsrs, doc(cfg(feature = "managed")))]
#[cfg(feature = "managed")]
pub mod managed;
pub mod raw;

pub use data::*;
use io::Read;
use raw::*;
use std::fmt;

/// Target for message sending
pub enum MessageTarget {
    /// Send to client
    Client(ClientId),
    /// Send to current channel of this client. You have to join the channel you want to send a message to.
    Channel,
    /// Send to whole server
    Server,
}

impl fmt::Display for MessageTarget {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Self::Client(id) => write!(f, "targetmode=1 target={}", id),
            Self::Channel => write!(f, "targetmode=2"),
            Self::Server => write!(f, "targetmode=3"),
        }
    }
}

#[derive(Snafu, Debug)]
pub enum Ts3Error {
    /// Error on response conversion with invalid utf8 data
    #[snafu(display("Input was invalid UTF-8: {}", source))]
    Utf8Error { source: FromUtf8Error },
    /// Catch-all IO error, contains optional context
    #[snafu(display("IO Error: {}{}, kind: {:?}", context, source, source.kind()))]
    Io {
        /// Context of action, empty per default.
        ///
        /// Please use a format like `"reading connection: "`
        context: &'static str,
        source: io::Error,
    },
    /// Reached EOF reading response, server closed connection / timeout.
    #[snafu(display("IO Error: Connection closed"))]
    ConnectionClosed { backtrace: Backtrace },
    #[snafu(display("No valid socket address provided."))]
    InvalidSocketAddress { backtrace: Backtrace },
    /// Invalid response error. Server returned unexpected data.
    #[snafu(display("Received invalid response, {}{:?}", context, data))]
    InvalidResponse {
        /// Context of action, empty per default.
        ///
        /// Please use a format like `"expected XY, got: "`
        context: &'static str,
        data: String,
    },
    #[snafu(display("Got invalid int response {}: {}", data, source))]
    InvalidIntResponse {
        data: String,
        source: std::num::ParseIntError,
        backtrace: Backtrace,
    },
    /// TS3-Server error response
    #[snafu(display("Server responded with error: {}", response))]
    ServerError {
        response: ErrorResponse,
        backtrace: Backtrace,
    },
    /// Maximum amount of response bytes/lines reached, DDOS limit prevented further data read.
    ///
    /// This will probably cause the current connection to become invalid due to remaining data in the connection.
    #[snafu(display("Invalid response, DDOS limit reached: {:?}", response))]
    ResponseLimit {
        response: Vec<String>,
        backtrace: Backtrace,
    },
    /// Invalid name length. Client-Name is longer than allowed!
    #[cfg(feature = "managed")]
    #[snafu(display("Invalid name length: {} max: {}!", length, expected))]
    InvalidNameLength { length: usize, expected: usize },
    /// No entry for key in server response, expected one.
    #[snafu(display("Expected entry for key {}, key not found!", key))]
    NoEntryResponse {
        key: &'static str,
        backtrace: Backtrace,
    },
    /// No value for key in response, expected some.
    #[snafu(display("Expected value for key {}, got none!", key))]
    NoValueResponse {
        key: &'static str,
        backtrace: Backtrace,
    },
}

impl Ts3Error {
    /// Returns true if the error is of kind ServerError
    pub fn is_error_response(&self) -> bool {
        match self {
            Ts3Error::ServerError { .. } => true,
            _ => false,
        }
    }
    /// Returns the [`ErrorResponse`](ErrorResponse) if existing.
    pub fn error_response(&self) -> Option<&ErrorResponse> {
        match self {
            Ts3Error::ServerError { response, .. } => Some(response),
            _ => None,
        }
    }
}

impl From<io::Error> for Ts3Error {
    fn from(error: io::Error) -> Self {
        Ts3Error::Io {
            context: "",
            source: error,
        }
    }
}

/// Ts3 Query client with active connection
pub struct QueryClient {
    rx: BufReader<TcpStream>,
    tx: TcpStream,
    limit_lines: usize,
    limit_lines_bytes: u64,
}

/// Default DoS limit for read lines
pub const LIMIT_READ_LINES: usize = 100;
/// Default DoS limit for read bytes per line
pub const LIMIT_LINE_BYTES: u64 = 64_000;

type Result<T> = ::std::result::Result<T, Ts3Error>;

impl Drop for QueryClient {
    fn drop(&mut self) {
        #[allow(unused_variables)]
        if let Err(e) = self.quit() {
            #[cfg(feature = "debug_response")]
            eprintln!("Can't quit on drop: {}", e);
        }
        let _ = self.tx.shutdown(Shutdown::Both);
    }
}

impl QueryClient {
    /// Create new query connection
    pub fn new<A: ToSocketAddrs>(addr: A) -> Result<Self> {
        let (rx, tx) = Self::new_inner(addr, None, None)?;

        Ok(Self {
            rx,
            tx,
            limit_lines: LIMIT_READ_LINES,
            limit_lines_bytes: LIMIT_LINE_BYTES,
        })
    }

    /// Create new query connection with timeouts
    ///
    /// `t_connect` is used for connection, `timeout` for read/write operations
    pub fn with_timeout<A: ToSocketAddrs>(
        addr: A,
        t_connect: Option<Duration>,
        timeout: Option<Duration>,
    ) -> Result<Self> {
        let (rx, tx) = Self::new_inner(addr, timeout, t_connect)?;

        Ok(Self {
            rx,
            tx,
            limit_lines: LIMIT_READ_LINES,
            limit_lines_bytes: LIMIT_LINE_BYTES,
        })
    }

    /// Set new maximum amount of lines to read per response, until DoS protection triggers.
    pub fn limit_lines(&mut self, limit: usize) {
        self.limit_lines = limit;
    }

    /// Set new maximum amount of bytes per line to read until DoS protection triggers.  
    /// You may need to increase this for backup/restore of instances.
    pub fn limit_line_bytes(&mut self, limit: u64) {
        self.limit_lines_bytes = limit;
    }

    /// Rename this client, performs `clientupdate client_nickname` escaping the name
    pub fn rename<T: AsRef<str>>(&mut self, name: T) -> Result<()> {
        writeln!(
            &mut self.tx,
            "clientupdate client_nickname={}",
            escape_arg(name)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Update channel name, performs `channeledit channel_name`
    pub fn rename_channel<T: AsRef<str>>(&mut self, channel: ChannelId, name: T) -> Result<()> {
        writeln!(
            &mut self.tx,
            "channeledit cid={} channel_name={}",
            channel,escape_arg(name)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Update client description. If target is none updates this clients description.
    ///
    /// Performs `clientupdate CLIENT_DESCRIPTION` or `clientedit clid=` with `CLIENT_DESCRIPTION` if target is set.
    pub fn update_description<T: AsRef<str>>(
        &mut self,
        descr: T,
        target: Option<ClientId>,
    ) -> Result<()> {
        if let Some(clid) = target {
            writeln!(
                &mut self.tx,
                "clientedit clid={} CLIENT_DESCRIPTION={}",
                clid,
                escape_arg(descr)
            )?;
        } else {
            writeln!(
                &mut self.tx,
                "clientupdate CLIENT_DESCRIPTION={}",
                escape_arg(descr)
            )?;
        }
        let _ = self.read_response()?;
        Ok(())
    }

    /// Poke a client.
    ///
    /// Performs `clientpoke`
    pub fn poke_client<T: AsRef<str>>(&mut self, client: ClientId, msg: T) -> Result<()> {
        writeln!(
            &mut self.tx,
            "clientpoke clid={} msg={}",
            client,
            msg.as_ref()
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Send chat message
    pub fn send_message<T: AsRef<str>>(&mut self, target: MessageTarget, msg: T) -> Result<()> {
        writeln!(
            &mut self.tx,
            "sendtextmessage {} msg={}",
            target,
            escape_arg(msg)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Send quit command, does not close the socket, not to be exposed
    fn quit(&mut self) -> Result<()> {
        writeln!(&mut self.tx, "quit")?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Inner new-function that handles greeting etc
    fn new_inner<A: ToSocketAddrs>(
        addr: A,
        timeout: Option<Duration>,
        conn_timeout: Option<Duration>,
    ) -> Result<(BufReader<TcpStream>, TcpStream)> {
        let addr = addr
            .to_socket_addrs()
            .context(Io {
                context: "invalid socket address",
            })?
            .next()
            .context(InvalidSocketAddress {})?;
        let stream = if let Some(dur) = conn_timeout {
            TcpStream::connect_timeout(&addr, dur).context(Io {
                context: "while connecting: ",
            })?
        } else {
            TcpStream::connect(addr).context(Io {
                context: "while connecting: ",
            })?
        };

        stream.set_write_timeout(timeout).context(Io {
            context: "setting write timeout: ",
        })?;
        stream.set_read_timeout(timeout).context(Io {
            context: "setting read timeout: ",
        })?;

        stream.set_nodelay(true).context(Io {
            context: "setting nodelay: ",
        })?;

        let mut reader = BufReader::new(stream.try_clone().context(Io {
            context: "splitting connection: ",
        })?);

        // read server type token
        let mut buffer = Vec::new();
        reader.read_until(b'\r', &mut buffer).context(Io {
            context: "reading response: ",
        })?;

        buffer.clear();
        if let Err(e) = reader.read_until(b'\r', &mut buffer) {
            use std::io::ErrorKind::*;
            match e.kind() {
                TimedOut | WouldBlock => (), // ignore no greeting
                _ => return Err(e.into()),
            }
        }

        Ok((reader, stream))
    }

    /// Perform a raw command, returns its response as raw value. (No unescaping is performed.)
    ///
    /// You need to escape the command properly.
    pub fn raw_command<T: AsRef<str>>(&mut self, command: T) -> Result<Vec<String>> {
        writeln!(&mut self.tx, "{}", command.as_ref())?;
        let v = self.read_response()?;
        Ok(v)
    }

    /// Performs `whoami`
    ///
    /// Returns a hashmap of entries. Values are unescaped if set.
    pub fn whoami(&mut self, unescape: bool) -> Result<HashMap<String, Option<String>>> {
        writeln!(&mut self.tx, "whoami")?;
        let v = self.read_response()?;
        Ok(parse_hashmap(v, unescape))
    }

    /// Logout
    pub fn logout(&mut self) -> Result<()> {
        writeln!(&mut self.tx, "logout")?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Login with provided data
    ///
    /// On drop queryclient issues a logout
    pub fn login<T: AsRef<str>, S: AsRef<str>>(&mut self, user: T, password: S) -> Result<()> {
        writeln!(
            &mut self.tx,
            "login {} {}",
            escape_arg(user),
            escape_arg(password)
        )?;

        let _ = self.read_response()?;

        Ok(())
    }

    /// Select server to perform commands on, by port
    ///
    /// Performs `use port`
    pub fn select_server_by_port(&mut self, port: u16) -> Result<()> {
        writeln!(&mut self.tx, "use port={}", port)?;

        let _ = self.read_response()?;
        Ok(())
    }

    /// Move client to channel with optional channel password
    ///
    /// Performs `clientmove`
    pub fn move_client(
        &mut self,
        client: ClientId,
        channel: ChannelId,
        password: Option<&str>,
    ) -> Result<()> {
        let pw_arg = if let Some(pw) = password {
            format!("cpw={}", raw::escape_arg(pw).as_str())
        } else {
            String::new()
        };
        writeln!(
            &mut self.tx,
            "clientmove clid={} cid={} {}",
            client, channel, pw_arg
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Kick client with specified message from channel/server. Message can't be longer than 40 characters.
    ///
    /// Performs `clientkick`
    pub fn kick_client(
        &mut self,
        client: ClientId,
        server: bool,
        message: Option<&str>,
    ) -> Result<()> {
        let msg_arg = if let Some(pw) = message {
            format!("reasonmsg={}", raw::escape_arg(pw).as_str())
        } else {
            String::new()
        };
        let rid = if server { 5 } else { 4 };
        writeln!(
            &mut self.tx,
            "clientkick clid={} reasonid={} {}",
            client, rid, msg_arg
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Create file directory in channel, has to be a valid path starting with `/`
    ///
    /// Performs `ftcreatedir`
    pub fn create_dir<T: AsRef<str>>(&mut self, channel: ChannelId, path: T) -> Result<()> {
        writeln!(
            &mut self.tx,
            "ftcreatedir cid={} cpw= dirname={}",
            channel,
            escape_arg(path)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Delete File/Folder in channel, acts recursive on folders
    ///
    /// Example: `/My Directory` deletes everything inside that directory.
    ///
    /// Performs `ftdeletefile`
    pub fn delete_file<T: AsRef<str>>(&mut self, channel: ChannelId, path: T) -> Result<()> {
        writeln!(
            &mut self.tx,
            "ftdeletefile cid={} cpw= name={}",
            channel,
            escape_arg(path)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Low-cost connection check
    ///
    /// Performs `whoami` command without parsing
    pub fn ping(&mut self) -> Result<()> {
        writeln!(&mut self.tx, "whoami")?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Select server to perform commands on, by server id.
    ///
    /// Performs `use sid`
    pub fn select_server_by_id(&mut self, sid: ServerId) -> Result<()> {
        writeln!(&mut self.tx, "use sid={}", sid)?;

        let _ = self.read_response()?;
        Ok(())
    }

    /// Performs `servergroupdelclient`  
    /// Removes all client-db-ids in `cldbid` from the specified `group` id.
    pub fn server_group_del_clients(
        &mut self,
        group: ServerGroupID,
        cldbid: &[usize],
    ) -> Result<()> {
        if cldbid.is_empty() {
            return Ok(());
        }
        writeln!(
            &mut self.tx,
            "servergroupdelclient sgid={} {}",
            group,
            Self::format_cldbids(cldbid)
        )?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Performs `servergroupaddclient`  
    /// Ads all specified `cldbid` clients to `group`.
    pub fn server_group_add_clients(
        &mut self,
        group: ServerGroupID,
        cldbid: &[usize],
    ) -> Result<()> {
        if cldbid.is_empty() {
            return Ok(());
        }
        let v = Self::format_cldbids(cldbid);
        writeln!(&mut self.tx, "servergroupaddclient sgid={} {}", group, v)?;
        let _ = self.read_response()?;
        Ok(())
    }

    /// Turn a list of client-db-ids into a list of cldbid=X
    fn format_cldbids(it: &[usize]) -> String {
        // would need itertools for format_with

        let mut res = String::new();
        let mut it = it.iter();
        if let Some(n) = it.next() {
            write!(res, "cldbid={}", n).unwrap();
        }
        for n in it {
            write!(res, "|cldbid={}", n).unwrap();
        }
        res
    }

    /// Read response and check error line
    fn read_response(&mut self) -> Result<Vec<String>> {
        let mut result: Vec<String> = Vec::new();
        let mut lr = (&mut self.rx).take(self.limit_lines_bytes);
        for _ in 0..self.limit_lines {
            let mut buffer = Vec::new();
            // damn cargo fmt..
            if lr.read_until(b'\r', &mut buffer).context(Io {
                context: "reading response: ",
            })? == 0
            {
                return ConnectionClosed {}.fail();
            }
            // we read until \r or max-read limit
            if buffer.ends_with(&[b'\r']) {
                buffer.pop();
                if buffer.ends_with(&[b'\n']) {
                    buffer.pop();
                }
            } else if lr.limit() == 0 {
                return ResponseLimit { response: result }.fail();
            } else {
                return InvalidResponse {
                    context: "expected \\r delimiter, got: ",
                    data: String::from_utf8_lossy(&buffer),
                }
                .fail();
            }

            if !buffer.is_empty() {
                let line = String::from_utf8(buffer).context(Utf8Error)?;
                #[cfg(feature = "debug_response")]
                println!("Read: {:?}", &line);
                if line.starts_with("error ") {
                    Self::check_ok(&line)?;
                    return Ok(result);
                }
                result.push(line);
            }
            lr.set_limit(LIMIT_LINE_BYTES);
        }
        ResponseLimit { response: result }.fail()
    }

    /// Returns a list of online clients with full infos. Visiblity depends on current permissions. Values are unescaped where applicable.
    ///
    /// Performs `clientlist -uid -away -voice -times -groups -info -country -ip -badges`
    pub fn online_clients_full(&mut self) -> Result<Vec<OnlineClientFull>> {
        writeln!(
            &mut self.tx,
            "clientlist -uid -away -voice -times -groups -info -country -ip -badges"
        )?;
        let res = self.read_response()?;

        let clients = raw::parse_multi_hashmap(res, false)
            .into_iter()
            .map(|v| Ok(OnlineClientFull::from_raw(v)?))
            .collect::<Result<_>>()?;

        Ok(clients)
    }

    /// Returns a list of online clients. Visiblity depends on current permissions. Values are unescaped where applicable.
    ///
    /// Performs `clientlist`
    pub fn online_clients(&mut self) -> Result<Vec<OnlineClient>> {
        writeln!(&mut self.tx, "clientlist")?;
        let res = self.read_response()?;

        let clients = raw::parse_multi_hashmap(res, false)
            .into_iter()
            .map(|v| Ok(OnlineClient::from_raw(v)?))
            .collect::<Result<_>>()?;

        Ok(clients)
    }

    /// Returns a list of channels. Values are unescaped where applicable.
    ///
    /// Performs `channellist`
    pub fn channels(&mut self) -> Result<Vec<Channel>> {
        writeln!(&mut self.tx, "channellist")?;
        let res = self.read_response()?;

        let channels = raw::parse_multi_hashmap(res, false)
            .into_iter()
            .map(|v| Ok(Channel::from_raw(v)?))
            .collect::<Result<_>>()?;

        Ok(channels)
    }

    /// Returns a list of channels with full infos. Values are unescaped where applicable.
    ///
    /// Performs `channellist -topic -flags -voice -limits -icon -secondsempty`
    pub fn channels_full(&mut self) -> Result<Vec<ChannelFull>> {
        writeln!(
            &mut self.tx,
            "channellist -topic -flags -voice -limits -icon -secondsempty"
        )?;
        let res = self.read_response()?;

        let channels = raw::parse_multi_hashmap(res, false)
            .into_iter()
            .map(|v| Ok(ChannelFull::from_raw(v)?))
            .collect::<Result<_>>()?;

        Ok(channels)
    }

    /// Deletes a channel
    ///
    /// Performs `channeldelete cid={} force={}`
    pub fn delete_channel(&mut self, id: ChannelId, force: bool) -> Result<()> {
        writeln!(
            &mut self.tx,
            "channeldelete cid={} force={}",
            id,
            if force { 1 } else { 0 }
        )?;
        let _ = self.read_response()?;

        Ok(())
    }

    /// Creates a channel
    /// Performs `channelcreate`
    pub fn create_channel(&mut self, channel: &ChannelEdit) -> Result<ChannelId> {
        writeln!(&mut self.tx, "channelcreate{}", &channel.to_raw())?;
        let res = self.read_response()?;

        let mut response = raw::parse_hashmap(res, false);
        let cid = int_val_parser(&mut response, "cid")?;

        Ok(cid)
    }

    /// Returns a list of server groups. May contain templates and query groups if permitted. Values are unescaped where applicable.
    ///
    /// Performs `servergrouplist`
    pub fn server_groups(&mut self) -> Result<Vec<ServerGroup>> {
        writeln!(&mut self.tx, "servergrouplist")?;
        let res = self.read_response()?;

        let groups = raw::parse_multi_hashmap(res, false)
            .into_iter()
            .map(|v| Ok(ServerGroup::from_raw(v)?))
            .collect::<Result<_>>()?;

        Ok(groups)
    }

    /// Get a list of client-DB-IDs for a given server group ID
    ///
    /// See `servergroupclientlist`
    pub fn servergroup_client_cldbids(&mut self, group: ServerGroupID) -> Result<Vec<usize>> {
        writeln!(&mut self.tx, "servergroupclientlist sgid={}", group)?;

        let resp = self.read_response()?;
        if let Some(line) = resp.get(0) {
            let data: Vec<usize> = line
                .split('|')
                .map(|e| {
                    if let Some(cldbid) = e.split('=').collect::<Vec<_>>().get(1) {
                        Ok(cldbid
                            .parse::<usize>()
                            .map_err(|_| Ts3Error::InvalidResponse {
                                context: "expected usize, got ",
                                data: line.to_string(),
                            })?)
                    } else {
                        Err(Ts3Error::InvalidResponse {
                            context: "expected data of cldbid=1, got ",
                            data: line.to_string(),
                        })
                    }
                })
                .collect::<Result<Vec<usize>>>()?;
            Ok(data)
        } else {
            Ok(Vec::new())
        }
    }

    /// Check if error line is ok
    fn check_ok(msg: &str) -> Result<()> {
        let result: Vec<&str> = msg.split(' ').collect();
        #[cfg(debug)]
        {
            // should only be invoked on `error` lines, sanity check
            assert_eq!(
                "check_ok invoked on non-error line",
                result.get(0),
                Some(&"error")
            );
        }
        if let (Some(id), Some(msg)) = (result.get(1), result.get(2)) {
            let split_id: Vec<&str> = id.split('=').collect();
            let split_msg: Vec<&str> = msg.split('=').collect();
            if let (Some(id), Some(msg)) = (split_id.get(1), split_msg.get(1)) {
                let id = id.parse::<usize>().map_err(|_| Ts3Error::InvalidResponse {
                    context: "expected usize, got ",
                    data: (*msg).to_string(), // clippy lint
                })?;
                if id != 0 {
                    return ServerError {
                        response: ErrorResponse {
                            id,
                            msg: unescape_val(*msg),
                        },
                    }
                    .fail();
                } else {
                    return Ok(());
                }
            }
        }
        Err(Ts3Error::InvalidResponse {
            context: "expected id and msg, got ",
            data: msg.to_string(),
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_format_cldbids() {
        let ids = vec![0, 1, 2, 3];
        assert_eq!(
            "cldbid=0|cldbid=1|cldbid=2|cldbid=3",
            QueryClient::format_cldbids(&ids)
        );
        assert_eq!("", QueryClient::format_cldbids(&[]));
        assert_eq!("cldbid=0", QueryClient::format_cldbids(&ids[0..1]));
    }
}