This commit is contained in:
Meghdad committed 2026-11-01 19:43:03 +03:30
commit 22fe85bb92
247 files changed
+35538

No files matched your search

@@ -0,0 +1,44 @@
[package]
name = "ts-bookkeeping"
version = "0.1.0"
authors = ["Flakebi <flakebi@t-online.de>"]
description = "Structs to store the state of a TeamSpeak server, with its clients and channels."
repository = "https://github.com/ReSpeak/tsclientlib/tree/master/utils/ts-bookkeeping"
readme = "README.md"
keywords = ["teamspeak3", "ts3"]
license = "MIT OR Apache-2.0"
build = "build/build.rs"
edition = "2018"
autobenches = false
include = [
"/Cargo.toml",
"/README.md",
"**/*.rs",
"**/*.tt",
]
[dependencies]
base64 = "0.22"
num-traits = "0.2"
num-derive = "0.4"
serde = { version = "1", features = ["derive"] }
thiserror = "2"
time = { version = "0.3", features = ["serde"] }
tracing = "0.1"
tsproto-packets = { path = "../tsproto-packets", version = "0.1" }
tsproto-types = { path = "../tsproto-types", version = "0.1" }
[build-dependencies]
heck = "0.5"
itertools = "0.14"
t4rust-derive = "0.3"
tsproto-structs = { path = "../tsproto-structs", version = "0.2" }
[dev-dependencies]
criterion = "0.8"
once_cell = "1"
tracing-subscriber = "0.3"
[[bench]]
name = "command"
harness = false
@@ -0,0 +1,21 @@
# ts-bookkeeping [![docs.rs](https://docs.rs/ts-bookkeeping/badge.svg)](https://docs.rs/ts-bookkeeping)
`ts-bookkeeping` contains structs to store the state of a TeamSpeak server, with its clients and
channels.
The crate can be used to keep track of the state on a server by processing all incoming
commands, which is why it is called “bookkeeping”. It also contains generated structs for all
TeamSpeak commands.
Incoming commands can be applied to the state and generate [`events`]. The main struct is
[`data::Connection`].
The structs have methods to create packets for various actions. The generated packets can be
sent to a server.
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
@@ -0,0 +1,10 @@
# ts-bookkeeping [![docs.rs](https://docs.rs/ts-bookkeeping/badge.svg)](https://docs.rs/ts-bookkeeping)
{{readme}}
## License
Licensed under either of
* [Apache License, Version 2.0](../../LICENSE-APACHE)
* [MIT license](../../LICENSE-MIT)
at your option.
@@ -0,0 +1,44 @@
use std::iter;
use criterion::{criterion_group, criterion_main, Bencher, Criterion};
use once_cell::sync::Lazy;
use ts_bookkeeping::messages::s2c::{self, InMessage};
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
const SHORT_CMD: &[u8] = b"notifyclientleftview cfid=1 ctid=0 clid=61";
const LONG_CMD: &[u8] = b"channellist cid=2 cpid=0 channel_name=Trusted\\sChannel channel_topic channel_codec=0 channel_codec_quality=0 channel_maxclients=0 channel_maxfamilyclients=-1 channel_order=1 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=0 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic channel_icon_id=0 channel_flag_private=0|cid=4 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s1\\s\\p\\sSplamy\xc2\xb4s\\sBett channel_topic channel_codec=4 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=0 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=Neo\\sSeebi\\sEvangelion channel_icon_id=0 channel_flag_private=0|cid=6 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s2\\s\\p\\sThe\\sBook\\sof\\sHeavy\\sMetal channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=4 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=Not\\senought\\sChannels channel_icon_id=0 channel_flag_private=0|cid=30 cpid=2 channel_name=Ding\\s\xe2\x80\xa2\\s3\\s\\p\\sSenpai\\sGef\xc3\xa4hrlich channel_topic channel_codec=2 channel_codec_quality=7 channel_maxclients=-1 channel_maxfamilyclients=-1 channel_order=6 channel_flag_permanent=1 channel_flag_semi_permanent=0 channel_flag_default=0 channel_flag_password=0 channel_codec_latency_factor=1 channel_codec_is_unencrypted=1 channel_delete_delay=0 channel_flag_maxclients_unlimited=1 channel_flag_maxfamilyclients_unlimited=0 channel_flag_maxfamilyclients_inherited=1 channel_needed_talk_power=0 channel_forced_silence=0 channel_name_phonetic=The\\strashcan\\shas\\sthe\\strash channel_icon_id=0 channel_flag_private=0";
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
fn parse(b: &mut Bencher, cmd: &[u8]) {
Lazy::force(&TRACING);
let header = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
b.iter(|| InMessage::new(&header.header(), cmd).unwrap());
}
fn write(b: &mut Bencher, cmd: &[u8]) {
Lazy::force(&TRACING);
let header = OutPacket::new_with_dir(Direction::S2C, Flags::empty(), PacketType::Command);
let msg = InMessage::new(&header.header(), cmd).unwrap();
match msg {
InMessage::ClientLeftView(msg) => {
let out_part = msg.iter().next().unwrap().as_out();
b.iter(|| s2c::OutClientLeftViewMessage::new(&mut iter::once(out_part.clone())));
}
InMessage::ChannelList(msg) => {
let out_part = msg.iter().next().unwrap().as_out();
b.iter(|| s2c::OutChannelListMessage::new(&mut iter::once(out_part.clone())));
}
_ => unreachable!("This command type is not supported in this test"),
}
}
fn parse_short(c: &mut Criterion) { c.bench_function("parse short", |b| parse(b, SHORT_CMD)); }
fn parse_long(c: &mut Criterion) { c.bench_function("parse long", |b| parse(b, LONG_CMD)); }
fn write_short(c: &mut Criterion) { c.bench_function("write short", |b| write(b, SHORT_CMD)); }
fn write_long(c: &mut Criterion) { c.bench_function("write long", |b| write(b, LONG_CMD)); }
criterion_group!(benches, parse_short, parse_long, write_short, write_long);
criterion_main!(benches);
@@ -0,0 +1,14 @@
<#@ template cleanws="true" #>
<# for struc in &self.0.structs { #>
<#= doc_comment(&struc.doc) #>
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct <#= struc.name #> {
<# for p in struc.get_all_properties() {
if let Some(ref doc) = p.get_doc() { #>
<#= indent(doc_comment(doc), 1) #>
<# } #>
pub <#= p.get_attr_name(&struc) #>: <#= p.get_type(&self.0.structs)? #>,
<# } #>
}
<# } #>
@@ -0,0 +1,232 @@
<#@ template cleanws="true" #>
<#
use std::{fmt, iter};
use tsproto_structs::messages::{MessageDeclarations, MessageGroup};
fn get_all_arguments<'a>(e: &'a Event<'a>, r: Option<&'a RuleKind<'a>>) -> String {
let mut args = String::new();
for r in e.ids.iter().chain(r.iter().cloned()) {
match r {
RuleKind::ArgumentMap { .. } |
RuleKind::ArgumentFunction { .. } => {
let arg = r.get_argument();
if !arg.is_empty() {
args.push_str(", ");
args.push_str(&arg);
}
}
_ => {}
}
}
args
}
fn get_all_id_arguments<'a>(e: &'a Event<'a>) -> String {
let mut args = String::new();
for r in &e.ids {
match r {
RuleKind::ArgumentMap { .. } |
RuleKind::ArgumentFunction { .. } => {
let arg = r.get_argument();
if !arg.is_empty() {
args.push_str(&arg);
args.push_str(", ");
}
}
_ => {}
}
}
args
}
fn create_message(
_fmt: &mut fmt::Formatter, e: &Event, rule: Option<&RuleKind>,
msg_group: &MessageGroup, messages: &MessageDeclarations,
) -> fmt::Result {
for r in e.ids.iter().chain(rule.iter().cloned()) {
call_func(_fmt, r)?;
}
#>
c2s::Out<#= e.msg.name #>Part {
<#
for a in &e.msg.attributes {
let field = messages.get_field(a);
let (from_rule, found) = find_rule(e, rule, field);
let from = match found {
Some(RuleKind::Map { from, .. }) => {
let from_self = if from_rule { "" } else { "self." };
Some(format!("{}{}", from_self, from.name.to_snake_case()))
}
Some(found@RuleKind::ArgumentMap { .. }) => Some(found.from_name().to_snake_case()),
Some(RuleKind::Function { .. })
| Some(RuleKind::ArgumentFunction { .. }) => Some(field.get_rust_name()),
None => None,
};
if let Some(from) = from {
if field.is_opt(&e.msg) { #>
<#= field.get_rust_name() #>: Some(<#= from #>.into()),
<# } else { #>
<#= field.get_rust_name() #>: <#= from #>.into(),
<# }
} else { #>
<#= field.get_rust_name() #>: None,
<# }
} #>
}
<#
Ok(())
}
/// Calls function if it is one, otherwise does nothing.
fn call_func(_fmt: &mut fmt::Formatter, r: &RuleKind) -> fmt::Result {
match r {
RuleKind::Function { name, to, .. } => { #>
let <#= get_to_list(to.as_slice()) #> = self.<#= name.to_snake_case() #>();
<# }
RuleKind::ArgumentFunction { from, to, name, .. } => { #>
let <#= get_to_list(to.as_slice())
#> = self.<#= name.to_snake_case() #>(<#= from.to_snake_case() #>);
<# }
_ => {}
}
Ok(())
}
/// Calls function if it is one, otherwise does nothing.
fn call_func2(_fmt: &mut fmt::Formatter, struct_name: &str, r: &RuleKind) -> fmt::Result {
match r {
RuleKind::Function { name, to, .. } => { #>
let <#= get_to_list(to.as_slice()) #> = <#= struct_name #>::<#= name.to_snake_case() #>();
<# }
RuleKind::ArgumentFunction { from, to, name, .. } => { #>
let <#= get_to_list(to.as_slice())
#> = <#= struct_name #>::<#= name.to_snake_case() #>(<#= from.to_snake_case() #>);
<# }
_ => {}
}
Ok(())
}
for e in &self.decls {
let msg_group = self.messages.get_message_group(&e.msg);
let uses_lifetime = self.messages.uses_lifetime(&e.msg);
// Update
if e.op == RuleOp::Update {
let small_change_name = e.get_small_name();
let change_name = e.get_change_name();
#>
impl <#= e.book_struct.name #> {
pub fn <#= change_name.to_snake_case() #><# if uses_lifetime { #><'a><# } #>(&self, <#=
get_all_id_arguments(e).replace('&', "&'a ") #>
<# if e.msg.attributes.is_empty() { #>
) -> OutCommand
<# } else { #>
) -> c2s::Out<#= e.msg.name #>Part<# if uses_lifetime { #><'a><# } #>
<# } #>
{
<# if e.msg.attributes.is_empty() { #>
c2s::Out<#= e.msg.name #>Message::new()
<# } else { #>
<# create_message(_fmt, e, None, msg_group, &self.messages)?; #>
<# } #>
}
}
<# if !e.rules.is_empty() { #>
pub trait M2B<#= e.msg.name #>Ext<# if uses_lifetime { #><'a><# } #> {
<# for r in &e.rules {
let name = r.from_name();
#>
fn set_<#= name.to_snake_case() #>(self, <#= r.get_argument_no_option()
.replace('&', "&'a ") #>) -> Self;
<# } #>
}
impl<# if uses_lifetime { #><'a><# } #> M2B<#= e.msg.name #>Ext<# if uses_lifetime { #><'a><# } #> for c2s::Out<#= e.msg.name #>Part<# if uses_lifetime { #><'a><# } #> {
<# for r in &e.rules {
let name = r.from_name();
let from_name;
match r {
RuleKind::Map { from, .. } => {
from_name = format!("self.{}", from.name.to_snake_case());
}
RuleKind::ArgumentMap { .. } => from_name = r.from_name().to_snake_case(),
RuleKind::Function { .. }
| RuleKind::ArgumentFunction { .. } => from_name = r.from_name().to_snake_case(),
}
#>
fn set_<#= name.to_snake_case() #>(mut self, <#= r.get_argument_no_option()
.replace('&', "&'a ") #>) -> Self {
<# call_func2(_fmt, &e.book_struct.name, r)?; #>
<# match r {
RuleKind::Map { to, .. }
| RuleKind::ArgumentMap { to, .. } => { #>
self.<#= to.get_rust_name() #> = Some(<#= r.from_name().to_snake_case() #>.into());
<# }
RuleKind::Function { to, .. }
| RuleKind::ArgumentFunction { to, .. } => {
for t in to { #>
self.<#= t.get_rust_name() #> = Some(<#= t.get_rust_name() #>.into());
<# }
}
} #>
self
}
<# } #>
}
<# } #>
<#
} else if e.op == RuleOp::Remove {
if e.rules.is_empty() {
let args = get_all_arguments(e, None);
let name_add = if !args.is_empty() {
format!("_{}", &args[2..args.find(':').unwrap()])
} else {
"".into()
}; #>
impl <#= e.book_struct.name #> {
pub fn remove<#= name_add #>(&self<#= args #>) -> OutCommand {
c2s::Out<#= e.msg.name #>Message::new(&mut std::iter::once({
<# create_message(_fmt, e, None, msg_group, &self.messages)?; #>
})<# if msg_group.default.response { #>, None<# } #>)
}
}
<# } else {
// Remove the property
for r in &e.rules {
let args = get_all_arguments(e, Some(r));
let name_add = if !args.is_empty() {
format!("_{}", &args[2..args.find(':').unwrap()])
} else {
"".into()
}; #>
impl <#= e.book_struct.name #> {
pub fn remove<#= name_add #>(&self<#= args #>) -> OutCommand {
c2s::Out<#= e.msg.name #>Message::new(&mut std::iter::once({
<# create_message(_fmt, e, Some(r), msg_group, &self.messages)?; #>
})<# if msg_group.default.response { #>, None<# } #>)
}
}
<# }
}
} else if e.op == RuleOp::Add {
for r in &e.rules {
let name = r.from_name_singular();
#>
impl <#= e.book_struct.name #> {
pub fn add_<#= name.to_snake_case() #>(&self<#= get_all_arguments(e, Some(r)) #>) -> OutCommand {
c2s::Out<#= e.msg.name #>Message::new(&mut std::iter::once({
<# create_message(_fmt, e, Some(r), msg_group, &self.messages)?; #>
})<# if msg_group.default.response { #>, None<# } #>)
}
}
<# }
}
} #>
@@ -0,0 +1,88 @@
<#@ template cleanws="true" #>
/// A `PropertyId` identifies a single attribute in the data structure of a
/// connection.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[non_exhaustive]
pub enum PropertyId {
<# for struc in &self.structs { #>
<#= struc.name #><#= struc.get_ids(&self.structs) #>,
<# } #>
<# for struc in self.structs.iter().filter(|s| !s.opt) {
for p in struc.get_properties(&self.structs) { #>
<#= struc.name #><#= p.get_name() #><#= p.get_ids(&self.structs, struc) #>,
<# }
} #>
}
/// A `PropertyValue` contains the value of an attribute in the data structures.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[non_exhaustive]
pub enum PropertyValue {
<# for struc in &self.structs { #>
<#= struc.name #>(<#= struc.get_type()? #>),
<# } #>
<#
let mut done = HashSet::new();
for struc in self.structs.iter().filter(|s| !s.opt) {
for p in struc.get_properties(&self.structs) {
let type_s = p.get_inner_type()?;
if !done.insert(type_s.to_string()) {
continue;
}
#>
<#= p.get_inner_type_as_name()? #>(<#= type_s #>),
<# }
} #>
}
/// A `PropertyValueRef` contains a reference to the value of an attribute in
/// the data structures.
///
/// See [`PropertyValue`] for the owned variant.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum PropertyValueRef<'a> {
<# for struc in &self.structs { #>
<#= struc.name #>(<#= struc.get_type()?.lifetime(true).to_ref(true) #>),
<# } #>
<#
let mut done = HashSet::new();
for struc in self.structs.iter().filter(|s| !s.opt) {
for p in struc.get_properties(&self.structs) {
let type_s = p.get_inner_type()?;
if !done.insert(type_s.to_string()) {
continue;
}
#>
<#= p.get_inner_type_as_name()? #>(<#= p.get_inner_type()?.lifetime(true).to_ref(true) #>),
<# }
} #>
}
impl PropertyValue {
pub fn as_ref(&self) -> PropertyValueRef<'_> {
match self {
<# for struc in &self.structs { #>
PropertyValue::<#= struc.name #>(s) => PropertyValueRef::<#= struc.name #>(<#= struc.get_type()?.code_as_ref("s").trim_start_matches('&') #>),
<# } #>
<#
let mut done = HashSet::new();
for struc in self.structs.iter().filter(|s| !s.opt) {
for p in struc.get_properties(&self.structs) {
let inner_type = p.get_inner_type()?;
if !done.insert(inner_type.to_string()) {
continue;
}
let name = inner_type.to_name();
let has_ref = inner_type.lifetime(true).to_ref(true).uses_lifetime();
#>
PropertyValue::<#= name #>(s) => PropertyValueRef::<#= name #>(<#= inner_type.wrap_ref().code_as_ref("s").trim_start_matches('&') #>),
<# }
} #>
}
}
}
@@ -0,0 +1,340 @@
<#@ template cleanws="true" #>
use std::borrow::Cow;
// Needed for vector serialization
#[allow(unused_imports)]
use std::fmt::Write as _;
use std::str;
use base64::prelude::*;
use num_traits::{FromPrimitive, ToPrimitive};
use tracing::{instrument, warn};
use tsproto_packets::commands::{CommandItem, CommandParser};
use tsproto_packets::packets::*;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum InMessage {
<# for msg_group in &self.0.msg_group {
for msg in &msg_group.msg { #>
<#= msg.name #>(In<#= msg.name #>),
<# }
} #>
}
impl InMessage {
/// Parse a message into a struct.
pub fn new(header: &InHeader, cmd: &[u8]) -> Result<Self> {
let (name, args) = CommandParser::new(cmd);
match name {
<#
let mut msgs: Vec<_> = self.0.msg_group.iter()
.flat_map(|g| g.msg.iter())
.filter(|m| m.notify.is_some())
.collect();
msgs.sort_unstable_by_key(|m| m.notify.as_ref().map(|s| s.as_str()).unwrap());
for (notify, group) in &msgs.iter().group_by(|m| m.notify.as_ref().map(|s| s.as_str()).unwrap()) {
let group: Vec<_> = group.collect();
let (msg, group) = group.split_last().unwrap();
#>
b"<#= notify #>" => <# for msg in group {
#>if let Ok(r) = In<#= msg.name #>::new(header, args.clone()) {
Ok(InMessage::<#= msg.name #>(r))
} else <#
} #>{
Ok(InMessage::<#= msg.name #>(In<#= msg.name #>::new(header, args)?))
}
<# } #>
s => Err(ParseError::UnknownCommand(str::from_utf8(s)?.to_string())),
}
}
pub fn get_command_name(&self) -> &'static str {
match self {
<# for msg_group in &self.0.msg_group {
for msg in &msg_group.msg { #>
InMessage::<#= msg.name #>(_) => "<#= if let Some(s) = &msg.notify { s } else { &msg.name } #>",
<# }
} #>
}
}
}
<# for msg_group in &self.0.msg_group {
for msg in &msg_group.msg {
let has_attributes = !msg.attributes.is_empty(); #>
#[derive(Clone, Debug)]
pub struct In<#= msg.name #> {
<# if msg_group.default.response { #>
pub return_code: Option<String>,
<# }
if has_attributes { #>
list: Vec<In<#= msg.name #>Part>,
<# } #>
}
<# if has_attributes { #>
#[derive(Clone, Debug)]
pub struct In<#= msg.name #>Part {
<# for a in &msg.attributes {
let field = self.0.get_field(a);
if field.get_rust_name() != field.ts { #>
/// `<#= field.ts #>` in TeamSpeak
<# } #>
pub <#= field.get_rust_name() #>: <#= field.get_type(a)? #>,
<# } #>
}
<# } #>
impl InMessageTrait for In<#= msg.name #> {
#[instrument(name = "parse_message", skip(header, <# if !has_attributes { #>_<# } #>args))]
fn new(header: &InHeader, <# if !has_attributes { #>_<# } #>args: CommandParser) -> Result<Self> {
// TODO newprotocol
//if <#= if msg_group.default.np { "!" } else { "" } #>header.flags().contains(Flags::NEWPROTOCOL) { return Err(ParseError::WrongNewprotocol(<#= if msg_group.default.np { "false" } else { "true" } #>)); }
if header.packet_type() != PacketType::Command<#= if msg_group.default.low { "Low" } else { "" } #> { return Err(ParseError::WrongPacketType(header.packet_type())); }
<# if !msg_group.default.s2c { #>
if header.direction() == Direction::S2C { return Err(ParseError::WrongDirection(header.direction())); }
<# } #>
<# if !msg_group.default.c2s { #>
if header.direction() == Direction::C2S { return Err(ParseError::WrongDirection(header.direction())); }
<# } #>
<# if msg_group.default.response { #>
let mut return_code = None;
<# } #>
<# for a in &msg.attributes { #>
let mut <#= self.0.get_field(a).get_rust_name() #> = None;
<# } #>
<# if !has_attributes { #>
Ok(In<#= msg.name #> {<# if msg_group.default.response { #> return_code <# } #>})
<# } else { #>
let mut list = Vec::<In<#= msg.name #>Part>::new();
for item in args.chain(std::iter::once(CommandItem::NextCommand)) {
match item {
CommandItem::NextCommand => {
// Build command
let new = In<#= msg.name #>Part {
<# for a in &msg.attributes {
let field = self.0.get_field(a);
let transform_func = if !field.get_type(a)?.is_primitive() {
".clone()"
} else {
""
}; #>
<#= field.get_rust_name() #>: <#= field.get_rust_name() #>
<# if !a.ends_with('?') { /* is not optional */ #>
.take()
.or_else(|| list.first().map(|p| p.<#= field.get_rust_name() #><#= transform_func #>))
.ok_or(ParseError::ParameterNotFound { arg: "<#= field.pretty #>", name: "<#= msg.name #>", })?,
<# } else { #>
.take()
.or_else(|| list.first().and_then(|p| p.<#= field.get_rust_name() #><#= transform_func #>)),
<# } #>
<# } #>
};
list.push(new);
}
CommandItem::Argument(arg) => {
match arg.name() {
<# for a in &msg.attributes {
let field = self.0.get_field(a); #>
b"<#= field.ts #>" => {
let val = arg.value().get_str()?;
let val = val.as_ref();
<#= field.get_rust_name() #> = Some({
<# #><#= generate_deserializer(field) #>
});
}
<# } #>
<# if msg_group.default.response { #>
b"return_code" => {
if return_code.is_some() {
warn!(command = "<#= msg.name #>", "Got multiple return codes");
}
return_code = Some(arg.value().get_str()?.into_owned());
}
<# } #>
s => warn!(command = "<#= msg.name #>", argument = ?str::from_utf8(s),
"Unknown argument"),
}
}
}
}
Ok(In<#= msg.name #> {<# if msg_group.default.response { #> return_code,<# } #> list })
<# } #>
}
}
<# if has_attributes { #>
impl In<#= msg.name #> {
#[inline]
pub fn iter(&self) -> InMessageIterator<In<#= msg.name #>Part> { self.into_iter() }
}
impl<'a> IntoIterator for &'a In<#= msg.name #> {
type Item = &'a In<#= msg.name #>Part;
type IntoIter = InMessageIterator<'a, In<#= msg.name #>Part>;
#[inline]
fn into_iter(self) -> Self::IntoIter { InMessageIterator(&self.list, 0) }
}
impl In<#= msg.name #>Part {
pub fn get_invoker(&self) -> Option<Invoker> {
<#
let mut has_invoker_id = false;
let mut has_invoker_name = false;
let mut has_invoker_uid = false;
let mut invoker_optional = true;
for a in &msg.attributes {
let field = self.0.get_field(a);
match field.ts.as_str() {
"invokerid" => {
has_invoker_id = true;
invoker_optional = a.ends_with('?');
}
"invokername" => has_invoker_name = true,
"invokeruid" => has_invoker_uid = true,
_ => {}
}
}
if has_invoker_id && has_invoker_name && has_invoker_uid { #>
<# if invoker_optional { #>
let id = self.invoker_id?;
let name = self.invoker_name.clone()?;
let uid = self.invoker_uid.clone();
<# } else { #>
let id = self.invoker_id;
let name = self.invoker_name.clone();
let uid = self.invoker_uid.clone();
<# } #>
Some(Invoker {
id,
name,
uid,
})
<# } else { #>
None
<# } #>
}
pub fn as_out(&self) -> Out<#= msg.name #>Part {
Out<#= msg.name #>Part {
<#
let mut uses_lifetime = false;
for a in &msg.attributes {
let field = self.0.get_field(a);
let ty = field.get_type(a)?;
let mut from = ty
.code_as_ref("field")
.replacen("field", &format!("self.{}", field.get_rust_name()), 1);
if ty.to_cow().is_cow() {
if ty.is_opt() {
from.push_str(".map(Cow::Borrowed)");
} else {
from = format!("Cow::Borrowed({})", from);
}
} #>
<#= field.get_rust_name() #>: <#= from #>,
<# } #>
}
}
}
<# } #>
<# }
} #>
/// The iterator is guaranteed to output at least one part.
pub struct InMessageIterator<'a, T>(&'a [T], usize);
impl<'a, T> Iterator for InMessageIterator<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<Self::Item> {
let i = self.1;
self.1 += 1;
self.0.get(i)
}
}
<# for msg_group in &self.0.msg_group {
let defs = &msg_group.default;
for msg in &msg_group.msg {
let uses_lifetime = self.0.uses_lifetime(msg);
let has_attributes = msg_group.default.response || !msg.attributes.is_empty(); #>
<# if has_attributes { #>
#[derive(Clone, Debug)]
pub struct Out<#= msg.name #>Part<# if uses_lifetime { #><'a><# } #> {
<# for a in &msg.attributes {
let field = self.0.get_field(a);
if field.get_rust_name() != field.ts { #>
/// `<#= field.ts #>` in TeamSpeak
<# } #>
pub <#= field.get_rust_name() #>: <#= field.get_type(a)?.to_cow().lifetime(true) #>,
<# } #>
}
<#
let part_name = format!("Out{}Part{}", msg.name, if uses_lifetime { "<'a>" } else { "" });
#>
impl<<# if uses_lifetime { #>'a, <# } #>> OutMessage<# if msg_group.default.response { #>WithReturn<# } #>Trait for &mut dyn Iterator<Item=<#= part_name #>> {
fn to_packet(self<#
if msg_group.default.response { #>, return_code: Option<&str><# } #>) -> OutCommand
where Self: Sized {
Out<#= msg.name #>Message::new(self<#
if msg_group.default.response { #>, return_code<# } #>)
}
}
impl<<# if uses_lifetime { #>'a, <# } #>> OutMessage<# if msg_group.default.response { #>WithReturn<# } #>Trait for <#= part_name #> {
fn to_packet(self<#
if msg_group.default.response { #>, return_code: Option<&str><# } #>) -> OutCommand
where Self: Sized {
Out<#= msg.name #>Message::new(&mut std::iter::once(self)<#
if msg_group.default.response { #>, return_code<# } #>)
}
}
<# } #>
pub struct Out<#= msg.name #>Message;
impl Out<#= msg.name #>Message {
#[allow(clippy::let_and_return, clippy::new_ret_no_self)]
pub fn new(<# if has_attributes { #>parts: &mut dyn Iterator<Item=Out<#= msg.name #>Part><#
if msg_group.default.response { #>, return_code: Option<&str><# } } #>) -> OutCommand {
let<# if has_attributes { #> mut<# } #> packet = OutCommand::new(
Direction::<#= if msg_group.default.s2c { "S2C" } else { "C2S" } #>,
Flags::<#= if msg_group.default.np { "NEWPROTOCOL" } else { "empty()" } #>,
PacketType::Command<# if msg_group.default.low { #>Low<# } #>,
"<#= msg.notify.as_ref().map(|s| s.as_str()).unwrap_or("") #>",
);
<# if msg_group.default.response { #>
if let Some(r) = return_code {
packet.write_arg("return_code", &r);
}
<# } #>
<# if !msg.attributes.is_empty() { #>
let mut first = true;
for p in parts {
if first {
first = false;
} else {
packet.start_new_part();
}
<# for a in &msg.attributes {
let field = self.0.get_field(a);
if a.ends_with('?') { #>
if let Some(val) = p.<#= field.get_rust_name() #> { packet.write_arg("<#= field.ts #>", <#= generate_serializer(field, "val") #>); }
<# } else { #>
packet.write_arg("<#= field.ts #>", <#= generate_serializer(field, &format!("p.{}", field.get_rust_name())) #>);
<# } #>
<# } #>
}
<# } #>
packet
}
}
<# }
} #>
@@ -0,0 +1,439 @@
<#@ template cleanws="true" #>
<#
/// Push into events the difference between two arrays.
///
/// The old value is stored in `old`, the `new` in the book.
fn diff(_fmt: &mut std::fmt::Formatter, new: &str, event: &Event, p: &Property, from: &Field) -> std::fmt::Result {
let mut ids = event.get_id_args("m");
let type_s = p.get_inner_type_as_name()?;
let added;
let removed;
let modifier = from.modifier.as_ref().unwrap();
if modifier == "array" {
added = format!("iter().filter(|n| !old.contains(n))");
removed = format!("into_iter().filter(|o| !{}.contains(o))", new);
} else if modifier == "set" {
added = format!("difference(&old)");
removed = format!("difference(&{})", new);
} else {
panic!("Unsupported modifier {}", modifier);
}
#>
// Added
for i in <#= new #>.<#= added #> {
events.push(Event::PropertyAdded {
id: PropertyId::<#= event.book_struct.name #><#= p.get_name() #>(<#= ids #>, *i),
invoker: invoker.clone(),
extra: ExtraInfo {
reason,
},
});
}
// Removed
for i in old.<#= removed #> {
events.push(Event::PropertyRemoved {
id: PropertyId::<#= event.book_struct.name #><#= p.get_name() #>(<#= ids #>, i),
old: PropertyValue::<#= type_s #>(i),
invoker: invoker.clone(),
extra: ExtraInfo {
reason,
},
});
}
<#
Ok(())
}
fn create_event(_fmt: &mut std::fmt::Formatter, event: &Event, change: &str, old: bool) -> std::fmt::Result {
let ids = embrace(&event.get_id_args("m"));
#>
events.push(Event::Property<#= change #> {
id: PropertyId::<#= event.book_struct.name #><#= ids #>,
<# if old { #>
old: PropertyValue::<#= event.book_struct.name #>(old),
<# } #>
invoker: invoker.clone(),
extra: ExtraInfo { reason },
});
<#
Ok(())
}
fn create_add_rule(_fmt: &mut std::fmt::Formatter, event: &Event) -> std::fmt::Result {
// Create a new object
// First, call all functions
for fun in event.rules.iter().filter(|r| r.is_function()) {
if let RuleKind::Function { name, to } = fun {
let return_match = if to.len() == 1 {
to[0].name.to_snake_case()
} else {
format!("({})", to.iter().map(|p| p.name.to_snake_case()).collect::<Vec<_>>().join(", "))
}; #>
let <#= return_match #> = self.<#= name.to_snake_case() #>(m, &mut events)?;
<# }
} #>
let r = <#= event.book_struct.name #> {
<#
// Add ids
for (id, fld) in event.book_struct.id.iter().zip(event.id.iter()) { #>
<#= PropId::from(id).get_attr_name(&event.book_struct) #>: m.<#= fld.get_rust_name() #>.clone(),
<# }
let v = vec![];
// Function return values
for p in event.rules.iter()
.flat_map(|f| if let RuleKind::Function { to, .. } = f {
to
} else {
&v
}) { #>
<#= p.name.to_snake_case() #>,
<# }
for p in event.rules.iter() {
if let RuleKind::Map { from, to, op } = p {
if *op != RuleOp::Update {
panic!("Cannot add or remove when adding a new struct");
}
let transform_func = if to.is_set() {
// Convert to set
".iter().cloned().collect()"
} else if !to.get_type()?.is_primitive() {
".clone()"
} else {
""
};
// to is optional, but from not
let from_opt = from.is_opt(&event.msg); #>
<#= to.name.to_snake_case() #>: <#
if to.opt && !from_opt {
#>Some(m.<#= from.get_rust_name() #><#= transform_func #>),
<# } else {
#>m.<#= from.get_rust_name() #><#= transform_func #>,
<# }
}
} #>
};
<#
Ok(())
}
#>
impl Connection {
/// Return if the message was handled and the generated events.
fn handle_command_generated(&mut self, msg: &InMessage) -> Result<(bool, Vec<Event>)> {
let mut events = Vec::new();
match msg {
<#
// Group events by message
let mut groups = HashMap::new();
for event in &self.decls {
let group = groups.entry(event.msg.name.as_str()).or_insert_with(Vec::new);
group.push(event);
}
for (msg_name, group) in groups {
let event = &group[0]; #>
InMessage::<#= msg_name #>(m) => for m in m.iter() {
#[allow(unused_variables)]
let invoker = m.get_invoker();
#[allow(unused_variables)]
<# if event.msg.attributes.iter().any(|a| a == "reasonid") { #>
let reason = Some(m.reason);
<# } else if event.msg.attributes.iter().any(|a| a == "reasonid?") { #>
let reason = m.reason;
<# } else { #>
let reason: Option<Reason> = None;
<# } #>
<#
for event in group {
let book_name = &event.book_struct.name;
#>
<# if event.op == RuleOp::Remove {
let function_name = format!("remove_{}", book_name.to_snake_case());
let mut ids = event.get_id_args("m");
if !ids.is_empty() { ids.push_str(", "); }
if !event.book_struct.opt { #>
let old = self.<#= function_name #>(<#= ids #>&mut events)?
.ok_or(Error::RemoveNotFound("<#= book_name #>"))?;
<# } else { #>
let old = self.<#= function_name #>(<#= ids #>&mut events)?;
<# }
create_event(_fmt, event, "Removed", true)?;
} else if event.op == RuleOp::Update && !event.book_struct.opt {
// Update the object
// Functions first
let mut rule_count = event.rules.len();
for rule in &event.rules {
if let RuleKind::Function { name, to } = rule {
rule_count -= 1; #>
self.<#= name.to_snake_case() #>(<#= event.get_id_args("m") #>, m, &mut events)?;
<# }
}
let function_name = format!("get_mut_{}", book_name.to_snake_case());
// Only print if necessary
if rule_count > 0 { #>
let r = self.<#= function_name #>(<#= event.get_id_args("m") #>)?;
<# }
for rule in &event.rules {
match rule {
RuleKind::Map { from, to, op } => {
// Put field from packet into bookkeeping struct
match op {
RuleOp::Update => {
let from_opt = from.is_opt(&event.msg);
// to/book is optional, but from/message not
if to.opt && !from_opt { #>
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, Some(m.<#= from.get_rust_name() #><# if !to.get_type()?.is_primitive() { #>.clone()<# } #>));
events.push(Event::PropertyChanged {
id: <#= event.get_property_id(to, from, "m") #>,
old: <#= get_property(to, "old") #>,
invoker: invoker.clone(),
extra: ExtraInfo { reason },
});
<# } else if from_opt {
let mut prefix = "";
let transform_func = if to.is_set() {
".iter().cloned().collect()"
} else if !to.get_type()?.is_primitive() {
".clone()"
} else {
prefix = "*";
""
}; #>
if let Some(val) = &m.<#= from.get_rust_name() #> {
<# if to.opt { #>
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, Some(<#= prefix #>val<#= transform_func #>));
<# } else { #>
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, <#= prefix #>val<#= transform_func #>);
<# } #>
<# if from.modifier.as_ref().map(|s| s == "array" || s == "set").unwrap_or(false) {
diff(_fmt, &format!("r.{}", to.name.to_snake_case()), event, to, from)?;
} else { #>
events.push(Event::PropertyChanged {
id: <#= event.get_property_id(to, from, "m") #>,
old: <#= get_property(to, "old") #>,
invoker: invoker.clone(),
extra: ExtraInfo { reason },
});
<# } #>
}
<# } else {
// Nothing is optional
#>
let old = mem::replace(&mut r.<#= to.name.to_snake_case() #>, m.<#= from.get_rust_name() #>.clone());
events.push(Event::PropertyChanged {
id: <#= event.get_property_id(to, from, "m") #>,
old: <#= get_property(to, "old") #>,
invoker: invoker.clone(),
extra: ExtraInfo { reason },
});
<# }
}
// The field in the struct is a vector
RuleOp::Add => {
if to.is_set() { #>
r.<#= to.name.to_snake_case() #>.insert(m.<#= from.get_rust_name() #>.clone());
<# } else { #>
r.<#= to.name.to_snake_case() #>.push(m.<#= from.get_rust_name() #>.clone());
<# } #>
events.push(Event::PropertyAdded {
id: <#= event.get_property_id(to, from, "m") #>,
invoker: invoker.clone(),
extra: ExtraInfo { reason },
});
<# }
RuleOp::Remove => {
if to.is_set() { #>
if r.<#= to.name.to_snake_case() #>.remove(&m.<#= from.get_rust_name() #>) {
let old = m.<#= from.get_rust_name() #>;
<# } else { #>
// Find index and remove
if let Some(i) = r.<#= to.name.to_snake_case() #>.iter().position(|i| *i == m.<#= from.get_rust_name() #>) {
let old = r.<#= to.name.to_snake_case() #>.remove(i);
<# } #>
events.push(Event::PropertyRemoved {
id: <#= event.get_property_id(to, from, "m") #>,
old: <#= get_property(to, "old") #>,
invoker: invoker.clone(),
extra: ExtraInfo { reason },
});
}
<# }
}
}
RuleKind::Function { to, .. } => {}
}
}
} else if event.op == RuleOp::Update && event.book_struct.opt {
// Optional structs that get only updated as a whole
// Create a new object
// First, call all functions
for fun in event.rules.iter().filter(|r| r.is_function()) {
if let RuleKind::Function { name, to } = fun {
let return_match = if to.len() == 1 {
to[0].name.to_snake_case()
} else {
format!("({})", to.iter().map(|p| p.name.to_snake_case()).collect::<Vec<_>>().join(", "))
}; #>
let <#= return_match #> = self.<#= name.to_snake_case() #>(m, &mut events)?;
<# }
}
// Check if all required data are available
// Pairs of (property, string to get the property)
let mut opt_props = Vec::new();
let mut props = Vec::new();
let v = Vec::new();
// Function return values
for p in event.rules.iter()
.flat_map(|f| if let RuleKind::Function { to, .. } = f {
to
} else {
&v
}) {
opt_props.push((p.name.to_snake_case(), p.name.to_snake_case()));
}
for p in event.rules.iter() {
if let RuleKind::Map { from, to, op } = p {
if *op != RuleOp::Update {
panic!("Cannot add or remove when adding a new struct");
}
let transform_func = if to.is_set() {
// Convert to set
".iter().cloned().collect()"
} else if !to.get_type()?.is_primitive() {
".clone()"
} else {
""
};
let from_opt = from.is_opt(&event.msg);
if to.opt && !from_opt {
// to is optional, but from not
let getter = format!("Some(m.{}{})", from.get_rust_name(), transform_func);
props.push((to.name.to_snake_case(), getter));
} else {
let getter = format!("m.{}{}", from.get_rust_name(), transform_func);
if from_opt && !to.opt {
opt_props.push((to.name.to_snake_case(), getter));
} else {
props.push((to.name.to_snake_case(), getter));
}
}
}
}
if !opt_props.is_empty() {
let mut matcher = opt_props.iter().map(|(p, _)| format!("Some({})", p)).collect::<Vec<_>>().join(", ");
let mut getter = opt_props.iter().map(|(_, p)| p.as_str()).collect::<Vec<_>>().join(", ");
if opt_props.len() > 1 {
matcher = format!("({})", matcher);
getter = format!("({})", getter);
}
#>
if let <#= matcher #> = <#= getter #> {
<# } #>
let r = <#= event.book_struct.name #> {
<#
// Add ids
for (id, fld) in event.book_struct.id.iter().zip(event.id.iter()) { #>
<#= PropId::from(id).get_attr_name(&event.book_struct) #>: m.<#= fld.get_rust_name() #>.clone(),
<# }
for (p, _) in &opt_props { #>
<#= p #>,
<# }
for (p, g) in &props {
if p != g { #>
<#= p #>: <#= g #>,
<# } else { #>
<#= p #>,
<# }
} #>
};
<#
let function_name = format!("replace_{}", book_name.to_snake_case());
let ids = event.get_id_args("m");
let comma = if ids.is_empty() { "" } else { ", " };
#>
let old = self.<#= function_name #>(<#= ids #><#= comma #>r, &mut events)?;
<# create_event(_fmt, event, "Changed", true)?;
if !opt_props.is_empty() { #>
}
<# }
} else if event.op == RuleOp::Add {
// Create a new object
// First, call all functions
for fun in event.rules.iter().filter(|r| r.is_function()) {
if let RuleKind::Function { name, to } = fun {
let return_match = if to.len() == 1 {
to[0].name.to_snake_case()
} else {
format!("({})", to.iter().map(|p| p.name.to_snake_case()).collect::<Vec<_>>().join(", "))
}; #>
let <#= return_match #> = self.<#= name.to_snake_case() #>(m, &mut events)?;
<# }
} #>
let r = <#= event.book_struct.name #> {
<#
// Add ids
for (id, fld) in event.book_struct.id.iter().zip(event.id.iter()) { #>
<#= PropId::from(id).get_attr_name(&event.book_struct) #>: m.<#= fld.get_rust_name() #><# if !id.find_property(&self.book.structs).get_type()?.is_primitive() { #>.clone()<# } #>,
<# }
let v = vec![];
// Function return values
for p in event.rules.iter()
.flat_map(|f| if let RuleKind::Function { to, .. } = f {
to
} else {
&v
}) { #>
<#= p.name.to_snake_case() #>,
<# }
for p in event.rules.iter() {
if let RuleKind::Map { from, to, op } = p {
if *op != RuleOp::Update {
panic!("Cannot add or remove when adding a new struct");
}
let transform_func = if to.is_set() {
// Convert to set
".iter().cloned().collect()"
} else if !to.get_type()?.is_primitive() {
".clone()"
} else {
""
};
// to is optional, but from not
let from_opt = from.is_opt(&event.msg); #>
<#= to.name.to_snake_case() #>: <#
if to.opt && !from_opt {
#>Some(m.<#= from.get_rust_name() #><#= transform_func #>),
<# } else {
#>m.<#= from.get_rust_name() #><#= transform_func #>,
<# }
}
} #>
};
<#
// TODO Previous function end
let function_name = format!("add_{}", book_name.to_snake_case());
let ids = event.get_id_args("m"); #>
self.<#= function_name #>(<#= ids #>, r, &mut events)?;
<# create_event(_fmt, event, "Added", false)?;
} #>
<# } #>
}
<# } #>
_ => {
// Ignore unmentioned messages
return Ok((false, events));
}
}
Ok((true, events))
}
}
@@ -0,0 +1,55 @@
<#@ template cleanws="true" #>
impl Connection {
/// Get a property by its id.
pub fn get_property(&self, id: &PropertyId) -> Result<PropertyValueRef<'_>> {
Ok(match id {
<# for struc in &self.0.structs {
let mut ids = embrace(&get_ids(struc));
let mut ids2 = get_ids2(&self.0.structs, struc);
ids2 = format!("({})", ids2); #>
PropertyId::<#= struc.name #><#= ids #> => PropertyValueRef::<#= struc.name #>(self.get_<#= struc.name.to_snake_case() #><#= ids2 #>?),
<# } #>
<# for struc in self.0.structs.iter().filter(|s| !s.opt) {
for p in struc.get_properties(&self.0.structs) {
let type_s = p.get_inner_type_as_name()?;
let mut ids = get_ids(struc);
if p.modifier.is_some() {
if !ids.is_empty() {
ids.push_str(", ");
}
ids.push_str("m");
}
ids = embrace(&ids);
let mut ids2 = format!("({})", get_ids2(&self.0.structs, struc));
#>
PropertyId::<#= struc.name #><#= p.get_name() #><#= ids
#> => PropertyValueRef::<#= type_s #>(self.get_<#=
struc.name.to_snake_case() #><#= ids2 #>?.<#=
p.name.to_snake_case() #><#
if p.modifier.as_ref().map(|s| s == "map").unwrap_or(false) {
#>.get(*m)
.ok_or_else(|| Error::NotFound("<#= p.name #>", m.to_string()))?<#
} else if p.modifier.as_ref().map(|s| s == "array").unwrap_or(false) {
#>.iter()<#
if p.type_s != "str" { #>.cloned().find(|i| i == m)<#
} else { #>.find(|i| *i == m)<# } #>
.ok_or_else(|| Error::NotFound("<#= p.name #>", m.to_string()))?<#
} else if p.modifier.as_ref().map(|s| s == "set").unwrap_or(false) {
#>.get(m)<#
if p.type_s != "str" { #>.cloned()<# } #>
.ok_or_else(|| Error::NotFound("<#= p.name #>", m.to_string()))?<#
}
if p.opt && (p.type_s == "str" || p.type_s == "Uid") {
#>.as_ref().map(|r| r.as_ref())<#
} else if p.type_s == "str" || p.type_s == "Uid" || ["TalkPowerRequest", "EccKeyPubP256"].contains(&p.type_s.as_str()) {
#>.as_ref()<#
} #>),
<# }
} #>
})
}
}
@@ -0,0 +1,13 @@
use std::default::Default;
use t4rust_derive::Template;
use tsproto_structs::*;
#[derive(Template)]
#[TemplatePath = "build/BookDeclarations.tt"]
#[derive(Debug)]
pub struct BookDeclarations<'a>(pub &'a book::BookDeclarations);
impl Default for BookDeclarations<'static> {
fn default() -> Self { BookDeclarations(&tsproto_structs::book::DATA) }
}
@@ -0,0 +1,71 @@
use std::default::Default;
use std::ops::Deref;
use heck::*;
use t4rust_derive::Template;
use tsproto_structs::book_to_messages::*;
use tsproto_structs::messages::Field;
use tsproto_structs::*;
#[derive(Template)]
#[TemplatePath = "build/BookToMessages.tt"]
#[derive(Debug)]
pub struct BookToMessagesDeclarations<'a>(&'a book_to_messages::BookToMessagesDeclarations<'a>);
impl<'a> Deref for BookToMessagesDeclarations<'a> {
type Target = book_to_messages::BookToMessagesDeclarations<'a>;
fn deref(&self) -> &Self::Target { self.0 }
}
impl Default for BookToMessagesDeclarations<'static> {
fn default() -> Self { BookToMessagesDeclarations(&DATA) }
}
fn get_to_list(to: &[&Field]) -> String {
let mut res = String::new();
if to.len() > 1 {
res.push('(');
}
let mut first = true;
for t in to {
if !first {
res.push_str(", ");
} else {
first = false;
}
res.push_str(&t.get_rust_name());
}
if to.len() > 1 {
res.push(')');
}
res
}
/// The prefix is written before from, if from is a mapped argument
fn rule_has_to(r: &RuleKind, field: &Field) -> bool {
match r {
RuleKind::Map { to, .. } | RuleKind::ArgumentMap { to, .. } => to == &field,
RuleKind::ArgumentFunction { to, .. } | RuleKind::Function { to, .. } => {
to.contains(&field)
}
}
}
/// Finds a matching rule in either the event ids or the given rule.
fn find_rule<'a>(
e: &'a Event, r: Option<&'a RuleKind>, field: &Field,
) -> (bool, Option<&'a RuleKind<'a>>) {
if let Some(r) = r {
if rule_has_to(r, field) {
return (true, Some(r));
}
}
for r in &e.ids {
if rule_has_to(r, field) {
return (false, Some(r));
}
}
(false, None)
}
@@ -0,0 +1,52 @@
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod book_parser;
mod book_to_messages_parser;
mod events;
mod message_parser;
mod messages_to_book_parser;
mod properties;
use crate::book_parser::BookDeclarations;
use crate::book_to_messages_parser::BookToMessagesDeclarations;
use crate::events::EventDeclarations;
use crate::message_parser::MessageDeclarations;
use crate::messages_to_book_parser::MessagesToBookDeclarations;
use crate::properties::Properties;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
// Book declarations
let path = Path::new(&out_dir);
let mut structs = File::create(path.join("structs.rs")).unwrap();
write!(&mut structs, "{}", BookDeclarations::default()).unwrap();
// Messages to book
let mut structs = File::create(path.join("m2bdecls.rs")).unwrap();
write!(&mut structs, "{}", MessagesToBookDeclarations::default()).unwrap();
// Write messages
let decls = MessageDeclarations::s2c();
let mut structs = File::create(path.join("s2c_messages.rs")).unwrap();
write!(&mut structs, "{}", MessageDeclarations(&decls)).unwrap();
let decls = MessageDeclarations::c2s();
let mut structs = File::create(path.join("c2s_messages.rs")).unwrap();
write!(&mut structs, "{}", MessageDeclarations(&decls)).unwrap();
// Book to messages
let mut structs = File::create(path.join("b2mdecls.rs")).unwrap();
write!(&mut structs, "{}", BookToMessagesDeclarations::default()).unwrap();
// Events
let mut structs = File::create(path.join("events.rs")).unwrap();
write!(&mut structs, "{}", EventDeclarations::default()).unwrap();
// Properties
let mut structs = File::create(path.join("properties.rs")).unwrap();
write!(&mut structs, "{}", Properties::default()).unwrap();
}
@@ -0,0 +1,20 @@
use std::collections::HashSet;
use std::default::Default;
use std::ops::Deref;
use t4rust_derive::Template;
use tsproto_structs::book::*;
#[derive(Template)]
#[TemplatePath = "build/Events.tt"]
#[derive(Debug)]
pub struct EventDeclarations<'a>(&'a BookDeclarations);
impl<'a> Deref for EventDeclarations<'a> {
type Target = BookDeclarations;
fn deref(&self) -> &Self::Target { self.0 }
}
impl Default for EventDeclarations<'static> {
fn default() -> Self { EventDeclarations(&DATA) }
}
@@ -0,0 +1,299 @@
use std::default::Default;
use itertools::Itertools;
use t4rust_derive::Template;
use tsproto_structs::messages::*;
use tsproto_structs::{indent, messages, InnerRustType, RustType};
#[derive(Template)]
#[TemplatePath = "build/MessageDeclarations.tt"]
#[derive(Debug, Clone)]
pub struct MessageDeclarations<'a>(pub &'a messages::MessageDeclarations);
impl MessageDeclarations<'static> {
pub fn s2c() -> messages::MessageDeclarations {
let mut res = DATA.clone();
res.msg_group.retain(|g| g.default.s2c);
res
}
pub fn c2s() -> messages::MessageDeclarations {
let mut res = DATA.clone();
res.msg_group.retain(|g| g.default.c2s);
res
}
}
impl Default for MessageDeclarations<'static> {
fn default() -> Self { MessageDeclarations(&DATA) }
}
pub fn generate_deserializer(field: &Field) -> String {
let rust_type = field.get_type("").unwrap();
if let InnerRustType::Vec(inner) = rust_type.inner {
vector_value_deserializer(field, (*inner).into())
} else {
single_value_deserializer(field, &rust_type.to_string())
}
}
pub fn single_value_deserializer(field: &Field, rust_type: &str) -> String {
let res = match rust_type {
"i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" => format!(
"val.parse().map_err(|e| ParseError::ParseInt {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?",
field.pretty
),
"f32" | "f64" => format!(
"val.parse().map_err(|e| ParseError::ParseFloat {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?",
field.pretty
),
"bool" => format!(
"match val {{ \"0\" => false, \"1\" => true, _ => return Err(ParseError::ParseBool {{
arg: \"{}\",
value: val.to_string(),
}}), }}",
field.pretty
),
"UidBuf" => "UidBuf(if let Ok(uid) = BASE64_STANDARD.decode(val) { uid } else { \
val.as_bytes().to_vec() })"
.into(),
"&str" => "val".into(),
"String" => "val.to_string()".into(),
"IconId" => format!(
"IconId(if val.starts_with('-') {{
val.parse::<i32>().map(|i| i as u32)
}} else {{
val.parse::<u64>().map(|i| i as u32)
}}.map_err(|e| ParseError::ParseInt {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?)",
field.pretty
),
"ClientId" | "ClientDbId" | "ChannelId" | "ServerGroupId" | "ChannelGroupId" => format!(
"{}(val.parse().map_err(|e| ParseError::ParseInt {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?)",
rust_type, field.pretty
),
"IpAddr" | "SocketAddr" => format!(
"val.parse().map_err(|e| ParseError::ParseAddr {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?",
field.pretty
),
"ClientType" => format!(
"match val {{
\"0\" => ClientType::Normal,
\"1\" => ClientType::Query {{ admin: false }},
_ => return Err(ParseError::InvalidValue {{
arg: \"{}\",
value: val.to_string(),
}}),
}}",
field.pretty
),
"TextMessageTargetMode"
| "HostMessageMode"
| "HostBannerMode"
| "LicenseType"
| "LogLevel"
| "Codec"
| "CodecEncryptionMode"
| "Reason"
| "GroupNamingMode"
| "GroupType"
| "Permission"
| "PermissionType"
| "TokenType"
| "PluginTargetMode"
| "Error" => format!(
"{}::from_u32(val.parse().map_err(|e| ParseError::ParseInt {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?).ok_or(ParseError::InvalidValue {{
arg: \"{1}\",
value: val.to_string(),
}})?",
rust_type, field.pretty
),
"ChannelPermissionHint" | "ClientPermissionHint" => format!(
"{}::from_bits(val.parse().map_err(|e| ParseError::ParseInt {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?).ok_or(ParseError::InvalidValue {{
arg: \"{1}\",
value: val.to_string(),
}})?",
rust_type, field.pretty
),
"Duration" => {
if field.type_s == "DurationSeconds" {
format!(
"let val = val.parse::<i64>().map_err(|e| ParseError::ParseInt {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?;
if val.checked_mul(1000).is_some() {{ Duration::seconds(val) }}
else {{ return Err(ParseError::InvalidValue {{
arg: \"{0}\",
value: val.to_string(),
}}); }}",
field.pretty
)
} else if field.type_s == "DurationMilliseconds" {
format!(
"Duration::milliseconds(val.parse::<i64>().map_err(|e| ParseError::ParseInt \
{{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?)",
field.pretty
)
} else if field.type_s == "DurationMillisecondsFloat" {
format!(
"Duration::microseconds((1000.0 * val.parse::<f32>().map_err(|e| \
ParseError::ParseFloat {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?) as i64)",
field.pretty
)
} else {
panic!("Unknown original time type {} found.", field.type_s);
}
}
"OffsetDateTime" => format!(
"OffsetDateTime::from_unix_timestamp(
val.parse().map_err(|e| ParseError::ParseInt {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?).map_err(|e| ParseError::ParseDate {{
arg: \"{}\",
value: val.to_string(),
source: e,
}})?",
field.pretty, field.pretty
),
_ => panic!("Unknown type '{}' when trying to deserialize {:?}", rust_type, field),
};
if res.contains('\n') { indent(&res, 2) } else { res }
}
pub fn vector_value_deserializer(field: &Field, rust_type: RustType) -> String {
format!(
"val.split(',')
.filter_map(|val| {{
let val = val.trim();
if val.is_empty() {{
None
}} else {{
Some(val)
}}
}}).map(|val| {{
let val = val.trim();
Ok({})
}}).collect::<Result<Vec<{}>>>()?",
single_value_deserializer(field, &rust_type.to_string()),
rust_type,
)
}
pub fn generate_serializer(field: &Field, name: &str) -> String {
let rust_type = field.get_type("").unwrap();
if let InnerRustType::Vec(inner) = rust_type.inner {
let inner_type: RustType = (*inner).into();
vector_value_serializer(field, &inner_type.to_string(), name)
} else {
single_value_serializer(field, &rust_type.to_string(), name, false)
}
}
pub fn single_value_serializer(field: &Field, rust_type: &str, name: &str, is_ref: bool) -> String {
let ref_amp = if is_ref { "" } else { "&" };
let ref_star = if is_ref { "*" } else { "" };
match rust_type {
"i8" | "u8" | "i16" | "u16" | "i32" | "u32" | "i64" | "u64" | "f32" | "f64" | "String"
| "IpAddr" | "SocketAddr" => format!("{}{}", ref_amp, name),
"bool" => format!("if {}{} {{ &\"1\" }} else {{ &\"0\" }}", ref_star, name),
"&str" => name.to_string(),
"UidBuf" | "&Uid" => format!(
"&if {0}.is_server_admin() {{ Cow::Borrowed(\"ServerAdmin\") }}
else {{ Cow::<str>::Owned(BASE64_STANDARD.encode(&{0}.0)) }}",
name,
),
"ClientId" | "ClientDbId" | "ChannelId" | "ServerGroupId" | "ChannelGroupId" | "IconId" => {
format!("&{}.0", name)
}
"ClientType" => format!(
"match {} {{
ClientType::Normal => &\"0\",
ClientType::Query {{ .. }} => &\"1\",
}}",
name
),
"TextMessageTargetMode"
| "HostMessageMode"
| "HostBannerMode"
| "LicenseType"
| "LogLevel"
| "Codec"
| "CodecEncryptionMode"
| "Reason"
| "GroupNamingMode"
| "GroupType"
| "Permission"
| "PermissionType"
| "TokenType"
| "PluginTargetMode"
| "Error" => format!("&{}.to_u32().unwrap()", name),
"ChannelPermissionHint" | "ClientPermissionHint" => format!("&{}.bits()", name),
"Duration" => {
if field.type_s == "DurationSeconds" {
format!("&{}.whole_seconds()", name)
} else if field.type_s == "DurationMilliseconds" {
format!("&{}.whole_milliseconds()", name)
} else if field.type_s == "DurationMillisecondsFloat" {
format!("&({}.whole_microseconds() as f32 / 1000.0)", name)
} else {
panic!("Unknown original time type {} found.", field.type_s);
}
}
"OffsetDateTime" => format!("&{}.unix_timestamp()", name),
_ => panic!("Unknown type '{}'", rust_type),
}
}
pub fn vector_value_serializer(field: &Field, inner_type: &str, name: &str) -> String {
// TODO Vector serialization creates an intermediate string which is not necessary
format!(
"&{{ let mut s = String::new();
for val in {}.as_ref() {{
if !s.is_empty() {{ s += \",\" }}
write!(&mut s, \"{{}}\", {}).unwrap();
}}
s
}}",
name,
single_value_serializer(field, inner_type, "val", true)
)
}
@@ -0,0 +1,28 @@
use std::collections::HashMap;
use std::default::Default;
use std::ops::Deref;
use heck::*;
use t4rust_derive::Template;
use tsproto_structs::book::{PropId, Property};
use tsproto_structs::messages::Field;
use tsproto_structs::messages_to_book::*;
use tsproto_structs::*;
#[derive(Template)]
#[TemplatePath = "build/MessagesToBook.tt"]
#[derive(Debug)]
pub struct MessagesToBookDeclarations<'a>(&'a messages_to_book::MessagesToBookDeclarations<'a>);
impl<'a> Deref for MessagesToBookDeclarations<'a> {
type Target = messages_to_book::MessagesToBookDeclarations<'a>;
fn deref(&self) -> &Self::Target { self.0 }
}
impl Default for MessagesToBookDeclarations<'static> {
fn default() -> Self { MessagesToBookDeclarations(&DATA) }
}
fn get_property(p: &Property, name: &str) -> String {
format!("PropertyValue::{}({})", p.get_inner_type_as_name().unwrap(), name)
}
@@ -0,0 +1,43 @@
//! Access properties of a connection with the property structs from events.
use std::default::Default;
use std::fmt::Write;
use heck::*;
use t4rust_derive::Template;
use tsproto_structs::book::*;
use tsproto_structs::embrace;
#[derive(Template)]
#[TemplatePath = "build/Properties.tt"]
#[derive(Debug)]
pub struct Properties<'a>(&'a BookDeclarations);
impl Default for Properties<'static> {
fn default() -> Self { Properties(&DATA) }
}
fn get_ids(struc: &Struct) -> String {
let mut res = String::new();
for i in 0..struc.id.len() {
if !res.is_empty() {
res.push_str(", ");
}
let _ = write!(res, "s{}", i);
}
res
}
fn get_ids2(structs: &[Struct], struc: &Struct) -> String {
let mut res = String::new();
for (i, id) in struc.id.iter().enumerate() {
let p = id.find_property(structs);
if !res.is_empty() {
res.push_str(", ");
}
if p.type_s != "str" {
res.push('*');
}
let _ = write!(res, "s{}", i);
}
res
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,79 @@
use serde::{Deserialize, Serialize};
use time::{Duration, OffsetDateTime};
use tsproto_types::crypto::EccKeyPubP256;
use crate::data::{
Channel, ChannelGroup, Client, Connection, ConnectionClientData, ConnectionServerData,
OptionalChannelData, OptionalClientData, OptionalServerData, Server, ServerGroup,
};
use crate::*;
include!(concat!(env!("OUT_DIR"), "/events.rs"));
/// Additional data for some events.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ExtraInfo {
/// Set for e.g. new clients to distinguish if they joined or are made available because we
/// subscribed to a channel.
pub reason: Option<Reason>,
}
/// An event gets fired when something in the data structure of a connection
/// changes or something happens like we receive a text message or get poked.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub enum Event {
/// The object with this id was added.
///
/// You can find the new object inside the connection data structure.
///
/// Like a client gets assigned a new server group or a new client joins the
/// server.
PropertyAdded { id: PropertyId, invoker: Option<Invoker>, extra: ExtraInfo },
/// The attribute with this id has changed.
///
/// The second tuple item holds the old value of the changed attribute.
///
/// E.g. a client changes its nickname or switches to another channel.
PropertyChanged {
id: PropertyId,
old: PropertyValue,
invoker: Option<Invoker>,
extra: ExtraInfo,
},
/// The object with this id was removed.
///
/// The object is not accessible anymore in the connection data structure,
/// but the second tuple item holds the removed object.
///
/// This happens when a client leaves the server (including our own client)
/// or a channel is removed.
PropertyRemoved {
id: PropertyId,
old: PropertyValue,
invoker: Option<Invoker>,
extra: ExtraInfo,
},
Message {
/// Where this message was sent to, in the server or channel chat or
/// directly to client.
///
/// This is our own client for private messages from others.
target: MessageTarget,
/// The user who wrote the message.
invoker: Invoker,
/// The content of the message.
message: String,
},
}
impl Event {
pub fn get_invoker(&self) -> Option<&Invoker> {
match self {
Event::PropertyAdded { invoker, .. }
| Event::PropertyChanged { invoker, .. }
| Event::PropertyRemoved { invoker, .. } => invoker.as_ref(),
Event::Message { invoker, .. } => Some(invoker),
}
}
}
@@ -0,0 +1,246 @@
//! `ts-bookkeeping` contains structs to store the state of a TeamSpeak server, with its clients and
//! channels.
//!
//! The crate can be used to keep track of the state on a server by processing all incoming
//! commands, which is why it is called “bookkeeping”. It also contains generated structs for all
//! TeamSpeak commands.
//!
//! Incoming commands can be applied to the state and generate [`events`]. The main struct is
//! [`data::Connection`].
//!
//! The structs have methods to create packets for various actions. The generated packets can be
//! sent to a server.
use std::fmt;
use std::net::{IpAddr, SocketAddr};
use serde::{Deserialize, Serialize};
use thiserror::Error;
pub mod data;
pub mod events;
pub mod messages;
// Reexports
pub use tsproto_types::errors::Error as TsError;
pub use tsproto_types::versions::Version;
pub use tsproto_types::{
ChannelGroupId, ChannelId, ChannelPermissionHint, ChannelType, ClientDbId, ClientId,
ClientPermissionHint, ClientType, Codec, CodecEncryptionMode, GroupNamingMode, GroupType,
HostBannerMode, HostMessageMode, IconId, Invoker, InvokerRef, LicenseType, LogLevel,
MaxClients, Permission, PermissionType, PluginTargetMode, Reason, ServerGroupId,
TalkPowerRequest, TextMessageTargetMode, TokenType, Uid, UidBuf,
};
type Result<T> = std::result::Result<T, Error>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("Target client id missing for a client text message")]
MessageWithoutTargetClientId,
#[error("Unknown TextMessageTargetMode")]
UnknownTextMessageTargetMode,
#[error("{0} {1} not found")]
NotFound(&'static str, String),
#[error("{0} should be removed but does not exist")]
RemoveNotFound(&'static str),
#[error("Failed to parse connection ip: {0}")]
InvalidConnectionIp(#[source] std::net::AddrParseError),
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ServerAddress {
SocketAddr(SocketAddr),
Other(String),
}
impl From<SocketAddr> for ServerAddress {
fn from(addr: SocketAddr) -> Self { ServerAddress::SocketAddr(addr) }
}
impl From<String> for ServerAddress {
fn from(addr: String) -> Self { ServerAddress::Other(addr) }
}
impl<'a> From<&'a str> for ServerAddress {
fn from(addr: &'a str) -> Self { ServerAddress::Other(addr.to_string()) }
}
impl fmt::Display for ServerAddress {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ServerAddress::SocketAddr(a) => fmt::Display::fmt(a, f),
ServerAddress::Other(a) => fmt::Display::fmt(a, f),
}
}
}
/// All possible targets to send messages.
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum MessageTarget {
Server,
Channel,
Client(ClientId),
Poke(ClientId),
}
/// The configuration to create a new connection.
#[derive(Deserialize, Serialize)]
pub struct ConnectOptions {
address: ServerAddress,
local_address: Option<SocketAddr>,
name: String,
version: Version,
log_commands: bool,
log_packets: bool,
log_udp_packets: bool,
}
impl ConnectOptions {
/// Start creating the configuration of a new connection.
///
/// # Arguments
/// The address of the server has to be supplied. The address can be a
/// [`SocketAddr`](std::net::SocketAddr), a string or directly a [`ServerAddress`]. A string
/// will automatically be resolved from all formats supported by TeamSpeak.
/// For details, see [`resolver::resolve`].
#[inline]
pub fn new<A: Into<ServerAddress>>(address: A) -> Self {
Self {
address: address.into(),
local_address: None,
name: String::from("TeamSpeakUser"),
version: Version::Linux_3_2_1,
log_commands: false,
log_packets: false,
log_udp_packets: false,
}
}
/// The address for the socket of our client
///
/// # Default
/// The default is `0.0.0:0` when connecting to an IPv4 address and `[::]:0`
/// when connecting to an IPv6 address.
#[inline]
pub fn local_address(mut self, local_address: SocketAddr) -> Self {
self.local_address = Some(local_address);
self
}
/// The name of the user.
///
/// # Default
/// `TeamSpeakUser`
#[inline]
pub fn name(mut self, name: String) -> Self {
self.name = name;
self
}
/// The displayed version of the client.
///
/// # Default
/// `3.2.1 on Linux`
#[inline]
pub fn version(mut self, version: Version) -> Self {
self.version = version;
self
}
/// If the content of all commands should be written to the logger.
///
/// # Default
/// `false`
#[inline]
pub fn log_commands(mut self, log_commands: bool) -> Self {
self.log_commands = log_commands;
self
}
/// If the content of all packets in high-level form should be written to
/// the logger.
///
/// # Default
/// `false`
#[inline]
pub fn log_packets(mut self, log_packets: bool) -> Self {
self.log_packets = log_packets;
self
}
/// If the content of all udp packets in byte-array form should be written
/// to the logger.
///
/// # Default
/// `false`
#[inline]
pub fn log_udp_packets(mut self, log_udp_packets: bool) -> Self {
self.log_udp_packets = log_udp_packets;
self
}
}
impl fmt::Debug for ConnectOptions {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Error if attributes are added
let ConnectOptions {
address,
local_address,
name,
version,
log_commands,
log_packets,
log_udp_packets,
} = self;
write!(
f,
"ConnectOptions {{ address: {:?}, local_address: {:?}, name: {}, version: {}, \
log_commands: {}, log_packets: {}, log_udp_packets: {} }}",
address, local_address, name, version, log_commands, log_packets, log_udp_packets,
)?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DisconnectOptions {
reason: Option<Reason>,
message: Option<String>,
}
impl Default for DisconnectOptions {
#[inline]
fn default() -> Self { Self { reason: None, message: None } }
}
impl DisconnectOptions {
#[inline]
pub fn new() -> Self { Self::default() }
/// Set the reason for leaving.
///
/// # Default
///
/// None
#[inline]
pub fn reason(mut self, reason: Reason) -> Self {
self.reason = Some(reason);
self
}
/// Set the leave message.
///
/// You also have to set the reason, otherwise the message will not be
/// displayed.
///
/// # Default
///
/// None
#[inline]
pub fn message<S: Into<String>>(mut self, message: S) -> Self {
self.message = Some(message.into());
self
}
}
@@ -0,0 +1,80 @@
use std::net::IpAddr;
use thiserror::Error;
use time::{Duration, OffsetDateTime};
use tsproto_packets::commands::CommandParser;
use tsproto_packets::packets::{Direction, InHeader, OutCommand, PacketType};
use tsproto_types::errors::Error;
use crate::*;
type Result<T> = std::result::Result<T, ParseError>;
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ParseError {
#[error(transparent)]
Base64(#[from] base64::DecodeError),
#[error("Parameter {arg} not found in {name}")]
ParameterNotFound { arg: &'static str, name: &'static str },
#[error("Parameter {arg} not found in {name}")]
ParameterNotFound2 { arg: String, name: String },
#[error("Command {0} is unknown")]
UnknownCommand(String),
#[error(transparent)]
StringParse(#[from] std::str::Utf8Error),
#[error(transparent)]
TsProto(#[from] tsproto_packets::Error),
/// Gets thrown when parsing a specific command with the wrong input.
#[error("Command {0} is wrong")]
WrongCommand(String),
#[error("Wrong newprotocol flag ({0})")]
WrongNewprotocol(bool),
#[error("Wrong packet type {0:?}")]
WrongPacketType(PacketType),
#[error("Wrong direction {0:?}")]
WrongDirection(Direction),
#[error("Cannot parse \"{value}\" as int for parameter {arg} ({source})")]
ParseInt { arg: &'static str, value: String, source: std::num::ParseIntError },
#[error("Cannot parse \"{value}\" as SocketAddr for parameter {arg} ({source})")]
ParseAddr { arg: &'static str, value: String, source: std::net::AddrParseError },
#[error("Cannot parse \"{value}\" as float for parameter {arg} ({source})")]
ParseFloat { arg: &'static str, value: String, source: std::num::ParseFloatError },
#[error("Cannot parse \"{value}\" as bool for parameter {arg}")]
ParseBool { arg: &'static str, value: String },
#[error("Cannot parse \"{value}\" as SocketAddr for parameter {arg} ({source})")]
ParseUid { arg: &'static str, value: String, source: base64::DecodeError },
#[error("Cannot parse \"{value}\" as DateTimeOffset for parameter {arg} ({source})")]
ParseDate { arg: &'static str, value: String, source: time::error::ComponentRange },
#[error("Invalid value \"{value}\" for parameter {arg}")]
InvalidValue { arg: &'static str, value: String },
}
pub trait InMessageTrait {
fn new(header: &InHeader, args: CommandParser) -> Result<Self>
where Self: Sized;
}
pub trait OutMessageTrait {
fn to_packet(self) -> OutCommand;
}
pub trait OutMessageWithReturnTrait {
fn to_packet(self, return_code: Option<&str>) -> OutCommand;
}
impl OutMessageTrait for OutCommand {
fn to_packet(self) -> OutCommand { self }
}
pub mod s2c {
#![allow(mismatched_lifetime_syntaxes)]
use super::*;
include!(concat!(env!("OUT_DIR"), "/s2c_messages.rs"));
}
pub mod c2s {
#![allow(mismatched_lifetime_syntaxes)]
use super::*;
include!(concat!(env!("OUT_DIR"), "/c2s_messages.rs"));
}