4 use std
::net
::{SocketAddr
, SocketAddrV4
, ToSocketAddrs
};
6 use serde
::{Serialize
, Serializer
};
8 use crate::HLQueryError
::{IOError
,A2SError
};
11 #[command(name = "HLQuery")]
12 #[command(author = "MegaBrutal")]
14 #[command(about = "Query Half-Life servers", long_about = None)]
16 /// Print output in JSON format
20 /// Pretty-print JSON or Rust objects
24 addresses
: Vec
<String
>
28 #[derive(Debug, Serialize)]
29 struct HLQueryResult
{
30 address
: SocketAddrV4
,
31 info
: Result
<a2s
::info
::Info
, HLQueryError
>,
32 rules
: Result
<Vec
<a2s
::rules
::Rule
>, HLQueryError
>,
33 players
: Result
<Vec
<a2s
::players
::Player
>, HLQueryError
>
37 fn new(a2s_client
: &A2SClient
, server
: SocketAddrV4
) -> Self {
40 info
: a2s_client
.in
fo
(server
).map_err(From
::from
),
41 rules
: a2s_client
.rules(server
).map_err(From
::from
),
42 players
: a2s_client
.players(server
).map_err(From
::from
)
47 #[derive(Debug, Serialize)]
50 result
: Result
<Vec
<HLQueryResult
>, HLQueryError
>
54 fn new
<S
: Into
<String
>>(input
: S
, result
: Result
<Vec
<HLQueryResult
>, HLQueryError
>) -> Self {
55 let input
= input
.into
();
56 Self { input
, result
}
62 IOError(std
::io
::Error
),
63 A2SError(a2s
::errors
::Error
)
66 impl Display
for HLQueryError
{
67 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
69 IOError(e
) => write
!(f
, "{:?}", e
),
70 A2SError(e
) => write
!(f
, "{:?}", e
)
75 impl Error
for HLQueryError
{}
77 impl Serialize
for HLQueryError
{
78 fn serialize
<S
>(&self, serializer
: S
) -> Result
<S
::Ok
, S
::Error
>
82 serializer
.serialize_str(&format
!("{self}"))
86 impl From
<std
::io
::Error
> for HLQueryError
{
87 fn from(e
: std
::io
::Error
) -> Self {
92 impl From
<a2s
::errors
::Error
> for HLQueryError
{
93 fn from(e
: a2s
::errors
::Error
) -> Self {
100 let cli
= Cli
::parse();
102 let client
= A2SClient
::new().unwrap
();
103 let query_results
: Vec
<HLQuery
> = cli
.addresses
.iter
()
105 let addresses
= arg
.to_socket_addrs();
108 .map(|lookup_result
| match lookup_result
{
109 (input
, Ok(iter_addr
)) => {
110 (input
, Ok(iter_addr
.filter
_map
(|sa
| match sa
{
111 SocketAddr
::V4(sa4
) => Some(sa4
),
115 (input
, Err(e
)) => (input
, Err(HLQueryError
::IOError(e
)))
117 .map(|(input
, address_group
)| HLQuery
::new(input
, address_group
.map(
118 |addresses
| addresses
.map(|addr
| HLQueryResult
::new(&client
, addr
)).collect())))
123 println
!("{}", serde_json
::to_string_pretty(&query_results
).unwrap
());
126 println
!("{}", serde_json
::to_string(&query_results
).unwrap
());
131 println
!("{:#?}", query_results
);
134 println
!("{:?}", query_results
);