-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathitems.rs
293 lines (257 loc) · 8.49 KB
/
items.rs
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
use crate::{Client, Code, RoliError};
use reqwest::header;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
const ITEM_DETAILS_API: &str = "https://www.rolimons.com/itemapi/itemdetails";
/// Represents the demand of an item.
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize, Copy,
)]
pub enum Demand {
/// The demand of the item is unassigned.
#[default]
Unassigned,
/// The demand of the item is terrible.
Terrible,
/// The demand of the item is low.
Low,
/// The demand of the item is normal.
Normal,
/// The demand of the item is high.
High,
/// The demand of the item is amazing.
Amazing,
}
/// Represents the trend of an item.
#[derive(
Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize, Copy,
)]
pub enum Trend {
#[default]
/// The trend of the item is unassigned.
Unassigned,
/// The trend of the item is lowering.
Lowering,
/// The trend of the item is unstable.
Unstable,
/// The trend of the item is stable.
Stable,
/// The trend of the item is raising.
Raising,
/// The trend of the item is fluctuating.
Fluctuating,
}
/// Struct representing details of an item (using Rolimons information).
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
pub struct ItemDetails {
/// The ID of the item.
pub item_id: u64,
/// The name of the item.
pub item_name: String,
/// An optional acronym for the item.
pub acronym: Option<String>,
/// The recent average price of the item.
pub rap: u64,
/// Whether the item is valued or not.
pub valued: bool,
/// The value of the item.
pub value: u64,
/// The demand of the item.
pub demand: Demand,
/// The trend of the item.
pub trend: Trend,
/// Whether the item is projected or not.
pub projected: bool,
/// Whether the item is hyped or not.
pub hyped: bool,
/// Whether the item is rare or not.
pub rare: bool,
}
/// Used for holding the raw json response from <https://www.rolimons.com/itemapi/itemdetails>.
#[derive(Default, Serialize, Deserialize)]
struct AllItemDetailsResponse {
success: bool,
item_count: u64,
items: HashMap<String, Vec<Code>>,
}
impl ItemDetails {
fn from_raw(item_id: u64, codes: Vec<Code>) -> Result<Self, RoliError> {
let item_name = codes[0].to_string();
let acronym = {
if codes[1].to_string().is_empty() {
None
} else {
Some(codes[1].to_string())
}
};
// For these lines below, we return a ItemsError::MalformedResponse if we cannot parse
// the value to an i64.
let rap = codes[2].to_i64()? as u64;
let valued = codes[3].to_i64()? != -1;
let value = codes[4].to_i64()? as u64;
let demand = match codes[5].to_i64()? {
-1 => Demand::Unassigned,
0 => Demand::Terrible,
1 => Demand::Low,
2 => Demand::Normal,
3 => Demand::High,
4 => Demand::Amazing,
_ => return Err(RoliError::MalformedResponse),
};
let trend = match codes[6].to_i64()? {
-1 => Trend::Unassigned,
0 => Trend::Lowering,
1 => Trend::Unstable,
2 => Trend::Stable,
3 => Trend::Raising,
4 => Trend::Fluctuating,
_ => return Err(RoliError::MalformedResponse),
};
let projected = match codes[7].to_i64()? {
1 => true,
-1 => false,
_ => return Err(RoliError::MalformedResponse),
};
let hyped = match codes[8].to_i64()? {
1 => true,
-1 => false,
_ => return Err(RoliError::MalformedResponse),
};
let rare = match codes[9].to_i64()? {
1 => true,
-1 => false,
_ => return Err(RoliError::MalformedResponse),
};
Ok(ItemDetails {
item_id,
item_name,
acronym,
rap,
valued,
value,
demand,
trend,
projected,
hyped,
rare,
})
}
}
impl AllItemDetailsResponse {
fn into_vec(self) -> Result<Vec<ItemDetails>, RoliError> {
let mut item_details_vec = Vec::new();
for (item_id_string, codes) in self.items {
let item_id = match item_id_string.parse() {
Ok(x) => x,
Err(_) => return Err(RoliError::MalformedResponse),
};
let item_details = ItemDetails::from_raw(item_id, codes)?;
item_details_vec.push(item_details);
}
Ok(item_details_vec)
}
}
impl Client {
/// A wrapper for <https://www.rolimons.com/itemapi/itemdetails>.
///
/// Does not require authentication.
///
/// # Warning
/// Although the rate limit is 10 requests per minute, the owner will ban people who continually abuse this api.
/// The data this endpoint is serving is cached on the server for 60 seconds, so there is no point in spamming it anyways.
///
/// # Example
/// ```no_run
/// # use std::error::Error;
/// #
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn Error>> {
/// let client = roli::ClientBuilder::new().build();
/// let all_item_details = client.all_item_details().await?;
/// #
/// # Ok(())
/// # }
/// ```
pub async fn all_item_details(&self) -> Result<Vec<ItemDetails>, RoliError> {
let request_result = self
.reqwest_client
.get(ITEM_DETAILS_API)
.header(header::USER_AGENT, crate::USER_AGENT)
.send()
.await;
match request_result {
Ok(response) => {
let status_code = response.status().as_u16();
match status_code {
200 => {
let raw = match response.json::<AllItemDetailsResponse>().await {
Ok(x) => x,
Err(_) => return Err(RoliError::MalformedResponse),
};
if !raw.success {
return Err(RoliError::RequestReturnedUnsuccessful);
}
let item_details = raw.into_vec()?;
Ok(item_details)
}
429 => Err(RoliError::TooManyRequests),
500 => Err(RoliError::InternalServerError),
_ => Err(RoliError::UnidentifiedStatusCode(status_code)),
}
}
Err(e) => Err(RoliError::ReqwestError(e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_raw_valid_data() {
let item_id = 123;
let codes = vec![
Code::String("Test item name".to_string()),
Code::String("TI".to_string()),
Code::Integer(100),
Code::Integer(1),
Code::Integer(200),
Code::Integer(3),
Code::Integer(4),
Code::Integer(1),
Code::Integer(1),
Code::Integer(1),
];
let result = ItemDetails::from_raw(item_id, codes);
assert!(result.is_ok());
let item_details = result.unwrap();
assert_eq!(item_details.item_id, item_id);
assert_eq!(item_details.item_name, "Test item name");
assert_eq!(item_details.acronym, Some("TI".to_string()));
assert_eq!(item_details.rap, 100);
assert!(item_details.valued);
assert_eq!(item_details.value, 200);
assert_eq!(item_details.demand, Demand::High);
assert_eq!(item_details.trend, Trend::Fluctuating);
assert!(item_details.projected);
assert!(item_details.hyped);
assert!(item_details.rare);
}
#[test]
fn test_from_raw_invalid_data() {
let item_id = 123;
let codes = vec![
Code::String("Test item name".to_string()),
Code::String("TI".to_string()),
Code::String("Invalid".to_string()),
Code::Integer(-1),
Code::Integer(200),
Code::Integer(3),
Code::Integer(4),
Code::Integer(1),
Code::Integer(1),
Code::Integer(1),
];
let result = ItemDetails::from_raw(item_id, codes);
assert!(result.is_err());
}
}