1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
pub mod arena;
pub mod character;
pub mod dungeons;
pub mod fortress;
pub mod guild;
pub mod idle;
pub mod items;
pub mod legendary_dungeon;
pub mod rewards;
pub mod social;
pub mod tavern;
pub mod underworld;
pub mod unlockables;
use std::{
borrow::Borrow,
collections::{HashMap, HashSet},
};
use chrono::{DateTime, Duration, Local, NaiveDateTime};
use enum_map::EnumMap;
use log::{error, warn};
use num_traits::FromPrimitive;
use strum::{EnumCount, IntoEnumIterator};
use crate::{
command::*,
error::*,
gamestate::{
arena::*, character::*, dungeons::*, fortress::*, guild::*, idle::*,
items::*, legendary_dungeon::*, rewards::*, social::*, tavern::*,
underworld::*, unlockables::*,
},
misc::*,
response::{Response, ResponseVal},
};
/// Represent the full state of the game at some point in time
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GameState {
/// Everything, that can be considered part of the character, or his
/// immediate surrounding and not the rest of the world
pub character: Character,
/// Information about quests and work
pub tavern: Tavern,
/// The place to fight other players
pub arena: Arena,
/// The last fight, that this player was involved in
pub last_fight: Option<Fight>,
/// Both shops. You can access a specific one either with `get()`,
/// `get_mut()`, or `[]` and the `ShopType` as the key.
pub shops: EnumMap<ShopType, Shop>,
pub shop_item_lvl: u32,
/// If the player is in a guild, this will contain information about it
pub guild: Option<Guild>,
/// Everything, that is time sensitive, like events, calendar, etc.
pub specials: TimedSpecials,
/// Everything, that can be found under the Dungeon tab
pub dungeons: Dungeons,
/// Contains information about the underworld, if it has been unlocked
pub underworld: Option<Underworld>,
/// Contains information about the fortress, if it has been unlocked
pub fortress: Option<Fortress>,
/// Information the pet collection, that a player can build over time
pub pets: Option<Pets>,
/// Contains information about the hellevator, if it is currently active
pub hellevator: HellevatorEvent,
/// Contains information about the legendary dungeons event, if it is
/// currently active
pub legendary_dungeon: LegendaryDungeonEvent,
/// Contains information about the blacksmith, if it has been unlocked
pub blacksmith: Option<Blacksmith>,
/// Contains information about the witch, if it has been unlocked
pub witch: Option<Witch>,
/// Tracker for small challenges, that a player can complete
pub achievements: Achievements,
/// The boring idle game
pub idle_game: Option<IdleGame>,
/// Contains the features this char is able to unlock right now
pub pending_unlocks: Vec<Unlockable>,
/// Anything related to hall of fames
pub hall_of_fames: HallOfFames,
/// Contains both other guilds & players, that you can look at via commands
pub lookup: Lookup,
/// Anything you can find in the mail tab of the official client
pub mail: Mail,
/// The raw timestamp, that the server has sent us
last_request_timestamp: i64,
/// The amount of sec, that the server is ahead of us in seconds (can be
/// negative)
server_time_diff: i64,
}
const SHOP_N: usize = 6;
/// A shop, that you can buy items from
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Shop {
pub typ: ShopType,
/// The items this shop has for sale
pub items: [Item; SHOP_N],
}
impl Default for Shop {
fn default() -> Self {
let items = core::array::from_fn(|_| Item {
typ: ItemType::Unknown(0),
price: u32::MAX,
mushroom_price: u32::MAX,
model_id: 0,
class: None,
type_specific_val: 0,
attributes: EnumMap::default(),
gem_slot: None,
rune: None,
enchantment: None,
color: 0,
upgrade_count: 0,
item_quality: 0,
is_washed: false,
full_model_id: 0,
});
Self {
items,
typ: ShopType::Magic,
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ShopPosition {
pub typ: ShopType,
pub pos: usize,
}
impl std::fmt::Display for ShopPosition {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.typ as usize, self.pos + 1)
}
}
impl ShopPosition {
/// The 0 based index into the backpack vec, where the item is parsed into
#[must_use]
pub fn shop(&self) -> ShopType {
self.typ
}
/// The inventory type and position within it, where the item is stored
/// according to previous inventory management logic. This is what you use
/// for commands
#[must_use]
pub fn position(&self) -> usize {
self.pos
}
}
impl Shop {
/// Creates an iterator over the inventory slots.
pub fn iter(&self) -> impl Iterator<Item = (ShopPosition, &Item)> {
self.items
.iter()
.enumerate()
.map(|(pos, item)| (ShopPosition { typ: self.typ, pos }, item))
}
pub(crate) fn parse(
data: &[i64],
server_time: ServerTime,
typ: ShopType,
) -> Result<Shop, SFError> {
let mut shop = Shop::default();
shop.typ = typ;
for (idx, item) in shop.items.iter_mut().enumerate() {
let d = data.skip(idx * ITEM_PARSE_LEN, "shop item")?;
let Some(p_item) = Item::parse(d, server_time)? else {
return Err(SFError::ParsingError(
"shop item",
format!("{d:?}"),
));
};
*item = p_item;
}
Ok(shop)
}
}
impl GameState {
/// Constructs a new `GameState` from the provided response. The response
/// has to be the login response from a `Session`.
///
/// # Errors
/// If the response contains any errors, or does not contain enough
/// information about the player to build a full `GameState`, this will
/// return a `ParsingError`, or `TooShortResponse` depending on the
/// exact error
pub fn new(response: Response) -> Result<Self, SFError> {
let mut res = Self::default();
res.update(response)?;
if res.character.level == 0 || res.character.name.is_empty() {
return Err(SFError::ParsingError(
"response did not contain full player state",
String::new(),
));
}
Ok(res)
}
/// Updates the players information with the new data received from the
/// server. Any error that is encounters terminates the update process
///
/// # Errors
/// Mainly returns `ParsingError` if the response does not exactly follow
/// the expected length, type and layout
pub fn update<R: Borrow<Response>>(
&mut self,
response: R,
) -> Result<(), SFError> {
let response = response.borrow();
let new_vals = response.values();
// Because the conversion of all other timestamps relies on the servers
// timestamp, this has to be set first
if let Some(ts) = new_vals.get("timestamp").copied() {
let ts = ts.into("server time stamp")?;
let server_time = DateTime::from_timestamp(ts, 0).ok_or(
SFError::ParsingError("server time stamp", ts.to_string()),
)?;
self.server_time_diff = (server_time.naive_utc()
- response.received_at())
.num_seconds();
self.last_request_timestamp = ts;
}
let server_time = self.server_time();
self.last_fight = None;
self.mail.open_claimable = None;
let mut other_player: Option<OtherPlayer> = None;
let mut other_guild: Option<OtherGuild> = None;
let mut errors = vec![];
for (key, val) in new_vals.iter().map(|(a, b)| (*a, *b)) {
let res = self.apply_update_key(
key,
val,
&mut other_player,
&mut other_guild,
server_time,
new_vals,
);
if let Err(err) = res {
errors.push(err);
}
}
if let Some(og) = other_guild {
self.lookup.guilds.insert(og.name.clone(), og);
}
if let Some(other_player) = other_player {
self.lookup.insert_lookup(other_player);
}
// Dungeon portal is unlocked with level 99
if self.dungeons.portal.is_some() && self.character.level < 99 {
self.dungeons.portal = None;
}
if let Some(pets) = &self.pets
&& pets.rank == 0
{
self.pets = None;
}
if let Some(t) = &self.guild
&& t.name.is_empty()
{
self.guild = None;
}
if self.fortress.is_some() && self.character.level < 25 {
self.fortress = None;
}
if let Some(fortress) = &mut self.fortress {
for (typ, unit) in &mut fortress.units {
let building_lvl =
fortress.buildings.get(typ.training_building()).level;
let limit_modifier = match typ {
FortressUnitType::Magician => 1,
FortressUnitType::Archer => 2,
FortressUnitType::Soldier => 3,
};
unit.limit = building_lvl * limit_modifier;
}
}
if let Some(t) = &self.underworld
&& t.buildings[UnderworldBuildingType::HeartOfDarkness].level < 1
{
self.underworld = None;
}
// Witch is automatically unlocked with level 66
if self.witch.is_some() && self.character.level < 66 {
self.witch = None;
}
match errors.len() {
0 => Ok(()),
1 => Err(errors.remove(0)),
_ => Err(SFError::NestedError(errors)),
}
}
pub(crate) fn updatete_relation_list(&mut self, val: &str) {
self.character.relations.clear();
for entry in val
.trim_end_matches(';')
.split(';')
.filter(|a| !a.is_empty())
{
let mut parts = entry.split(',');
let (
Some(id),
Some(name),
Some(guild),
Some(level),
Some(relation),
) = (
parts.next().and_then(|a| a.parse().ok()),
parts.next().map(std::string::ToString::to_string),
parts.next().map(std::string::ToString::to_string),
parts.next().and_then(|a| a.parse().ok()),
parts.next().and_then(|a| match a {
"-1" => Some(Relationship::Ignored),
"1" => Some(Relationship::Friend),
_ => None,
}),
)
else {
warn!("bad friendslist entry: {entry}");
continue;
};
self.character.relations.push(RelationEntry {
id,
name,
guild,
level,
relation,
});
}
}
pub(crate) fn update_gttime(
&mut self,
data: &[i64],
server_time: ServerTime,
) -> Result<(), SFError> {
let d = &mut self.hellevator;
d.start = data.cstget(0, "event start", server_time)?;
d.end = data.cstget(1, "event end", server_time)?;
d.collect_time_end = data.cstget(3, "claim time end", server_time)?;
Ok(())
}
pub(crate) fn update_resources(
&mut self,
res: &[i64],
) -> Result<(), SFError> {
self.character.mushrooms = res.csiget(1, "mushrooms", 0)?;
self.character.silver = res.csiget(2, "player silver", 0)?;
self.tavern.quicksand_glasses =
res.csiget(4, "quicksand glass count", 0)?;
self.specials.wheel.lucky_coins = res.csiget(3, "lucky coins", 0)?;
let bs = self.blacksmith.get_or_insert_with(Default::default);
bs.metal = res.csiget(9, "bs metal", 0)?;
bs.arcane = res.csiget(10, "bs arcane", 0)?;
let fortress = self.fortress.get_or_insert_with(Default::default);
fortress
.resources
.get_mut(FortressResourceType::Wood)
.current = res.csiget(5, "saved wood ", 0)?;
fortress
.resources
.get_mut(FortressResourceType::Stone)
.current = res.csiget(7, "saved stone", 0)?;
let pets = self.pets.get_or_insert_with(Default::default);
for (e_pos, element) in HabitatType::iter().enumerate() {
pets.habitats.get_mut(element).fruits =
res.csiget(12 + e_pos, "fruits", 0)?;
}
self.underworld
.get_or_insert_with(Default::default)
.souls_current = res.csiget(11, "uu souls saved", 0)?;
Ok(())
}
/// Returns the time of the server. This is just an 8 byte copy behind the
/// scenes, so feel free to NOT cache/optimize calling this in any way
#[must_use]
pub fn server_time(&self) -> ServerTime {
ServerTime(self.server_time_diff)
}
/// Given a header value like "fight4", this would give you the
/// corresponding fight[3]. In case that does not exist, it will be created
/// w/ the default
#[must_use]
fn get_fight(&mut self, header_name: &str) -> &mut SingleFight {
let id = fight_no_from_header(header_name);
let fights =
&mut self.last_fight.get_or_insert_with(Default::default).fights;
if fights.len() < id {
fights.resize(id, SingleFight::default());
}
#[allow(clippy::unwrap_used)]
fights.get_mut(id - 1).unwrap()
}
/// Updates the gamestate with the given key and value
#[allow(clippy::match_same_arms)]
fn apply_update_key(
&mut self,
key: &str,
val: ResponseVal<'_>,
other_player: &mut Option<OtherPlayer>,
other_guild: &mut Option<OtherGuild>,
server_time: ServerTime,
all_values: &HashMap<&str, ResponseVal<'_>>,
) -> Result<(), SFError> {
match key {
"timestamp" => {
// Handled above
}
"Success" | "sucess" => {
// Whatever we did worked. Note that the server also
// sends this for bad requests from time to time :)
}
"login count" | "sessionid" | "cryptokey" | "cryptoid" => {
// Should already be handled when receiving the response
}
"preregister"
| "languagecodelist"
| "tracking"
| "skipvideo"
| "webshopid"
| "cidstring"
| "mountexpired"
| "tracking_netto"
| "tracking_coins"
| "tutorial_game_entry" => {
// Stuff that looks irrellevant
}
"ownplayername" => {
self.character.name.set(val.as_str());
}
"owndescription" => {
self.character.description = from_sf_string(val.as_str());
}
"wagesperhour" => {
self.tavern.guard_wage = val.into("tavern wage")?;
}
"skipallow" => {
let raw_skip = val.into::<i32>("skip allow")?;
self.tavern.mushroom_skip_allowed = raw_skip != 0;
}
"cryptoid not found" => return Err(SFError::ConnectionError),
"ownplayersave" => {
// Goodbye old friend...
}
"owngroupname" => self
.guild
.get_or_insert_with(Default::default)
.name
.set(val.as_str()),
"tavernspecialsub" => {
self.specials.events.active.clear();
let flags = val.into::<i32>("tavern special sub")?;
for (idx, event) in Event::iter().enumerate() {
if (flags & (1 << idx)) > 0 {
self.specials.events.active.insert(event);
}
}
}
"sfhomeid" => {}
"backpack" => {
let data: Vec<i64> = val.into_list("backpack")?;
self.character.inventory.backpack = data
.chunks_exact(ITEM_PARSE_LEN)
.map(|a| Item::parse(a, server_time))
.collect::<Result<Vec<_>, _>>()?;
}
"itemlevelshop" => {
self.shop_item_lvl = val.into("shop lvl")?;
}
"storeitemsshakes" => {
let data: Vec<i64> = val.into_list("weapon store")?;
*self.shops.get_mut(ShopType::Weapon) =
Shop::parse(&data, server_time, ShopType::Weapon)?;
}
"questofferitems" => {
for (chunk, quest) in val
.into_list("quest items")?
.chunks_exact(19)
.zip(&mut self.tavern.quests)
{
quest.item = Item::parse(chunk, server_time)?;
}
}
#[allow(
clippy::indexing_slicing,
clippy::cast_sign_loss,
clippy::cast_possible_truncation
)]
#[allow(deprecated)]
"toiletstate" => {
let vals: Vec<i64> = val.into_list("toilet state")?;
if vals.len() < 3 {
return Ok(());
}
let toilet = self.tavern.toilet.get_or_insert_default();
toilet.sacrifices_left = vals[2] as u32;
}
"companionequipment" => {
let data: Vec<i64> = val.into_list("quest items")?;
if data.is_empty() {
return Ok(());
}
for (idx, cmp) in self
.dungeons
.companions
.get_or_insert_with(Default::default)
.values_mut()
.enumerate()
{
let data = data.skip(
(19 * EquipmentSlot::COUNT) * idx,
"companion item",
)?;
cmp.equipment = Equipment::parse(data, server_time)?;
}
}
"storeitemsfidget" => {
let data: Vec<i64> = val.into_list("magic store")?;
*self.shops.get_mut(ShopType::Magic) =
Shop::parse(&data, server_time, ShopType::Magic)?;
}
"ownplayersaveequipment" => {
let data: Vec<i64> = val.into_list("player equipment")?;
self.character.equipment =
Equipment::parse(&data, server_time)?;
}
"systemmessagelist" => {}
"newslist" => {}
"dummieequipment" => {
let m: Vec<i64> = val.into_list("mannequin")?;
self.character.mannequin =
Some(Equipment::parse(&m, server_time)?);
}
"owntower" => {
let data = val.into_list("tower")?;
let companions = self
.dungeons
.companions
.get_or_insert_with(Default::default);
for (i, class) in CompanionClass::iter().enumerate() {
let comp_start = 3 + i * 148;
companions.get_mut(class).level =
data.cget(comp_start, "comp level")?;
update_enum_map(
&mut companions.get_mut(class).attributes,
data.skip(comp_start + 4, "comp attrs")?,
);
}
// Why would they include this in the tower response???
self.underworld
.get_or_insert_with(Default::default)
.update(&data, server_time)?;
}
"owngrouprank" => {
self.guild.get_or_insert_with(Default::default).rank =
val.into("group rank")?;
}
"owngroupattack" | "owngroupdefense" => {
// Annoying
}
"owngrouprequirement" | "othergrouprequirement" => {
// TODO:
}
"owngroupsave" => {
self.guild
.get_or_insert_with(Default::default)
.update_group_save(val.as_str(), server_time)?;
}
"owngroupmember" => self
.guild
.get_or_insert_with(Default::default)
.update_member_names(val.as_str()),
"owngrouppotion" => {
self.guild
.get_or_insert_with(Default::default)
.update_member_potions(val.as_str());
}
"unitprice" => {
self.fortress
.get_or_insert_with(Default::default)
.update_unit_prices(&val.into_list("fortress units")?)?;
}
"dicestatus" => {
let dices: Option<Vec<DiceType>> = val
.into_list("dice status")?
.into_iter()
.map(FromPrimitive::from_u8)
.collect();
self.tavern.dice_game.current_dice = dices.unwrap_or_default();
}
"dicereward" => {
let data: Vec<u32> = val.into_list("dice reward")?;
let win_typ: DiceType =
data.cfpuget(0, "dice reward", |a| a - 1)?;
self.tavern.dice_game.reward = Some(DiceReward {
win_typ,
amount: data.cget(1, "dice reward amount")?,
});
}
"chathistory" => {
self.guild.get_or_insert_with(Default::default).chat =
ChatMessage::parse_messages(val.as_str());
}
"chatwhisper" => {
self.guild.get_or_insert_with(Default::default).whispers =
ChatMessage::parse_messages(val.as_str());
}
"upgradeprice" => {
self.fortress
.get_or_insert_with(Default::default)
.update_unit_upgrade_info(
&val.into_list("fortress unit upgrade prices")?,
)?;
}
"unitlevel" => {
self.fortress
.get_or_insert_with(Default::default)
.update_levels(&val.into_list("fortress unit levels")?)?;
}
"fortressprice" => {
self.fortress
.get_or_insert_with(Default::default)
.update_prices(
&val.into_list("fortress upgrade prices")?,
)?;
}
"Arenarank" => {
if let Some(uw) = self.underworld.as_mut() {
uw.lure_suggestion =
val.as_str().parse::<u32>().ok().map(LureSuggestion);
}
}
"witch" => {
// old witch data without price
}
"witchshop" => {
self.witch
.get_or_insert_with(Default::default)
.update(&val.into_list("witch")?)?;
}
"underworldupgradeprice" => {
self.underworld
.get_or_insert_with(Default::default)
.update_underworld_unit_prices(
&val.into_list("underworld upgrade prices")?,
)?;
}
"unlockfeature" => {
self.pending_unlocks =
Unlockable::parse(&val.into_list("unlock")?)?;
}
"dungeonprogresslight" => self.dungeons.update_progress(
&val.into_list("dungeon progress light")?,
DungeonType::Light,
),
"dungeonprogressshadow" => self.dungeons.update_progress(
&val.into_list("dungeon progress shadow")?,
DungeonType::Shadow,
),
"portalprogress" => {
self.dungeons
.portal
.get_or_insert_with(Default::default)
.update(&val.into_list("portal progress")?, server_time)?;
}
"tavernspecialend" => {
self.specials.events.ends = server_time
.convert_to_local(val.into("event end")?, "event end");
}
"owntowerlevel" => {
// Already in dungeons
}
"serverversion" => {
// Handled in session
}
"stoneperhournextlevel" => {
self.fortress
.get_or_insert_with(Default::default)
.resources
.get_mut(FortressResourceType::Stone)
.production
.per_hour_next_lvl = val.into("stone next lvl")?;
}
"woodperhournextlevel" => {
self.fortress
.get_or_insert_with(Default::default)
.resources
.get_mut(FortressResourceType::Wood)
.production
.per_hour_next_lvl = val.into("wood next lvl")?;
}
"shadowlevel" | "dungeonlevel" => {
// We just look at the db
}
"gttime" => {
self.update_gttime(&val.into_list("gttime")?, server_time)?;
}
"gtsave" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.update(&val.into_list("gtsave")?, server_time)?;
}
"maxrank" => {
self.hall_of_fames.players_total = val.into("player count")?;
}
"achievement" => {
self.achievements.update(&val.into_list("achievements")?)?;
}
"groupskillprice" => {
self.guild
.get_or_insert_with(Default::default)
.update_group_prices(
&val.into_list("guild skill prices")?,
)?;
}
"soldieradvice" => {
// Replaced
}
"owngroupdescription" => self
.guild
.get_or_insert_with(Default::default)
.update_description_embed(val.as_str()),
"idle" => {
self.idle_game = IdleGame::parse_idle_game(
&val.into_list("idle game")?,
server_time,
);
}
"resources" => {
self.update_resources(&val.into_list("resources")?)?;
}
"chattime" => {
// let _chat_time = server_time
// .convert_to_local(val.into("chat time")?, "chat
// time"); Pretty sure this is the time something last
// happened in chat, but nobody cares and messages have a
// time
}
"maxpetlevel" => {
self.pets.get_or_insert_with(Default::default).max_pet_level =
val.into("max pet lvl")?;
}
"otherdescription" => {
other_player
.get_or_insert_with(Default::default)
.description = from_sf_string(val.as_str());
}
"otherplayergroupname" => {
let guild =
Some(val.as_str().to_string()).filter(|a| !a.is_empty());
other_player.get_or_insert_with(Default::default).guild = guild;
}
"otherplayername" => {
other_player
.get_or_insert_with(Default::default)
.name
.set(val.as_str());
}
"otherplayersaveequipment" => {
let data: Vec<i64> = val.into_list("other player equipment")?;
other_player.get_or_insert_with(Default::default).equipment =
Equipment::parse(&data, server_time)?;
}
"fortresspricereroll" => {
self.fortress
.get_or_insert_with(Default::default)
.opponent_reroll_price = val.into("fortress reroll")?;
}
"fortresswalllevel" => {
self.fortress
.get_or_insert_with(Default::default)
.wall_combat_lvl = val.into("fortress wall lvl")?;
}
"dragongoldbonus" => {
self.character.mount_dragon_refund = val.into("dragon gold")?;
}
"wheelresult" => {
// NOTE: These are the reqs to unlock the upgrade, not a
// check if it is actually upgraded
let upgraded = self.character.level >= 95
&& self.pets.is_some()
&& self.underworld.is_some();
self.specials.wheel.result = Some(WheelReward::parse(
&val.into_list("wheel result")?,
upgraded,
)?);
}
"dailyreward" => {
// Dead since last update
}
"calenderreward" => {
// Probably removed and should be irrelevant
}
"oktoberfest" => {
// Not sure if this is still used, but it seems to just be
// empty.
if !val.as_str().is_empty() {
warn!("oktoberfest response is not empty: {val}");
}
}
"usersettings" => {
// Contains language and flag settings
let vals: Vec<_> = val.as_str().split('/').collect();
let v = match vals.as_slice().cget(4, "questing setting")? {
"a" => ExpeditionSetting::PreferExpeditions,
"0" | "b" => ExpeditionSetting::PreferQuests,
x => {
error!("Weird expedition settings: {x}");
ExpeditionSetting::PreferQuests
}
};
self.tavern.questing_preference = v;
}
"mailinvoice" => {
// Incomplete email address
}
"calenderinfo" => {
// This is twice in the original response.
// This API sucks LMAO
let data: Vec<i64> = val.into_list("calendar")?;
self.specials.calendar.rewards.clear();
for p in data.chunks_exact(2) {
let reward = CalendarReward::parse(p)?;
self.specials.calendar.rewards.push(reward);
}
}
"othergroupattack" => {
other_guild.get_or_insert_with(Default::default).attacks =
Some(val.to_string());
}
"othergroupdefense" => {
other_guild
.get_or_insert_with(Default::default)
.defends_against = Some(val.to_string());
}
"inboxcapacity" => {
self.mail.inbox_capacity = val.into("inbox cap")?;
}
"magicregistration" => {
// Pretty sure this means you have not provided a pw or
// mail. Just a name and clicked play
}
"Ranklistplayer" => {
self.hall_of_fames.players.clear();
for player in val.as_str().trim_matches(';').split(';') {
// Stop parsing once we receive an empty player
if player.ends_with(",,,0,0,0,") {
break;
}
match HallOfFamePlayer::parse(player) {
Ok(x) => {
self.hall_of_fames.players.push(x);
}
Err(err) => warn!("{err}"),
}
}
}
"ranklistgroup" => {
self.hall_of_fames.guilds.clear();
for guild in val.as_str().trim_matches(';').split(';') {
match HallOfFameGuild::parse(guild) {
Ok(x) => {
self.hall_of_fames.guilds.push(x);
}
Err(err) => warn!("{err}"),
}
}
}
"maxrankgroup" => {
self.hall_of_fames.guilds_total = Some(val.into("guild max")?);
}
"maxrankPets" => {
self.hall_of_fames.pets_total = Some(val.into("pet rank max")?);
}
"RanklistPets" => {
self.hall_of_fames.pets.clear();
for entry in val.as_str().trim_matches(';').split(';') {
match HallOfFamePets::parse(entry) {
Ok(x) => {
self.hall_of_fames.pets.push(x);
}
Err(err) => warn!("{err}"),
}
}
}
"ranklistfortress" | "Ranklistfortress" => {
self.hall_of_fames.fortresses.clear();
for guild in val.as_str().trim_matches(';').split(';') {
match HallOfFameFortress::parse(guild) {
Ok(x) => {
self.hall_of_fames.fortresses.push(x);
}
Err(err) => warn!("{err}"),
}
}
}
"ranklistunderworld" => {
self.hall_of_fames.underworlds.clear();
for entry in val.as_str().trim_matches(';').split(';') {
match HallOfFameUnderworld::parse(entry) {
Ok(x) => {
self.hall_of_fames.underworlds.push(x);
}
Err(err) => warn!("{err}"),
}
}
}
"gamblegoldvalue" => {
self.tavern.gamble_result =
Some(GambleResult::SilverChange(val.into("gold gamble")?));
}
"gamblecoinvalue" => {
self.tavern.gamble_result = Some(GambleResult::MushroomChange(
val.into("gold gamble")?,
));
}
"maxrankFortress" => {
self.hall_of_fames.fortresses_total =
Some(val.into("fortress max")?);
}
"underworldprice" => self
.underworld
.get_or_insert_with(Default::default)
.update_building_prices(&val.into_list("ub prices")?)?,
"owngroupknights" => self
.guild
.get_or_insert_with(Default::default)
.update_group_knights(val.as_str()),
"friendlist" => self.updatete_relation_list(val.as_str()),
"legendaries" => {
if val.as_str().chars().any(|a| a != 'A') {
warn!("Found a legendaries value, that is not just AAA..");
}
}
"smith" => {
let data: Vec<i64> = val.into_list("smith")?;
let bs = self.blacksmith.get_or_insert_with(Default::default);
bs.dismantle_left = data.csiget(0, "dismantles left", 0)?;
bs.last_dismantled = data.cstget(1, "bs time", server_time)?;
}
"tavernspecial" => {
// Pretty sure this has been replaced
}
"fortressGroupPrice" => {
self.fortress
.get_or_insert_with(Default::default)
.hall_of_knights_upgrade_price = FortressCost::parse(
&val.into_list("hall of knights prices")?,
)?;
}
"goldperhournextlevel" => {
// I dont think this matters
}
"underworldmaxsouls" => {
// This should already be in resources
}
"dailytaskrewardpreview" => {
let vals: Vec<i64> =
val.into_list("event task reward preview")?;
self.specials.tasks.daily.rewards = parse_rewards(&vals);
}
"expeditionevent" => {
let data: Vec<i64> = val.into_list("exp event")?;
self.tavern.expeditions.start =
data.cstget(0, "expedition start", server_time)?;
let end = data.cstget(1, "expedition end", server_time)?;
self.tavern.expeditions.end = end;
}
"expeditions" => {
let data: Vec<i64> = val.into_list("exp event")?;
if !data.len().is_multiple_of(8) {
warn!(
"Available expeditions have weird size: {data:?} {}",
data.len()
);
}
self.tavern.expeditions.available = data
.chunks_exact(8)
.map(|data| {
Ok(AvailableExpedition {
target: data
.cfpget(0, "expedition typ", |a| a)?
.unwrap_or_default(),
location_1: data
.cfpget(4, "exp loc 1", |a| a)?
.unwrap_or_default(),
location_2: data
.cfpget(5, "exp loc 2", |a| a)?
.unwrap_or_default(),
thirst_for_adventure_sec: data
.csiget(6, "exp alu", 600)?,
special: data.cfpget(7, "exp special", |a| a)?,
})
})
.collect::<Result<_, _>>()?;
}
"expeditionrewardresources" => {
// I would assume, that everything we get is just update
// elsewhere, so I dont care about parsing this
}
"expeditionreward" => {
// This works, but I dont think anyone cares about that. It
// will just be in the inv. anyways
// let data:Vec<i64> = val.into_list("expedition reward")?;
// for chunk in data.chunks_exact(ITEM_PARSE_LEN){
// let item = Item::parse(chunk, server_time);
// println!("{item:#?}");
// }
}
"expeditionmonster" => {
let data: Vec<i64> = val.into_list("expedition monster")?;
let exp = self
.tavern
.expeditions
.active
.get_or_insert_with(Default::default);
exp.boss = ExpeditionBoss {
id: data
.cfpget(0, "expedition monster", |a| -a)?
.unwrap_or_default(),
items: soft_into(
data.get(1).copied().unwrap_or_default(),
"exp monster items",
3,
),
};
}
"expeditionhalftime" => {
let data: Vec<i64> = val.into_list("halftime exp")?;
let exp = self
.tavern
.expeditions
.active
.get_or_insert_with(Default::default);
exp.halftime_for_boss_id =
-data.cget(0, "halftime for boss id")?;
exp.rewards = data
.skip(1, "halftime choice")?
.chunks_exact(2)
.map(Reward::parse)
.collect::<Result<_, _>>()?;
}
"expeditionstate" => {
let data: Vec<i64> = val.into_list("exp state")?;
let exp = self
.tavern
.expeditions
.active
.get_or_insert_with(Default::default);
exp.floor_stage = data.cget(2, "floor stage")?;
exp.target_thing = data
.cfpget(3, "expedition target", |a| a)?
.unwrap_or_default();
exp.target_current = data.csiget(7, "exp current", 100)?;
exp.target_amount = data.csiget(8, "exp target", 100)?;
exp.current_floor = data.csiget(0, "clearing", 0)?;
exp.heroism = data.csiget(13, "heroism", 0)?;
exp.busy_since = data.cstget(15, "exp start", server_time)?;
exp.busy_until = data.cstget(16, "exp busy", server_time)?;
for (x, item) in data
.skip(9, "exp items")?
.iter()
.copied()
.zip(&mut exp.items)
{
*item = match FromPrimitive::from_i64(x) {
None if x != 0 => {
warn!("Unknown item: {x}");
Some(ExpeditionThing::Unknown)
}
x => x,
};
}
}
"expeditioncrossroad" => {
// 3/3/132/0/2/2
let data: Vec<i64> = val.into_list("cross")?;
let exp = self
.tavern
.expeditions
.active
.get_or_insert_with(Default::default);
exp.update_encounters(&data);
}
"eventtasklist" => {
let data: Vec<i64> = val.into_list("etl")?;
self.specials.tasks.event.tasks.clear();
for c in data.chunks_exact(4) {
let task = Task::parse(c)?;
self.specials.tasks.event.tasks.push(task);
}
}
"eventtaskrewardpreview" => {
let vals: Vec<i64> =
val.into_list("event task reward preview")?;
self.specials.tasks.event.rewards = parse_rewards(&vals);
}
"dailytasklist" => {
let data: Vec<i64> = val.into_list("daily tasks list")?;
self.specials.tasks.daily.tasks.clear();
// I think the first value here is the amount of > 1 bell
// quests
for d in data.skip(1, "daily tasks")?.chunks_exact(4) {
self.specials.tasks.daily.tasks.push(Task::parse(d)?);
}
}
"eventtaskinfo" => {
let data: Vec<i64> = val.into_list("eti")?;
self.specials.tasks.event.theme = data
.cfpget(2, "event task theme", |a| a)?
.unwrap_or(EventTaskTheme::Unknown);
self.specials.tasks.event.start =
data.cstget(0, "event t start", server_time)?;
self.specials.tasks.event.end =
data.cstget(1, "event t end", server_time)?;
}
"scrapbook" => {
self.character.scrapbook = ScrapBook::parse(val.as_str());
}
"dungeonfaces" | "shadowfaces" => {
// Gets returned after winning a dungeon fight. This looks a
// bit like a reward, but that should be handled in fight
// parsing already?
}
"messagelist" => {
let data = val.as_str();
self.mail.inbox.clear();
for msg in data.split(';').filter(|a| !a.trim().is_empty()) {
match InboxEntry::parse(msg, server_time) {
Ok(msg) => self.mail.inbox.push(msg),
Err(e) => warn!("Invalid msg: {msg} {e}"),
}
}
}
"messagetext" => {
self.mail.open_msg = Some(from_sf_string(val.as_str()));
}
"combatloglist" => {
self.mail.combat_log.clear();
for entry in val.as_str().split(';') {
let parts = entry.split(',').collect::<Vec<_>>();
if parts.iter().all(|a| a.is_empty()) {
continue;
}
match CombatLogEntry::parse(&parts, server_time) {
Ok(cle) => {
self.mail.combat_log.push(cle);
}
Err(e) => {
warn!(
"Unable to parse combat log entry: {parts:?} \
- {e}"
);
}
}
}
}
"maxupgradelevel" => {
self.fortress
.get_or_insert_with(Default::default)
.building_max_lvl = val.into("max upgrade lvl")?;
}
"singleportalenemylevel" => {
self.dungeons
.portal
.get_or_insert_with(Default::default)
.enemy_level = val.into("portal lvl").unwrap_or(u32::MAX);
}
"ownpetsstats" => {
self.pets
.get_or_insert_with(Default::default)
.update_pet_stat(&val.into_list("pet stats")?);
}
"ownpets" => {
let data = val.into_list("own pets")?;
self.pets
.get_or_insert_with(Default::default)
.update(&data, server_time)?;
}
"petsdefensetype" => {
let pet_id = val.into("pet def typ")?;
self.pets
.get_or_insert_with(Default::default)
.opponent
.habitat = Some(HabitatType::from_typ_id(pet_id).ok_or(
SFError::ParsingError("pet def typ", format!("{pet_id}")),
)?);
}
"otherplayersavecharacter" => {
other_player
.get_or_insert_default()
.update(&val.into_list("other player")?, server_time)?;
}
"otherplayersavepotions" => {
other_player.get_or_insert_default().active_potions =
items::parse_active_potions(
&val.into_list("other potions")?,
server_time,
);
}
"otherplayer" => {
let data: Vec<i64> = val.into_list("other player")?;
#[allow(deprecated)]
{
other_player.get_or_insert_default().guild_joined =
data.cstget(166, "other joined guild", server_time)?;
}
}
"otherplayerfriendstatus" => {
other_player
.get_or_insert_with(Default::default)
.relationship = warning_parse(
val.into::<i32>("other friend")?,
"other friend",
FromPrimitive::from_i32,
)
.unwrap_or_default();
}
"otherplayerpetbonus" => {
other_player
.get_or_insert_with(Default::default)
.update_pet_bonus(&val.into_list("o pet bonus")?)?;
}
"otherplayerunitlevel" => {
let data: Vec<i64> =
val.into_list("other player unit level")?;
// This includes other levels, but they are handled
// elsewhere I think
other_player
.get_or_insert_with(Default::default)
.wall_combat_lvl = data.csiget(0, "wall_lvl", 0)?;
}
"petsrank" => {
self.pets.get_or_insert_with(Default::default).rank =
val.into("pet rank")?;
}
"maxrankUnderworld" => {
self.hall_of_fames.underworlds_total =
Some(val.into("mrank under")?);
}
"otherplayerfortressrank" => {
match val.into::<i64>("other player fortress rank")? {
..=-1 => {}
x => {
let rank = x.try_into().unwrap_or(1);
other_player
.get_or_insert_default()
.fortress
.get_or_insert_default()
.rank = rank;
}
}
}
"workreward" => {
// Should be irrelevant
}
x if x.starts_with("winnerid") => {
// For all winnerid's, except the last one, the winnerid
// value contains the fightversion as well
let raw_winner_id = val
.as_str()
.split_once(|a: char| !a.is_ascii_digit())
.map_or(val.as_str(), |a| a.0);
if let Ok(winner_id) = raw_winner_id.parse() {
self.get_fight(x).winner_id = winner_id;
} else {
error!("Invalid winner id: {raw_winner_id}");
}
}
"fightresult" => {
let data: Vec<i64> = val.into_list("fight result")?;
self.last_fight
.get_or_insert_with(Default::default)
.update_result(&data, server_time)?;
// Note: The sub_key from this, can improve fighter parsing
}
x if x.starts_with("fightheader") => {
self.get_fight(x).update_fighters(val.as_str());
}
"fightgroups" => {
let fight =
self.last_fight.get_or_insert_with(Default::default);
fight.update_groups(val.as_str());
}
"fightadditionalplayers" => {
// This should be players in guild battles, that have not
// participapted. I dont think this matters
}
"fightversion" => {
// This key is unreliable and partially merged into
// winnerid, so I just parse this in the fight response
// below, where it is actually used
}
x if x.starts_with("fight") && x.len() <= 7 => {
let fight_no = fight_no_from_header(x);
let wkey = format!("winnerid{fight_no}");
let version = if let Some(winner_id) =
all_values.get(wkey.as_str())
{
// For unknown reasons, the fightversion is merged
// into the winnerid for all fights, except the last
// one
winner_id.as_str().split_once("fightversion:").map(|a| a.1)
} else {
// The last fight uses the normal fightversion
// header
all_values.get("fightversion").map(|a| a.as_str())
};
let fight = self.get_fight(x);
if let Some(version) = version.and_then(|a| a.parse().ok()) {
fight.update_rounds(val.as_str(), version)?;
} else {
fight.actions.clear();
}
}
"othergroupname" => {
other_guild
.get_or_insert_with(Default::default)
.name
.set(val.as_str());
}
"othergrouprank" => {
other_guild.get_or_insert_with(Default::default).rank =
val.into("other group rank")?;
}
"othergroupfightcost" => {
other_guild.get_or_insert_with(Default::default).attack_cost =
val.into("other group fighting cost")?;
}
"othergroupmember" => {
let names: Vec<_> = val.as_str().split(',').collect();
let og = other_guild.get_or_insert_with(Default::default);
og.members.resize_with(names.len(), Default::default);
for (m, n) in og.members.iter_mut().zip(names) {
m.name.set(n);
}
}
"othergroupdescription" => {
let guild = other_guild.get_or_insert_with(Default::default);
let (emblem, desc) =
val.as_str().split_once('§').unwrap_or(("", val.as_str()));
guild.emblem.update(emblem);
guild.description = from_sf_string(desc);
}
"othergroup" => {
other_guild
.get_or_insert_with(Default::default)
.update(val.as_str(), server_time)?;
}
"reward" => {
// This is the task reward, which you should already know
// from collecting
}
"gtdailypoints" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.guild_points_today = val.into("gtdaily").unwrap_or(0);
}
"gtchest" => {
// 2500/0/5000/1/7500/2/10000/0/12500/1/15000/2/17500/0/
// 20000/1/22500/2/25000/0/27500/1/30000/2/32500/0/35000/1/
// 37500/2/40000/0/42500/1/45000/2/47500/0/50000/1/57500/2/
// 65000/0/72500/1/80000/2/87500/0/95000/1/102500/2/110000/
// 0/117500/1/125000/2/137500/0/150000/1/162500/2/175000/0/
// 187500/1/200000/2/212500/0/225000/1/237500/2/250000/0/
// 272500/1/295000/2/317500/0/340000/1/362500/2/385000/0/
// 407500/1/430000/2/452500/0/475000/1
}
"gtraidparticipants" => {
let all: Vec<_> = val.as_str().split('/').collect();
let hellevator =
self.hellevator.active.get_or_insert_with(Default::default);
for floor in &mut hellevator.guild_raid_floors {
floor.today_assigned.clear();
}
#[allow(clippy::indexing_slicing)]
for part in all.chunks_exact(2) {
// The name of the guild member
let name = part[0];
// should be the dungeon they signed up for today
let val: usize = part
.cget(1, "hell raid part")
.ok()
.and_then(|a| a.parse().ok())
.unwrap_or(0);
if val > 0 {
if val > hellevator.guild_raid_floors.len() {
hellevator
.guild_raid_floors
.resize_with(val, Default::default);
}
if let Some(floor) =
hellevator.guild_raid_floors.get_mut(val - 1)
{
floor.today_assigned.push(name.to_string());
}
}
}
}
"gtraidparticipantsyesterday" => {
let all: Vec<_> = val.as_str().split('/').collect();
let hellevator =
self.hellevator.active.get_or_insert_with(Default::default);
for floor in &mut hellevator.guild_raid_floors {
floor.yesterday_assigned.clear();
}
#[allow(clippy::indexing_slicing)]
for part in all.chunks_exact(2) {
// The name of the guild member
let name = part[0];
// should be the dungeon they signed up for today
let val: usize = part
.cget(1, "hell raid part yd")
.ok()
.and_then(|a| a.parse().ok())
.unwrap_or(0);
if val > 0 {
if val > hellevator.guild_raid_floors.len() {
hellevator
.guild_raid_floors
.resize_with(val, Default::default);
}
if let Some(floor) =
hellevator.guild_raid_floors.get_mut(val - 1)
{
floor.yesterday_assigned.push(name.to_string());
}
}
}
}
"gtrank" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.guild_rank = val.into("gt rank").unwrap_or(0);
}
"gtrankingmax" => {
self.hall_of_fames.hellevator_total =
val.into("gt rank max").ok();
}
"gtbracketlist" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.brackets =
val.into_list("gtbracketlist").unwrap_or_default();
}
"gtraidfights" => {
let data: Vec<i64> =
val.into_list("gt raids").unwrap_or_default();
let hellevator =
self.hellevator.active.get_or_insert_with(Default::default);
hellevator.guild_raid_signup_start = data
.cstget(0, "h raid signup start", server_time)?
.unwrap_or_default();
hellevator.guild_raid_start = data
.cstget(1, "h raid next attack", server_time)?
.unwrap_or_default();
let start = data.skip(2, "hellevator_fights")?;
let floor_count = start.len() / 5;
if floor_count > hellevator.guild_raid_floors.len() {
hellevator
.guild_raid_floors
.resize_with(floor_count, Default::default);
}
#[allow(clippy::indexing_slicing)]
for (data, floor) in
start.chunks_exact(5).zip(&mut hellevator.guild_raid_floors)
{
// FIXME: What are these?
floor.today = data[1];
floor.yesterday = data[2];
floor.point_reward =
data.csiget(3, "floor t-reward", 0).unwrap_or(0);
floor.silver_reward =
data.csiget(4, "floor c-reward", 0).unwrap_or(0);
}
}
"gtmonsterreward" => {
let data: Vec<i64> =
val.into_list("gt m reward").unwrap_or_default();
let hellevator =
self.hellevator.active.get_or_insert_with(Default::default);
hellevator.monster_rewards.clear();
for chunk in data.chunks_exact(3) {
let raw_typ = chunk.cget(0, "gt monster reward typ")?;
if raw_typ <= 0 {
continue;
}
let one = chunk
.csiget(1, "gt monster reward typ", 0)
.unwrap_or(0);
if one != 0 {
warn!("hellevator monster t: {one}");
}
let typ = HellevatorMonsterRewardTyp::parse(raw_typ);
let amount: u64 =
chunk.csiget(2, "gt monster reward amount", 0)?;
hellevator
.monster_rewards
.push(HellevatorMonsterReward { typ, amount });
}
}
"gtdailyreward" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.rewards_today = HellevatorDailyReward::parse(
&val.into_list("hdrtd").unwrap_or_default(),
);
}
"gtdailyrewardnext" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.rewards_next = HellevatorDailyReward::parse(
&val.into_list("hdrnd").unwrap_or_default(),
);
}
"gtdailyrewardyesterday" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.rewards_yesterday = HellevatorDailyReward::parse(
&val.into_list("hdryd").unwrap_or_default(),
);
}
"gtdailyrewardclaimed" => {
if let Some(hellevator) = self.hellevator.active.as_mut() {
// This response key is sent when either yesterday's or
// today's daily reward was claimed. To check whether
// yesterday's daily reward was claimed, we check if
// "gtdailyreward" is missing in the response, since it
// is only included if today's daily reward was claimed.
if !all_values.contains_key("gtdailyreward") {
// The game doesn't update this value itself, so we
// do it manually.
hellevator.rewards_yesterday = None;
}
}
}
"gtranking" => {
self.hall_of_fames.hellevator = val
.as_str()
.split(';')
.filter(|a| !a.is_empty())
.map(|chunk| chunk.split(',').collect())
.flat_map(|chunk: Vec<_>| -> Result<_, SFError> {
Ok(HallOfFameHellevator {
rank: chunk.cfsuget(0, "hh rank")?,
name: chunk.cget(1, "hh name")?.to_string(),
tokens: chunk.cfsuget(2, "hh tokens")?,
})
})
.collect();
}
"gtpreviewreward" => {
// TODO: these are the previews of the rewards per rank
// 1:17/0/1/16/0/1/8/1/64200/9/1/96300/4/1/3201877800/,2:18/
// 0/1/16/0/1/8/1/64200/9/1/96300/4/1/3201877800/,3:19/0/1/
// 16/0/1/8/1/64200/9/1/96300/4/1/3201877800/,4:16/0/1/8/1/
// 61632/9/1/92448/4/1/3041783910/,5:16/0/1/8/1/59064/9/1/
// 88596/4/1/2881690020/,6:16/0/1/8/1/56496/9/1/84744/4/1/
// 2721596130/,7:16/0/1/8/1/53928/9/1/80892/4/1/2561502240/,
// 8:16/0/1/8/1/51360/9/1/77040/4/1/2401408350/,9:16/0/1/8/
// 1/48792/9/1/73188/4/1/2241314460/,10:16/0/1/8/1/46224/9/
// 1/69336/4/1/2241314460/,11:16/0/1/8/1/43656/9/1/65484/4/
// 1/2081220570/,12:16/0/1/8/1/41088/9/1/61632/4/1/
// 2081220570/,13:16/0/1/8/1/38520/9/1/57780/4/1/1921126680/
// ,14:16/0/1/8/1/35952/9/1/53928/4/1/1921126680/,15:16/0/1/
// 8/1/33384/9/1/50076/4/1/1761032790/,16:16/0/1/8/1/30816/
// 9/1/46224/4/1/1761032790/,17:8/1/28248/9/1/42372/4/1/
// 1600938900/,18:8/1/25680/9/1/38520/4/1/1600938900/,19:4/
// 1/1440845010/,20:4/1/1280751120/,21:4/1/1120657230/,22:4/
// 1/960563340/,23:4/1/800469450/,24:4/1/640375560/,25:4/1/
// 480281670/,
}
"gtmonster" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.current_monster = HellevatorMonster::parse(
&val.into_list("h monster").unwrap_or_default(),
)
.ok();
}
"gtbonus" => {
self.hellevator
.active
.get_or_insert_with(Default::default)
.daily_treat_bonus = val
.into_list("gt bonus")
.and_then(|a| HellevatorTreatBonus::parse(&a))
.ok();
}
"pendingrewards" => {
let vals: Vec<_> = val.as_str().split('/').collect();
self.mail.claimables = vals
.chunks_exact(6)
.flat_map(|chunk| -> Result<ClaimableMail, SFError> {
let start = chunk.cfsuget(4, "p reward start")?;
let end = chunk.cfsuget(5, "p reward end")?;
let status = match chunk.cget(1, "p read")? {
"0" => ClaimableStatus::Unread,
"1" => ClaimableStatus::Read,
"2" => ClaimableStatus::Claimed,
x => {
warn!("Unknown claimable status: {x}");
ClaimableStatus::Claimed
}
};
Ok(ClaimableMail {
typ: FromPrimitive::from_i64(
chunk.cfsuget(2, "claimable typ")?,
)
.unwrap_or_default(),
msg_id: chunk.cfsuget(0, "msg_id")?,
status,
name: chunk.cget(3, "reward code")?.to_string(),
received: server_time
.convert_to_local(start, "p start"),
claimable_until: server_time
.convert_to_local(end, "p end"),
})
})
.collect();
}
"pendingrewardressources" => {
let vals: Vec<i64> =
val.into_list("pendingrewardressources")?;
self.mail
.open_claimable
.get_or_insert_with(Default::default)
.resources = vals
.chunks_exact(2)
.flat_map(|chunk| -> Result<Reward, SFError> {
Ok(Reward {
typ: RewardType::parse(chunk.cget(0, "c typ")?),
amount: chunk.csiget(1, "c amount", 1)?,
})
})
.collect();
}
"pendingreward" => {
let vals: Vec<i64> = val.into_list("pending item")?;
self.mail
.open_claimable
.get_or_insert_with(Default::default)
.items = vals
.chunks_exact(ITEM_PARSE_LEN)
.flat_map(|a|
// Might be broken
Item::parse(a, server_time))
.flatten()
.collect();
}
"fightablegroups" => {
self.guild
.get_or_insert_default()
.update_fightable_targets(val.as_str())?;
}
"adventscalendar" => {
let vals: Vec<i64> = val.into_list("advent door")?;
self.specials.advent_calendar = match vals.first() {
Some(0) | None => None,
_ => Reward::parse(&vals).ok(),
};
}
"fortresschances" => {
// chances for different gems to drop in the gem mine / 100
// big/medium/small/orange/black/others
// 3334/3333/3333/0/1700/8300
}
"deedsandtitlesplayersave" => {
// The deeds of glory of the player
// rank?/110/3199/14/4/0/0/0/0/1/118/0/119/0/94/0/0/0/0/0/0/
// 0
}
"deedshelves" => {
// deedshelves (subkey => 1)
// 1
}
"fortressstorage" => {
self.fortress.get_or_insert_default().update_resources(
&val.into_list("ft resources")?,
server_time,
)?;
}
"fortressunits" => {
self.fortress
.get_or_insert_default()
.update_units(&val.into_list("ft units")?, server_time)?;
}
"fortress" => {
self.fortress
.get_or_insert_default()
.update(&val.into_list("fortress")?, server_time)?;
}
"wheel" => {
let data: Vec<i64> = val.into_list("wheel")?;
// [0] => 2 ??
self.specials.wheel.spins_today =
data.csiget(1, "lucky turns", 0)?;
self.specials.wheel.next_free_spin =
data.cstget(2, "next lucky turn", server_time)?;
}
"dice" => {
let data: Vec<i64> = val.into_list("dice")?;
self.tavern.dice_game.next_free =
data.cstget(0, "dice next", server_time)?;
self.tavern.dice_game.remaining =
data.csiget(1, "rem dice games", 0)?;
}
"charactergroup" => {
let data: Vec<i64> = val.into_list("c group")?;
let guild = self.guild.get_or_insert_with(Default::default);
guild.own_treasure_skill =
data.csiget(0, "own treasure skill", 0)?;
guild.own_instructor_skill =
data.csiget(1, "own instruction skill", 0)?;
guild.hydra.next_battle =
data.cstget(2, "pet battle", server_time)?;
guild.hydra.remaining_fights =
data.csiget(3, "remaining pet battles", 0)?;
guild.own_pet_lvl = data.csiget(4, "own pet lvl", 0)?;
guild.joined = data.cstget(5, "guild joined", server_time)?;
// [6] => ????
}
"arena" => {
let data: Vec<i64> = val.into_list("arena")?;
self.arena.next_free_fight =
data.cstget(0, "next battle time", server_time)?;
self.arena.fights_for_xp =
data.csiget(1, "arena xp fights", 0)?;
for (idx, val) in self.arena.enemy_ids.iter_mut().enumerate() {
*val = data.csiget(2 + idx, "arena enemy id", 0)?;
}
// [5] => ??
}
"ownplayersavepotions" => {
let data: Vec<i64> = val.into_list("potions")?;
self.character.active_potions =
items::parse_active_potions(&data, server_time);
}
"arcanetoilet" => {
let data: Vec<i64> = val.into_list("toilet")?;
// Toilet remains none as long as its level is 0
let toilet_lvl = data.cget(0, "toilet lvl")?;
if toilet_lvl > 0 {
self.tavern
.toilet
.get_or_insert_with(Default::default)
.update(&data, server_time)?;
}
}
"vipstatus" => {
other_player.get_or_insert_default().is_vip =
val.as_str() != "0";
}
"characterstatus" => {
let data: Vec<i64> = val.into_list("char status")?;
self.tavern.current_action = CurrentAction::parse(
data.cget(1, "action id")?,
data.cget(2, "action sec")?,
data.cstget(3, "current action time", server_time)?,
);
// NOTE: [4] contains the start
self.tavern.beer_max = data.csiget(5, "beer total", 0)?;
self.tavern.thirst_for_adventure_sec =
data.csiget(6, "remaining ALU", 0)?;
self.tavern.beer_drunk =
data.csiget(7, "beer drunk count", 0)?;
self.specials.calendar.collected =
data.csiget(8, "calendar collected", 245)?;
self.specials.calendar.next_possible =
data.cstget(9, "calendar next", server_time)?;
// 0
// 0
// 0
// 0
// 0
// 1513 // was [15]
// 1541087831 // acc creation time?
// 0
// 0
// 0
self.pets
.get_or_insert_with(Default::default)
.next_free_exploration =
data.cstget(20, "pet next free exp", server_time)?;
self.dungeons.next_free_fight =
data.cstget(21, "dungeon timer", server_time)?;
if let Some(start) =
data.cstget(22, "dungeon timer", server_time)?
{
self.legendary_dungeon
.active
.get_or_insert_default()
.healing_start = Some(start);
}
// 0
// 1
// 0
// 0
// 0
// 0
// 0
// 0
// 0
}
"ownplayersavecharacter" => {
let data: Vec<i64> = val.into_list("char save")?;
// 1482984989 // creation time? secret id?
self.character.player_id = data.csiget(1, "player id", 0)?;
// 0
self.character.level =
data.csimget(3, "level", 0, |a| a & 0xFFFF)?;
self.character.experience = data.csiget(4, "experience", 0)?;
self.character.next_level_xp =
data.csiget(5, "xp to next lvl", 0)?;
self.character.honor = data.csiget(6, "honor", 0)?;
self.character.rank = data.csiget(7, "rank", 0)?;
self.character.portrait =
Portrait::parse(data.skip(8, "portrait")?)
.unwrap_or_default();
///// Portrait
// 4
// 206
// 203
// 2
// 0
// 2
// 7
// 2
// 0
// 0
self.character.race = data.cfpuget(18, "char race", |a| a)?;
// 2
// ////
self.character.class =
data.cfpuget(20, "character class", |a| a - 1)?;
self.character.mount =
data.cfpget(21, "character mount", |a| a & 0xFF)?;
// 0
self.character.armor = data.csiget(23, "total armor", 0)?;
self.character.min_damage = data.csiget(24, "min damage", 0)?;
self.character.max_damage = data.csiget(25, "max damage", 0)?;
self.guild
.get_or_insert_with(Default::default)
.portal
.damage_bonus =
data.cimget(26, "portal dmg bonus", |a| a)?;
// 4280492 ??
self.dungeons
.portal
.get_or_insert_with(Default::default)
.player_hp_bonus =
data.csimget(28, "portal hp bonus", 0, |a| a)?;
self.character.mount_end =
data.cstget(29, "mount end", server_time)?;
update_enum_map(
&mut self.character.attribute_basis,
data.skip(30, "char attr basis")?,
);
update_enum_map(
&mut self.character.attribute_additions,
data.skip(35, "char attr adds")?,
);
update_enum_map(
&mut self.character.attribute_times_bought,
data.skip(40, "char attr tb")?,
);
// 0
// 0
// 0
// 0
// 1
// 17
// 0
// 0
// 0
// 66
// 0
// 7
// 18
// 0
// 0
// 0
// 0
// 0
// 0
// 0
// 80315 // guild_id ?
// 12122 // sb count
// 0
// 31
// 15 // gladiators
}
"adventure" => {
let data: Vec<i64> = val.into_list("char save")?;
// 198 - Might be the person to give you the quest?
// 198 - ??
for (slice, quest) in data
.skip(2, "quests")?
.chunks_exact(7)
.zip(&mut self.tavern.quests)
{
quest.update(slice)?;
}
}
"events" => {
// Information about the currently ongoing major event
// (I think)
}
// Legendary Dungeons
"iadungeonchances" => {
// IDK
}
"iadungeontime" => {
let dungeons = &mut self.legendary_dungeon;
let vals: Vec<i64> = val.into_list("iadungeontime")?;
dungeons.theme = vals.cfpget(0, "ld theme", |x| x)?;
dungeons.start = vals.cstget(1, "ld start", server_time)?;
dungeons.end = vals.cstget(2, "ld end", server_time)?;
dungeons.close = vals.cstget(3, "ld closes", server_time)?;
}
"iadungeonstatstotal" => {
let dungeons =
self.legendary_dungeon.active.get_or_insert_default();
let data: Vec<i64> = val.into_list("iadungeonstatstotal")?;
dungeons.total_stats = TotalStats::parse(&data)?;
}
"iadungeonstats" => {
let dungeons =
self.legendary_dungeon.active.get_or_insert_default();
let data = val.into_list("iadungeonstats")?;
dungeons.stats = Stats::parse(&data).unwrap_or_default();
}
"iadungeon" => {
let data: Vec<i64> = val.into_list("iadungeon")?;
let dungeons =
self.legendary_dungeon.active.get_or_insert_default();
dungeons.update(&data)?;
if !all_values.contains_key("iapendingitems") {
dungeons.pending_items.clear();
}
}
"iapendingitems" => {
let dungeons =
self.legendary_dungeon.active.get_or_insert_default();
dungeons.pending_items.clear();
let data: Vec<i64> = val.into_list("iapendingitems")?;
let amount: i64 = data.cget(0, "pending amount")?;
if amount < 1 {
return Ok(());
}
for slice in
data.skip(1, "ld items")?.chunks_exact(ITEM_PARSE_LEN)
{
let Some(item) = Item::parse(slice, server_time)? else {
warn!("Could not parse pending ld item");
continue;
};
dungeons.pending_items.push(item);
}
}
"ialootitem" => {
// The stuff, that was looted after a fight
}
"iamerchant" => {
let data: Vec<i64> = val.into_list("iamerchant")?;
self.legendary_dungeon
.active
.get_or_insert_default()
.merchant_offers = data
.chunks_exact(3)
.flat_map(MerchantOffer::parse)
.flatten()
.collect();
}
"iadungeon20cost" => {
self.legendary_dungeon
.active
.get_or_insert_default()
.heal_quarter_cost = val.into("iadungeon20cost")?;
}
"iadungeonsoulstones" => {
let dungeons =
self.legendary_dungeon.active.get_or_insert_default();
let data: Vec<i64> = val.into_list("iamerchant")?;
let mut chunks = data.chunks_exact(6);
dungeons.active_gems = chunks
.by_ref()
.take(3)
.flat_map(GemOfFate::parse)
.flatten()
.collect();
dungeons.available_gems =
chunks.flat_map(GemOfFate::parse).flatten().collect();
}
"iamap" => {
// 25/-5159/1/-315/
// 25/-5160/1/-315/
// 25/-5172/1/-315/
// 25/-5168/1/-315
// Parsing this sucks. The first value is amount of levels
// and the 2. is monster_id, so far so good. The next 2
// values are weird though. If you change -315 to 315, it
// counts as having visited the shop one, but I have no
// idea how to further improve that. In addition, you can
// inc. 1 in steps of 4 to inc. max shops by one... but
// that breaks the total count of floors?? It is also
// unclear how effect & name can be changed, might be
// dependant on `LegendaryDungeonsEventTheme`? Whatever is
// may be, I don't think we really need this, as long as
// it does not contain the gems
}
"otherplayerfortressinfo" => {
other_player
.get_or_insert_default()
.update_fortress(&val.into_list("other ft")?)?;
}
x if x.contains("average") && x.ends_with("level") => {
// We do not care about avg. item lvl
}
// This is the extra bonus effect all treats get that day
x if x.contains("dungeonenemies") => {
// I `think` we do not need this
}
x if x.starts_with("attbonus") => {
// This is always 0s, so I have no idea what this could be
}
x => {
warn!("Update ignored {x} -> {val:?}");
}
}
Ok(())
}
}
/// Gets the number if the fight header, so for `fight4` it would return 4 and
/// for fight it would return 1
fn fight_no_from_header(header_name: &str) -> usize {
let number_str =
header_name.trim_start_matches(|a: char| !a.is_ascii_digit());
let id: usize = number_str.parse().unwrap_or(1);
id.max(1)
}
/// Stores the time difference between the server and the client to parse the
/// response timestamps and to always be able to know the servers (timezoned)
/// time without sending new requests to ask it
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ServerTime(i64);
impl ServerTime {
/// Converts the raw timestamp from the server to the local time.
#[must_use]
pub(crate) fn convert_to_local(
self,
timestamp: i64,
name: &str,
) -> Option<DateTime<Local>> {
if matches!(timestamp, 0 | -1 | 1 | 11) {
// For some reason these can be bad
return None;
}
if !(1_000_000_000..=3_000_000_000).contains(×tamp) {
warn!("Weird time stamp: {timestamp} for {name}");
return None;
}
DateTime::from_timestamp(timestamp - self.0, 0)?
.naive_utc()
.and_local_timezone(Local)
.latest()
}
/// The current time of the server in their time zone (whatever that might
/// be). This uses the system time and calculates the offset to the
/// servers time, so this is NOT the time at the last request, but the
/// actual current time of the server.
#[must_use]
pub fn current(&self) -> NaiveDateTime {
Local::now().naive_local() + Duration::seconds(self.0)
}
#[must_use]
pub fn next_midnight(&self) -> std::time::Duration {
let current = self.current();
let tomorrow = current.date() + Duration::days(1);
let tomorrow = NaiveDateTime::from(tomorrow);
let sec_until_midnight =
(tomorrow - current).to_std().unwrap_or_default().as_secs();
// Time stuff is weird so make sure this never skips a day + actual
// amount
std::time::Duration::from_secs(sec_until_midnight % (60 * 60 * 24))
}
}
// https://stackoverflow.com/a/59955929
trait StringSetExt {
fn set(&mut self, s: &str);
}
impl StringSetExt for String {
/// Replace the contents of a string with a string slice. This is basically
/// `self = s.to_string()`, but without the deallication of self +
/// allocation of s for that
fn set(&mut self, s: &str) {
self.replace_range(.., s);
}
}
/// The cost of something
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct NormalCost {
/// The amount of silver something costs
pub silver: u64,
/// The amount of mushrooms something costs
pub mushrooms: u16,
}