beatsaver-rs 0.2.0

A Rust library for interacting with the beatsaver.com api
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
//! # Map
//!
//! This module contains structures that correspond to the map API responses
//!
//! [API documentation here](https://docs.beatsaver.com/responses/beatmap.html)
use crate::BeatSaverUser;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// This structure specifies whether or not a difficulty exists in the map
///
/// Note: `false` here corresponds with `None` in [MapDifficultyCharacteristics][crate::map::MapDifficultyCharacteristics]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MapDifficulties {
    /// `true` if easy map is available
    pub easy: bool,
    /// `true` if normal map is available
    pub normal: bool,
    /// `true` if hard map is available
    pub hard: bool,
    /// `true` if expert map is available
    pub expert: bool,
    /// `true` if expert+ map is available
    #[serde(alias = "expertPlus")]
    pub expert_plus: bool,
}

/// Characteristics of a map difficulty level
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MapDifficltyCharacteristic {
    /// Duration of the difficulty beatmap
    pub duration: f32,
    /// TODO: What does this represent?
    pub length: usize,
    /// TODO: What does this represent?
    pub njs: f32,
    /// TODO: What does this represent?
    #[serde(alias = "njsOffset")]
    pub njs_offset: f32,
    /// Number of bombs in the difficulty beatmap
    pub bombs: usize,
    /// Number of notes in the difficulty beatmap
    pub notes: usize,
    /// Number of walls in the difficulty beatmap
    pub obstacles: usize,
}

/// Characteristics for each difficulty level
///
/// Note: A `None` characteristic will correspond with `false` in [MapDifficulties][crate::map::MapDifficulties]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MapDifficultyCharacteristics {
    /// Easy difficulty beatmap characteristic
    pub easy: Option<MapDifficltyCharacteristic>,
    /// Normal difficulty beatmap characteristic
    pub normal: Option<MapDifficltyCharacteristic>,
    /// Hard difficulty beatmap characteristic
    pub hard: Option<MapDifficltyCharacteristic>,
    /// Expert difficulty beatmap characteristic
    pub expert: Option<MapDifficltyCharacteristic>,
    /// Expert+ difficulty beatmap characteristic
    #[serde(alias = "expertPlus")]
    pub expert_plus: Option<MapDifficltyCharacteristic>,
}

/// A named characteristic group
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MapCharacteristics {
    /// Included difficulties
    pub difficulties: MapDifficultyCharacteristics,
    /// Characteristic group name
    pub name: String,
}

/// Metadata about a given map
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MapMetadata {
    /// Included difficulties
    pub difficulties: MapDifficulties,
    /// Song duration
    pub duration: usize,
    /// Automapper name
    ///
    /// If map was not autogenerated, this will be `None`
    pub automapper: Option<String>,
    /// Map characteristic groups
    pub characteristics: Vec<MapCharacteristics>,
    /// Name of the author of the beatmap
    #[serde(alias = "levelAuthorName")]
    pub level_author: String,
    /// Name of the author of the song
    #[serde(alias = "songAuthorName")]
    pub song_author: String,
    /// Name of the map's song
    #[serde(alias = "songName")]
    pub song_name: String,
    /// Subname of the map's song
    #[serde(alias = "songSubName")]
    pub song_sub_name: String,
    /// Song beats per minute
    pub bpm: f32,
}

/// Collected BeatSaver statistics for the map
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MapStats {
    /// Number of times map has been downloaded
    pub downloads: usize,
    /// Number of times map has been played
    pub plays: usize,
    /// Number of times map has been downvoted
    #[serde(alias = "downVotes")]
    pub downvotes: usize,
    /// Number of times map has been upvoted
    #[serde(alias = "upVotes")]
    pub upvotes: usize,
    /// Rough difficulty rating of the map
    pub heat: f32,
    /// Average rating of the map
    pub rating: f32,
}

/// Information about a map
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Map {
    /// Map metadata
    pub metadata: MapMetadata,
    /// Map statistics
    pub stats: MapStats,
    /// Description of the map
    pub description: String,
    /// ID assigned to the map (e.g. `5cff620c48229f7d88fc60df`)
    ///
    /// Note: Maps are referenced through the `key` and `hash` fields, not this one
    #[serde(alias = "_id")]
    pub id: String,
    /// Key assigned to the map (e.g. `1234`)
    ///
    /// Note: This is one of the values used to index maps
    pub key: String,
    /// Name given to the map
    pub name: String,
    /// User who uploaded the map
    pub uploader: BeatSaverUser,
    /// Hash of the map
    /// Note: This is one of the values used to index maps
    pub hash: String,
    /// Timestamp of map upload
    pub uploaded: DateTime<Utc>,
    #[serde(alias = "directDownload")]
    /// CDN URL to download the map from
    ///
    /// Note: This is a relative path, use the following code to get a full url:
    /// ```no_run
    /// # #[cfg(feature = "reqwest_backend")]
    /// # use beatsaver_rs::client::BeatSaverReqwest;
    /// # #[cfg(feature = "surf_backend")]
    /// # use beatsaver_rs::client::BeatSaverSurf;
    /// # #[cfg(feature = "async")]
    /// # use beatsaver_rs::BeatSaverApiAsync;
    /// # use std::convert::TryInto;
    /// use beatsaver_rs::BEATSAVER_URL;
    ///
    /// # #[cfg(feature = "async")]
    /// # async fn example() {
    /// #     #[cfg(feature = "reqwest_backend")]
    /// #     let client = BeatSaverReqwest::new();
    /// #     #[cfg(feature = "surf_backend")]
    /// #     let client = BeatSaverSurf::new();
    /// #     let map = client.map(&"1".try_into().unwrap()).await.unwrap();
    /// let full_url = BEATSAVER_URL.join(map.direct_download.as_str()).unwrap();
    /// # }
    /// # #[cfg(all(feature = "sync", feature = "ureq_backend"))]
    /// # mod sync {
    /// #     use beatsaver_rs::client::BeatSaverUreq;
    /// #     use beatsaver_rs::BEATSAVER_URL;
    /// #     use beatsaver_rs::BeatSaverApiSync;
    /// #     use std::convert::TryInto;
    /// #     fn info() {
    /// #         let client = BeatSaverUreq::new();
    /// #         let map = client.map(&"1".try_into().unwrap()).unwrap();
    /// #         let full_url = BEATSAVER_URL.join(map.direct_download.as_str()).unwrap();
    /// #     }
    /// # }
    /// ```
    pub direct_download: String,
    /// API URL to download the map from
    ///
    /// Note: This is a relative path, use the following code to get a full url:
    /// ```no_run
    /// # #[cfg(feature = "reqwest_backend")]
    /// # use beatsaver_rs::client::BeatSaverReqwest;
    /// # #[cfg(feature = "surf_backend")]
    /// # use beatsaver_rs::client::BeatSaverSurf;
    /// # #[cfg(feature = "async")]
    /// # use beatsaver_rs::BeatSaverApiAsync;
    /// # use std::convert::TryInto;
    /// use beatsaver_rs::BEATSAVER_URL;
    ///
    /// # #[cfg(feature = "async")]
    /// # async fn example() {
    /// #     #[cfg(feature = "reqwest_backend")]
    /// #     let client = BeatSaverReqwest::new();
    /// #     #[cfg(feature = "surf_backend")]
    /// #     let client = BeatSaverSurf::new();
    /// #     let map = client.map(&"1".try_into().unwrap()).await.unwrap();
    /// let full_url = BEATSAVER_URL.join(map.download.as_str()).unwrap();
    /// # }
    /// # #[cfg(all(feature = "sync", feature = "ureq_backend"))]
    /// # mod sync {
    /// #     use beatsaver_rs::client::BeatSaverUreq;
    /// #     use beatsaver_rs::BEATSAVER_URL;
    /// #     use beatsaver_rs::BeatSaverApiSync;
    /// #     use std::convert::TryInto;
    /// #     fn info() {
    /// #         let client = BeatSaverUreq::new();
    /// #         let map = client.map(&"1".try_into().unwrap()).unwrap();
    /// #         let full_url = BEATSAVER_URL.join(map.download.as_str()).unwrap();
    /// #     }
    /// # }
    /// ```
    #[serde(alias = "downloadURL")]
    pub download: String,
    /// Cover art URL
    ///
    /// Note: This is a relative path, use the following code to get a full url:
    /// ```no_run
    /// # #[cfg(feature = "reqwest_backend")]
    /// # use beatsaver_rs::client::BeatSaverReqwest;
    /// # #[cfg(feature = "surf_backend")]
    /// # use beatsaver_rs::client::BeatSaverSurf;
    /// # #[cfg(feature = "async")]
    /// # use beatsaver_rs::BeatSaverApiAsync;
    /// # use std::convert::TryInto;
    /// use beatsaver_rs::BEATSAVER_URL;
    ///
    /// # #[cfg(feature = "async")]
    /// # async fn example() {
    /// #     #[cfg(feature = "reqwest_backend")]
    /// #     let client = BeatSaverReqwest::new();
    /// #     #[cfg(feature = "surf_backend")]
    /// #     let client = BeatSaverSurf::new();
    /// #     let map = client.map(&"1".try_into().unwrap()).await.unwrap();
    /// let full_url = BEATSAVER_URL.join(map.cover.as_str()).unwrap();
    /// # }
    /// # #[cfg(all(feature = "sync", feature = "ureq_backend"))]
    /// # mod sync {
    /// #     use beatsaver_rs::client::BeatSaverUreq;
    /// #     use beatsaver_rs::BEATSAVER_URL;
    /// #     use beatsaver_rs::BeatSaverApiSync;
    /// #     use std::convert::TryInto;
    /// #     fn info() {
    /// #         let client = BeatSaverUreq::new();
    /// #         let map = client.map(&"1".try_into().unwrap()).unwrap();
    /// #         let full_url = BEATSAVER_URL.join(map.cover.as_str()).unwrap();
    /// #     }
    /// # }
    /// ```
    #[serde(alias = "coverURL")]
    pub cover: String,
}

#[cfg(test)]
mod tests {
    use crate::map::Map;
    use chrono::DateTime;
    use serde_json;

    #[test]
    fn test_map() {
        let data = r#"
        {
            "metadata": {
                "difficulties": {
                    "easy": false,
                    "normal": true,
                    "hard": true,
                    "expert":true,
                    "expertPlus":true
                },
                "duration": 0,
                "automapper": null,
                "characteristics": [{
                    "name":"Standard",
                    "difficulties": {
                        "easy": null,
                        "normal": {
                            "duration": 417,
                            "length": 195,
                            "bombs": 4,
                            "notes": 301,
                            "obstacles": 24,
                            "njs": 10,
                            "njsOffset": 0
                        },
                        "hard": {
                            "duration": 417,
                            "length": 195,
                            "bombs": 4,
                            "notes": 486,
                            "obstacles": 24,
                            "njs": 10,
                            "njsOffset": 0
                        },
                        "expert": {
                            "duration": 417.5,
                            "length": 195,
                            "bombs": 4,
                            "notes": 620,
                            "obstacles": 24,
                            "njs": 10,
                            "njsOffset": 0
                        },
                        "expertPlus": {
                            "duration": 417.5,
                            "length": 195,
                            "bombs": 0,
                            "notes": 894,
                            "obstacles": 0,
                            "njs": 12,
                            "njsOffset": 0
                        }
                    }
                }],
                "songName": "Shut Up and Dance",
                "songSubName": "WALK THE MOON",
                "songAuthorName": "BennyDaBeast",
                "levelAuthorName": "bennydabeast",
                "bpm":128
            },
            "stats": {
                "downloads": 418854,
                "plays": 558,
                "downVotes": 133,
                "upVotes": 10763,
                "heat": 395.8225333,
                "rating": 0.9580848467461356
            },
            "description": "Difficulties: Expert+ (Added 11/15), Expert, Hard, Normal\r\nYouTube Preview: https://youtu.be/x9hJbTlPQUY",
            "deletedAt": null,
            "_id": "5cff621148229f7d88fc77c9",
            "key": "2144",
            "name": "Shut Up and Dance - WALK THE MOON",
            "uploader": {
                "_id": "5cff0b7298cc5a672c84e98d",
                "username": "bennydabeast"
            },
            "uploaded": "2018-11-21T01:27:00.000Z",
            "hash": "89cf8bb07afb3c59ae7b5ac00337d62261c36fb4",
            "directDownload": "/cdn/2144/89cf8bb07afb3c59ae7b5ac00337d62261c36fb4.zip",
            "downloadURL": "/api/download/key/2144",
            "coverURL": "/cdn/2144/89cf8bb07afb3c59ae7b5ac00337d62261c36fb4.png"
        }"#;

        let v: Map = serde_json::from_str(data).unwrap();

        let difficulties = v.metadata.difficulties;
        assert_eq!(difficulties.easy, false);
        assert_eq!(difficulties.normal, true);
        assert_eq!(difficulties.hard, true);
        assert_eq!(difficulties.expert, true);
        assert_eq!(difficulties.expert_plus, true);

        assert_eq!(v.metadata.duration, 0);
        assert_eq!(v.metadata.automapper, None);

        assert_eq!(v.metadata.characteristics.len(), 1);
        let characteristics = &v.metadata.characteristics[0];
        assert_eq!(characteristics.name, "Standard");

        assert_eq!(characteristics.difficulties.easy, None);

        assert!(characteristics.difficulties.normal.is_some());
        let normal = characteristics.difficulties.normal.as_ref().unwrap();
        assert_eq!(normal.duration, 417f32);
        assert_eq!(normal.length, 195);
        assert_eq!(normal.bombs, 4);
        assert_eq!(normal.notes, 301);
        assert_eq!(normal.obstacles, 24);
        assert_eq!(normal.njs, 10f32);
        assert_eq!(normal.njs_offset, 0f32);

        assert!(characteristics.difficulties.hard.is_some());
        let hard = characteristics.difficulties.hard.as_ref().unwrap();
        assert_eq!(hard.duration, 417f32);
        assert_eq!(hard.length, 195);
        assert_eq!(hard.bombs, 4);
        assert_eq!(hard.notes, 486);
        assert_eq!(hard.obstacles, 24);
        assert_eq!(hard.njs, 10f32);
        assert_eq!(hard.njs_offset, 0f32);

        assert!(characteristics.difficulties.expert.is_some());
        let expert = characteristics.difficulties.expert.as_ref().unwrap();
        assert_eq!(expert.duration, 417.5f32);
        assert_eq!(expert.length, 195);
        assert_eq!(expert.bombs, 4);
        assert_eq!(expert.notes, 620);
        assert_eq!(expert.obstacles, 24);
        assert_eq!(expert.njs, 10f32);
        assert_eq!(expert.njs_offset, 0f32);

        assert!(characteristics.difficulties.expert_plus.is_some());
        let expert_plus = characteristics.difficulties.expert_plus.as_ref().unwrap();
        assert_eq!(expert_plus.duration, 417.5f32);
        assert_eq!(expert_plus.length, 195);
        assert_eq!(expert_plus.bombs, 0);
        assert_eq!(expert_plus.notes, 894);
        assert_eq!(expert_plus.obstacles, 0);
        assert_eq!(expert_plus.njs, 12f32);
        assert_eq!(expert_plus.njs_offset, 0f32);

        assert_eq!(v.metadata.song_name, "Shut Up and Dance");
        assert_eq!(v.metadata.song_sub_name, "WALK THE MOON");
        assert_eq!(v.metadata.song_author, "BennyDaBeast");
        assert_eq!(v.metadata.level_author, "bennydabeast");
        assert_eq!(v.metadata.bpm, 128f32);

        assert_eq!(v.stats.downloads, 418854);
        assert_eq!(v.stats.plays, 558);
        assert_eq!(v.stats.downvotes, 133);
        assert_eq!(v.stats.upvotes, 10763);
        assert_eq!(v.stats.heat, 395.8225333f32);
        assert_eq!(v.stats.rating, 0.9580848467461356f32);

        assert_eq!(v.description, "Difficulties: Expert+ (Added 11/15), Expert, Hard, Normal\r\nYouTube Preview: https://youtu.be/x9hJbTlPQUY");
        assert_eq!(v.key, "2144");
        assert_eq!(v.name, "Shut Up and Dance - WALK THE MOON");
        assert_eq!(v.uploader.id, "5cff0b7298cc5a672c84e98d");
        assert_eq!(v.uploader.username, "bennydabeast");
        assert_eq!(
            v.uploaded,
            DateTime::parse_from_rfc3339("2018-11-21T01:27:00.000Z").unwrap()
        );
        assert_eq!(v.hash, "89cf8bb07afb3c59ae7b5ac00337d62261c36fb4");
        assert_eq!(
            v.direct_download,
            "/cdn/2144/89cf8bb07afb3c59ae7b5ac00337d62261c36fb4.zip"
        );
        assert_eq!(v.download, "/api/download/key/2144");
        assert_eq!(
            v.cover,
            "/cdn/2144/89cf8bb07afb3c59ae7b5ac00337d62261c36fb4.png"
        );
    }
}