msq 0.2.1

Rust library implementation of the legacy Master Server Query Protocol
Documentation
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
//! Filter builder - Construct your filter to filter out server results
//!
//! **NOTE**: Some filters may or may not work as expected depending on
//! appid/games you try it on. The filter builder methods and string
//! construction generally follows close to the reference listed out
//! in the Valve developer wiki.
//!
//! Reference: <https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol#Filter>
//!
//! # Quick Start
//!
//! ```
//! use msq::Filter;
//! let filter = Filter::new()
//!     .appid(240)
//!     .full(false)
//!     .map("de_dust2");
//! ```
//!
#[derive(Clone)]
enum FilterPropVal {
    Special(Vec<FilterProp>),
    Boolean(bool),
    Str(String),
    Uint32(u32),
    Tags(Vec<String>),
}

impl FilterPropVal {
    fn from_special(spec: &Vec<FilterProp>) -> FilterPropVal {
        Self::Special(spec.clone())
    }

    fn from_tags(tags: &Vec<&str>) -> FilterPropVal {
        let mut fpvtags: Vec<String> = vec![];

        for tag in tags {
            fpvtags.push(String::from(*tag));
        }

        Self::Tags(fpvtags)
    }

    fn as_str(&self) -> String {
        match &*self {
            Self::Special(filterprops) => {
                let mut sstr = String::from("");

                // Start with values count
                sstr += &format!("{}", filterprops.len());

                // Populate the string with inner values
                for fp in filterprops {
                    sstr += &fp.as_str();
                }

                sstr
            }
            Self::Boolean(b) => format!("{}", *b as i32),
            Self::Str(s) => String::from(s),
            Self::Uint32(i) => format!("{}", i),
            Self::Tags(tags) => {
                let mut tags_str = String::from("");
                for tag in tags {
                    tags_str += &tag;
                    tags_str += ",";
                }
                tags_str.pop();
                tags_str
            }
        }
    }
}

#[derive(Clone)]
struct FilterProp {
    pub name: String,
    pub value: FilterPropVal,
}

impl FilterProp {
    fn new(name: &str, value: FilterPropVal) -> FilterProp {
        FilterProp {
            name: String::from(name),
            value: value,
        }
    }

    fn as_str(&self) -> String {
        format!("\\{}\\{}", self.name, self.value.as_str())
    }
}

/// Filter builder - Construct your filter to filter out server results
///
/// * Intended to be used with: [`MSQClient`](crate::MSQClient) and
/// [`MSQClientBlock`](crate::MSQClientBlock)
/// * **NOTE**: Some filters may or may not work as expected depending on
/// appid/games you try it on. The filter builder methods and string
/// construction generally follows close to the reference listed out
/// in the Valve developer wiki.
/// * Reference: <https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol#Filter>
///
/// # Quick Start
/// ```rust
/// use msq::Filter;
///
/// let filter = Filter::new()      // Create a Filter builder
///         .appid(240)             // appid of 240 (CS:S)
///         .nand()                 // Start of NAND special filter
///             .map("de_dust2")        // Map is de_dust2
///             .empty(true)            // Server is empty
///         .end()                  // End of NAND special filter
///         .gametype(&vec!["friendlyfire", "alltalk"]);
/// ```
///
pub struct Filter {
    filter_lst: Vec<FilterProp>,
    in_special: bool,
    spec_vec: Vec<FilterProp>,
    special_name: String,
}

impl Filter {
    /// Returns a string representing the filters
    #[deprecated(since = "0.2.0", note = "Replaced with as_string (name change)")]
    pub fn as_str(&self) -> String {
        self.as_string()
    }

    /// Returns a string representing the filters
    pub fn as_string(&self) -> String {
        let mut sstr = String::from("");

        for fp in &self.filter_lst {
            sstr += &fp.as_str();
        }

        sstr
    }

    /// Returns a new Filter struct, used for string builder
    ///
    /// # Examples
    /// ```
    /// // Filter
    /// use msq::Filter;
    /// let filter = Filter::new()
    ///     .appid(240)
    ///     .full(false)
    ///     .map("de_dust2");
    /// ```
    pub fn new() -> Filter {
        Filter {
            filter_lst: vec![],
            in_special: false,
            spec_vec: vec![],
            special_name: String::from(""),
        }
    }

    fn push(mut self, name: &str, value: FilterPropVal) -> Filter {
        if self.in_special {
            self.spec_vec.push(FilterProp::new(name, value));
        } else {
            self.filter_lst.push(FilterProp::new(name, value));
        }
        self
    }

    // Generic filter: Boolean
    fn boolean(self, name: &str, switch: bool) -> Filter {
        self.push(name, FilterPropVal::Boolean(switch))
    }

    // Generic filter: String
    fn string(self, name: &str, param: &str) -> Filter {
        self.push(name, FilterPropVal::Str(String::from(param)))
    }

    // Generic filter: Unsigned integer of 32 bits
    fn uint32(self, name: &str, num: u32) -> Filter {
        self.push(name, FilterPropVal::Uint32(num))
    }

    // Generic filter: Vector of strings
    fn vecstr(self, name: &str, tags: &Vec<&str>) -> Filter {
        if tags.len() > 0 {
            self.push(name, FilterPropVal::from_tags(tags))
        } else {
            self
        }
    }

    // Generic filter: Special (start)
    fn special_start(mut self, name: &str) -> Filter {
        self.spec_vec.clear();
        self.in_special = true;
        self.special_name = String::from(name);
        self
    }

    /// A special filter, specifies that servers matching any of the following \[x\] conditions should not be returned.
    /// See [`end`](#method.end) method to see examples on usage.
    pub fn nor(self) -> Filter {
        self.special_start("nor")
    }

    /// A special filter, specifies that servers matching all of the following \[x\] conditions should not be returned.
    /// See [`end`](#method.end) method to see examples on usage.
    pub fn nand(self) -> Filter {
        self.special_start("nand")
    }

    /// End the special filter (nor, nand)
    /// You must use this method after each nor/nand special filter method being used
    ///
    /// # Examples
    /// Using the NAND filter:
    /// ```
    /// use msq::Filter;
    /// let filter = Filter::new()
    ///     .appid(240)
    ///     .nand()     // Exclude servers that has de_dust2 AND is empty
    ///         .map("de_dust2")
    ///         .empty(true)
    ///     .end()      // Ends the NAND special filter
    ///     .gametype(&vec!["friendlyfire", "alltalk"]);
    /// ```
    ///
    /// Using the NOR filter:
    /// ```
    /// use msq::Filter;
    /// let filter = Filter::new()
    ///     .appid(240)
    ///     .nor()      // Exclude servers that has de_dust2 OR is empty
    ///         .map("de_dust2")
    ///         .empty(true)
    ///     .end()      // Ends the NOR special filter
    ///     .gametype(&vec!["friendlyfire", "alltalk"]);
    /// ```
    pub fn end(mut self) -> Filter {
        self.filter_lst.push(FilterProp::new(
            &self.special_name,
            FilterPropVal::from_special(&self.spec_vec),
        ));
        self.in_special = false;
        self.special_name = String::from("");
        self
    }

    /// Filters if the servers running dedicated
    ///
    /// # Arguments
    /// * `is_dedicated` - `true` = dedicated, `false` = not dedicated
    pub fn dedicated(self, is_dedicated: bool) -> Filter {
        self.boolean("dedicated", is_dedicated)
    }

    /// Servers using anti-cheat technology (VAC, but potentially others as well)
    ///
    /// # Arguments
    /// * `hasac` - `true` = secure, `false` = not secure
    pub fn secure(self, hasac: bool) -> Filter {
        self.boolean("secure", hasac)
    }

    /// Servers running the specified modification (ex: cstrike)
    ///
    /// # Arguments
    /// * `modg` - The modification name (ex: `cstrike`)
    pub fn gamedir(self, modg: &str) -> Filter {
        self.string("gamedir", modg)
    }

    /// Servers running the specified map (ex: cs_italy)
    ///
    /// # Arguments
    /// * `mapn` - The current map it's playing (ex: `cs_italy`)
    pub fn map(self, mapn: &str) -> Filter {
        self.string("map", mapn)
    }

    /// Servers running on a Linux platform
    ///
    /// # Arguments
    /// * `runslinux` - `true` = Runs on Linux, `false` = Does not runs on Linux
    pub fn linux(self, runslinux: bool) -> Filter {
        self.boolean("linux", runslinux)
    }

    /// Servers that are password protected
    ///
    /// # Arguments
    /// * `protected` - `true` = Password protected, `false` = Not password protected
    pub fn password(self, protected: bool) -> Filter {
        self.boolean("password", protected)
    }

    /// Servers that are full
    ///
    /// # Arguments
    /// * `is_full` - `true` = Server's full, `false` = Server's not full
    pub fn full(self, is_full: bool) -> Filter {
        self.boolean("full", !is_full)
    }

    /// Servers that are spectator proxies
    ///
    /// # Arguments
    /// * `specprox` - `true` = A spectator proxies, `false` = Not a spectator proxies
    pub fn proxy(self, specprox: bool) -> Filter {
        self.boolean("proxy", specprox)
    }

    /// Servers that are running game \[appid\]
    ///
    /// # Arguments
    /// * `appid` - The appid of the server: (EX: `240` (for CS:S))
    pub fn appid(self, appid: u32) -> Filter {
        self.uint32("appid", appid)
    }

    /// Servers that are NOT running game \[appid\]
    ///
    /// # Arguments
    /// * `appid` - The appid of the server: (EX: `240` (for CS:S))
    pub fn napp(self, appid: u32) -> Filter {
        self.uint32("napp", appid)
    }

    /// Servers that are empty
    ///
    /// # Arguments
    /// * `is_empty` - `true` = Empty, `false` = Not empty
    pub fn empty(self, is_empty: bool) -> Filter {
        if is_empty {
            self.boolean("noplayers", true)
        } else {
            self.boolean("empty", true)
        }
    }

    /// Servers that are whitelisted
    ///
    /// # Arguments
    /// * `white` - `true` = Whitelisted, `false` = Not whitelisted
    pub fn whitelisted(self, white: bool) -> Filter {
        self.boolean("white", white)
    }

    /// Servers with all of the given tag(s) in sv_tags
    ///
    /// # Arguments
    /// * `tags` - A vector of strings which represents a tag from sv_tags
    ///
    /// # Example
    /// ```
    /// use msq::Filter;
    /// let filter = Filter::new()
    ///     .appid(240)
    ///     .gametype(&vec!["friendlyfire", "alltalk"]);
    /// ```
    ///
    /// If you put in an empty vector, it will return nothing
    pub fn gametype(self, tags: &Vec<&str>) -> Filter {
        self.vecstr("gametype", tags)
    }

    /// Servers with all of the given tag(s) in their 'hidden' tags (L4D2)
    ///
    /// # Arguments
    /// * `tags` - A vector of strings which represents a tag from sv_tags
    pub fn gamedata(self, tags: &Vec<&str>) -> Filter {
        self.vecstr("gamedata", tags)
    }

    /// Servers with any of the given tag(s) in their 'hidden' tags (L4D2)
    ///
    /// # Arguments
    /// * `tags` - A vector of strings which represents a tag from sv_tags
    pub fn gamedataor(self, tags: &Vec<&str>) -> Filter {
        self.vecstr("gamedataor", tags)
    }

    /// Servers with their hostname matching \[hostname\] (can use * as a wildcard)
    ///
    /// # Arguments
    /// * `hostname` - String of matching hostname (EX: `1.2.*`)
    pub fn name_match(self, hostname: &str) -> Filter {
        self.string("name_match", hostname)
    }

    /// Servers running version \[version\] (can use * as a wildcard)
    ///
    /// # Arguments
    /// * `ver` - String of matching version
    pub fn version_match(self, ver: &str) -> Filter {
        self.string("version_match", ver)
    }

    /// Return only one server for each unique IP address matched
    ///
    /// # Arguments
    /// * `one_server` - `true` = Return one server
    pub fn collapse_addr_hash(self, one_server: bool) -> Filter {
        self.boolean("collapse_addr_hash", one_server)
    }

    /// Return only servers on the specified IP address (port supported and optional)
    ///
    /// # Arguments
    /// * `ipaddr` - String of the IP address to match
    pub fn gameaddr(self, ipaddr: &str) -> Filter {
        self.string("gameaddr", ipaddr)
    }
}