sf-api 0.4.3

A simple API to send commands to the Shakes & Fidget servers and parse their responses into characters
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
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
use std::{
    fmt::{Debug, Display, Write},
    str::FromStr,
};

use chrono::{DateTime, Local};
use enum_map::{Enum, EnumArray, EnumMap};
use log::warn;
use num_traits::FromPrimitive;

use crate::{error::SFError, gamestate::ServerTime};

pub const HASH_CONST: &str = "ahHoj2woo1eeChiech6ohphoB7Aithoh";
pub const DEFAULT_CRYPTO_KEY: &str = "[_/$VV&*Qg&)r?~g";
pub const DEFAULT_CRYPTO_ID: &str = "0-00000000000000";
pub const DEFAULT_SESSION_ID: &str = "00000000000000000000000000000000";
pub const CRYPTO_IV: &str = "jXT#/vz]3]5X7Jl\\";

#[must_use]
pub fn sha1_hash(val: &str) -> String {
    use sha1::{Digest, Sha1};
    let mut hasher = Sha1::new();
    hasher.update(val.as_bytes());
    let hash = hasher.finalize();
    let mut result = String::with_capacity(hash.len() * 2);
    for byte in &hash {
        _ = write!(result, "{byte:02x}");
    }
    result
}

/// Converts a raw value into the appropriate type. If that is not possible,
/// a warning will be emitted and the given default returned. This is useful
/// for stuff, that should not crash everything, when there is a weird value and
/// the silent failure of `as T`, or `unwrap_or_default()` would yield worse
/// results and/or no warning
#[inline]
pub(crate) fn soft_into<B: Display + Copy, T: TryFrom<B>>(
    val: B,
    name: &str,
    default: T,
) -> T {
    val.try_into().unwrap_or_else(|_| {
        log::warn!("Invalid value for {name} in server response: {val}");
        default
    })
}

/// Tries to convert val to T. If that fails a warning is emitted and none is
/// returned
#[inline]
pub(crate) fn warning_try_into<B: Display + Copy, T: TryFrom<B>>(
    val: B,
    name: &str,
) -> Option<T> {
    val.try_into().ok().or_else(|| {
        log::warn!("Invalid value for {name} in server response: {val}");
        None
    })
}

/// Converts the value using the function. If that fails, a warning is emitted
/// and None is returned
#[inline]
pub(crate) fn warning_parse<T, F, V: Display + Copy>(
    val: V,
    name: &str,
    conv: F,
) -> Option<T>
where
    F: Fn(V) -> Option<T>,
{
    conv(val).or_else(|| {
        log::warn!("Invalid value for {name} in server response: {val}");
        None
    })
}

#[inline]
pub(crate) fn warning_from_str<T: FromStr>(val: &str, name: &str) -> Option<T> {
    val.parse().ok().or_else(|| {
        log::warn!("Invalid value for {name} in server response: {val}");
        None
    })
}

/// Converts a S&F string from the server to their original unescaped
/// representation
#[must_use]
pub fn from_sf_string(val: &str) -> String {
    let mut new = String::with_capacity(val.len());
    let mut is_escaped = false;
    for char in val.chars() {
        if char == '$' {
            is_escaped = true;
            continue;
        }
        let escaped_char = match char {
            x if !is_escaped => x,
            'b' => '\n',
            'c' => ':',
            'P' => '%',
            's' => '/',
            'p' => '|',
            '+' => '&',
            'q' => '"',
            'r' => '#',
            'C' => ',',
            'S' => ';',
            'd' => '$',
            x => {
                warn!("Unkown escape sequence: ${x}");
                x
            }
        };
        new.push(escaped_char);
        is_escaped = false;
    }
    new
}

/// Makes a user controlled string, like a new character description safe to use
/// in a request
#[must_use]
pub fn to_sf_string(val: &str) -> String {
    let mut new = String::with_capacity(val.len());
    for char in val.chars() {
        match char {
            '\n' => new.push_str("$b"),
            ':' => new.push_str("$c"),
            '%' => new.push_str("$P"),
            '/' => new.push_str("$s"),
            '|' => new.push_str("$p"),
            '&' => new.push_str("$+"),
            '"' => new.push_str("$q"),
            '#' => new.push_str("$r"),
            ',' => new.push_str("$C"),
            ';' => new.push_str("$S"),
            '$' => new.push_str("$d"),
            _ => new.push(char),
        }
    }
    new
}

pub(crate) fn parse_vec<B: Display + Copy + std::fmt::Debug, T, F>(
    data: &[B],
    name: &'static str,
    func: F,
) -> Result<Vec<T>, SFError>
where
    F: Fn(B) -> Option<T>,
{
    data.iter()
        .map(|a| {
            func(*a)
                .ok_or_else(|| SFError::ParsingError(name, format!("{data:?}")))
        })
        .collect()
}

fn raw_cget<T: Copy + std::fmt::Debug>(
    val: &[T],
    pos: usize,
    name: &'static str,
) -> Result<T, SFError> {
    val.get(pos)
        .copied()
        .ok_or_else(|| SFError::TooShortResponse {
            name,
            pos,
            array: format!("{val:?}"),
        })
}

pub(crate) trait CGet<T: Copy + std::fmt::Debug> {
    fn cget(&self, pos: usize, name: &'static str) -> Result<T, SFError>;
}

impl<T: Copy + std::fmt::Debug + Display> CGet<T> for [T] {
    fn cget(&self, pos: usize, name: &'static str) -> Result<T, SFError> {
        raw_cget(self, pos, name)
    }
}

#[allow(unused)]
pub(crate) trait CCGet<T: Copy + std::fmt::Debug + Display, I: TryFrom<T>> {
    fn csiget(
        &self,
        pos: usize,
        name: &'static str,
        def: I,
    ) -> Result<I, SFError>;
    fn csimget(
        &self,
        pos: usize,
        name: &'static str,
        def: I,
        fun: fn(T) -> T,
    ) -> Result<I, SFError>;
    fn cwiget(
        &self,
        pos: usize,
        name: &'static str,
    ) -> Result<Option<I>, SFError>;
    fn ciget(&self, pos: usize, name: &'static str) -> Result<I, SFError>;
    fn cimget(
        &self,
        pos: usize,
        name: &'static str,
        fun: fn(T) -> T,
    ) -> Result<I, SFError>;
}

impl<T: Copy + std::fmt::Debug + Display, I: TryFrom<T>> CCGet<T, I> for [T] {
    fn csiget(
        &self,
        pos: usize,
        name: &'static str,
        def: I,
    ) -> Result<I, SFError> {
        let raw = raw_cget(self, pos, name)?;
        Ok(soft_into(raw, name, def))
    }

    fn cwiget(
        &self,
        pos: usize,
        name: &'static str,
    ) -> Result<Option<I>, SFError> {
        let raw = raw_cget(self, pos, name)?;
        Ok(warning_try_into(raw, name))
    }

    fn csimget(
        &self,
        pos: usize,
        name: &'static str,
        def: I,
        fun: fn(T) -> T,
    ) -> Result<I, SFError> {
        let raw = raw_cget(self, pos, name)?;
        let raw = fun(raw);
        Ok(soft_into(raw, name, def))
    }

    fn ciget(&self, pos: usize, name: &'static str) -> Result<I, SFError> {
        let raw = raw_cget(self, pos, name)?;
        raw.try_into()
            .map_err(|_| SFError::ParsingError(name, raw.to_string()))
    }

    fn cimget(
        &self,
        pos: usize,
        name: &'static str,
        fun: fn(T) -> T,
    ) -> Result<I, SFError> {
        let raw = raw_cget(self, pos, name)?;
        let raw = fun(raw);
        raw.try_into()
            .map_err(|_| SFError::ParsingError(name, raw.to_string()))
    }
}

pub(crate) trait CSGet<T: FromStr> {
    fn cfsget(
        &self,
        pos: usize,
        name: &'static str,
    ) -> Result<Option<T>, SFError>;
    fn cfsuget(&self, pos: usize, name: &'static str) -> Result<T, SFError>;
}

impl<T: FromStr> CSGet<T> for [&str] {
    fn cfsget(
        &self,
        pos: usize,
        name: &'static str,
    ) -> Result<Option<T>, SFError> {
        let raw = raw_cget(self, pos, name)?;
        Ok(warning_from_str(raw, name))
    }

    fn cfsuget(&self, pos: usize, name: &'static str) -> Result<T, SFError> {
        let raw = raw_cget(self, pos, name)?;
        let Some(val) = warning_from_str(raw, name) else {
            return Err(SFError::ParsingError(name, raw.to_string()));
        };
        Ok(val)
    }
}

pub(crate) fn update_enum_map<
    B: Default + TryFrom<i64>,
    A: enum_map::Enum + enum_map::EnumArray<B>,
>(
    map: &mut enum_map::EnumMap<A, B>,
    vals: &[i64],
) {
    for (map_val, val) in map.as_mut_slice().iter_mut().zip(vals) {
        *map_val = soft_into(*val, "attribute val", B::default());
    }
}

/// This is a workaround for clippy index warnings for safe index ops. It
/// also is more convenient in some cases to use these fundtions if you want
/// to make sure something is &mut, or &
pub trait EnumMapGet<K, V> {
    /// Gets a normal reference to the value
    fn get(&self, key: K) -> &V;
    /// Gets a mutable reference to the value
    fn get_mut(&mut self, key: K) -> &mut V;
}

impl<K: Enum + EnumArray<V>, V> EnumMapGet<K, V> for EnumMap<K, V> {
    fn get(&self, key: K) -> &V {
        #[allow(clippy::indexing_slicing)]
        &self[key]
    }

    fn get_mut(&mut self, key: K) -> &mut V {
        #[allow(clippy::indexing_slicing)]
        &mut self[key]
    }
}

pub(crate) trait ArrSkip<T: Debug> {
    /// Basically does the equivalent of [pos..], but bounds checked with
    /// correct errors
    fn skip(&self, pos: usize, name: &'static str) -> Result<&[T], SFError>;
}

impl<T: Debug> ArrSkip<T> for [T] {
    fn skip(&self, pos: usize, name: &'static str) -> Result<&[T], SFError> {
        if pos > self.len() {
            return Err(SFError::TooShortResponse {
                name,
                pos,
                array: format!("{self:?}"),
            });
        }
        Ok(self.split_at(pos).1)
    }
}

pub(crate) trait CFPGet<T: Into<i64> + Copy + std::fmt::Debug, R: FromPrimitive>
{
    fn cfpget(
        &self,
        pos: usize,
        name: &'static str,
        fun: fn(T) -> T,
    ) -> Result<Option<R>, SFError>;

    fn cfpuget(
        &self,
        pos: usize,
        name: &'static str,
        fun: fn(T) -> T,
    ) -> Result<R, SFError>;
}

impl<T: Into<i64> + Copy + std::fmt::Debug, R: FromPrimitive> CFPGet<T, R>
    for [T]
{
    fn cfpget(
        &self,
        pos: usize,
        name: &'static str,
        fun: fn(T) -> T,
    ) -> Result<Option<R>, SFError> {
        let raw = raw_cget(self, pos, name)?;
        let raw = fun(raw);
        let t: i64 = raw.into();
        let res = FromPrimitive::from_i64(t);
        if res.is_none() && t != 0 && t != -1 {
            warn!("There might be a new {name} -> {t}");
        }
        Ok(res)
    }

    fn cfpuget(
        &self,
        pos: usize,
        name: &'static str,
        fun: fn(T) -> T,
    ) -> Result<R, SFError> {
        let raw = raw_cget(self, pos, name)?;
        let raw = fun(raw);
        let t: i64 = raw.into();
        FromPrimitive::from_i64(t)
            .ok_or_else(|| SFError::ParsingError(name, t.to_string()))
    }
}

pub(crate) trait CSTGet<T: Copy + Debug + Into<i64>> {
    fn cstget(
        &self,
        pos: usize,
        name: &'static str,
        server_time: ServerTime,
    ) -> Result<Option<DateTime<Local>>, SFError>;
}

impl<T: Copy + Debug + Into<i64>> CSTGet<T> for [T] {
    fn cstget(
        &self,
        pos: usize,
        name: &'static str,
        server_time: ServerTime,
    ) -> Result<Option<DateTime<Local>>, SFError> {
        let val = raw_cget(self, pos, name)?;
        let val = val.into();
        Ok(server_time.convert_to_local(val, name))
    }
}

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

    #[test]
    fn test_from_sf_string() {
        let input = "$bHello$cWorld$PThis$sis a test!";
        let expected_output = "\nHello:World%This/is a test!";
        let result = from_sf_string(input);
        assert_eq!(result, expected_output);

        let input = "$$$$$$$$$$$";
        let expected_output = "";
        let result = from_sf_string(input);
        assert_eq!(result, expected_output);

        let input = "$$b$c$P$s$p$+$q$r$C$S$d";
        let expected_output = "\n:%/|&\"#,;$";
        let result = from_sf_string(input);
        assert_eq!(result, expected_output);
    }
    #[test]
    fn test_to_sf_string() {
        let input = "\nHello:World%This/is a test!";
        let expected_output = "$bHello$cWorld$PThis$sis a test!";
        let result = to_sf_string(input);
        assert_eq!(result, expected_output);

        let input = "\n:%/|&\"#,;$";
        let expected_output = "$b$c$P$s$p$+$q$r$C$S$d";
        let result = to_sf_string(input);
        assert_eq!(result, expected_output);
    }
}