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
#[cfg(feature = "beatsaver")]
extern crate reqwest;
#[cfg(feature = "beatsaver")]
extern crate tempfile;
#[cfg(feature = "beatsaver")]
extern crate zip;

#[cfg(feature = "audio")]
extern crate ogg_metadata;

use difficulty::Difficulty;
use info::info::difficulty_beatmap_set::{
    difficulty_beatmap::DifficultyRank, BeatmapCharacteristic,
};
use info::Info;
use std::collections::HashMap;
use std::error::Error;
use std::path::Path;

#[cfg(feature = "beatsaver")]
use std::io;
#[cfg(feature = "beatsaver")]
use std::io::Read;
#[cfg(feature = "beatsaver")]
use std::time::Duration;

#[cfg(feature = "audio")]
use ogg_metadata::OggFormat;
#[cfg(feature = "audio")]
use std::fs::File;

#[cfg(feature = "beatsaver")]
#[cfg(feature = "audio")]
use std::io::{Seek, SeekFrom};

/// Contains types related to the difficulty files
pub mod difficulty;
/// Contains types related to the `info.dat` file
pub mod info;

type DifficultyHashMap = HashMap<BeatmapCharacteristic, HashMap<DifficultyRank, Difficulty>>;

/// Represents a Beat Saber map
#[derive(Debug)]
pub struct Beatmap {
    /// Beatmap info
    pub info: Info,
    /// Beatmap difficulty sets
    pub difficulties: DifficultyHashMap,
    /// BeatSaver key
    #[cfg(feature = "beatsaver")]
    pub key: Option<String>,
    /// Audio file length, in seconds
    #[cfg(feature = "audio")]
    pub length: f64,
}

impl Beatmap {
    #[cfg(feature = "audio")]
    fn calculate_ogg_length(formats: Vec<OggFormat>, mut length: f64) -> f64 {
        for format in formats {
            if let OggFormat::Vorbis(metadata) = format {
                length = (metadata.length_in_samples.unwrap_or(1) as f64
                    / metadata.sample_rate as f64)
                    / metadata.channels as f64;
                length *= 2.0;
                break;
            }
        }
        length
    }

    /// Returns a new Beatmap instance from an `info.dat` file
    pub fn from_file_dat(filename: &str) -> Result<Beatmap, Box<dyn Error>> {
        // Get Info from info.dat
        let info_contents = std::fs::read_to_string(filename)?;
        let info: Info = serde_json::from_str(&info_contents)?;

        // Get the directory containing the map
        let beatmap_dir = Path::new(filename).parent().unwrap_or(Path::new("."));

        let mut difficulties: DifficultyHashMap = HashMap::new();
        // For each characteristic, get the difficulty ranks
        for difficulty_beatmap_set in &info.difficulty_beatmap_sets {
            let mut sub_difficulties = HashMap::new();
            // For each difficulty rank, get the difficulty from its file
            for difficulty_beatmap in &difficulty_beatmap_set.difficulty_beatmaps {
                let difficulty_filename =
                    Path::new(beatmap_dir).join(&difficulty_beatmap.beatmap_filename);
                let difficulty_contents = std::fs::read_to_string(difficulty_filename)?;
                let difficulty: Difficulty = serde_json::from_str(&difficulty_contents)?;

                sub_difficulties.insert(difficulty_beatmap.difficulty_rank.clone(), difficulty);
            }

            difficulties.insert(
                difficulty_beatmap_set.beatmap_characteristic_name.clone(),
                sub_difficulties,
            );
        }

        // Calculate the audio file length
        #[cfg(feature = "audio")]
        let mut length = 0.0;
        #[cfg(feature = "audio")]
        {
            let audio_filename = Path::new(beatmap_dir).join(&info.song_filename);
            let mut audio_file = File::open(audio_filename)?;
            let formats = ogg_metadata::read_format(&mut audio_file)?;

            length = Beatmap::calculate_ogg_length(formats, length);
        }

        // Create the Beatmap and return it
        Ok(Beatmap {
            info,
            difficulties,
            #[cfg(feature = "beatsaver")]
            key: None,
            #[cfg(feature = "audio")]
            length,
        })
    }

    /// Returns a new Beatmap instance from a BeatSaver key
    #[cfg(feature = "beatsaver")]
    pub fn from_beatsaver_key(key: &str) -> Result<Beatmap, Box<dyn Error>> {
        // Download the file and store it temporarly
        let mut response = reqwest::Client::builder()
            .timeout(Duration::from_secs(120))
            .build()?
            .get(&format!("https://beatsaver.com/api/download/key/{}", key))
            .send()?;
        let mut temp_file = tempfile::tempfile()?;
        io::copy(&mut response, &mut temp_file)?;

        // Create the zip archive object
        let mut archive = zip::ZipArchive::new(temp_file)?;

        let info: Info = {
            // Get Info from info.dat
            let mut info_file = archive.by_name("info.dat")?;
            let mut info_contents = String::new();
            info_file.read_to_string(&mut info_contents)?;

            serde_json::from_str(&info_contents)?
        };

        let mut difficulties: DifficultyHashMap = HashMap::new();
        // For each characteristic, get the difficulty ranks
        for difficulty_beatmap_set in &info.difficulty_beatmap_sets {
            let mut sub_difficulties = HashMap::new();
            // For each difficulty rank, get the difficulty from its file
            for difficulty_beatmap in &difficulty_beatmap_set.difficulty_beatmaps {
                let mut difficulty_file = archive.by_name(&difficulty_beatmap.beatmap_filename)?;
                let mut difficulty_contents = String::new();
                difficulty_file.read_to_string(&mut difficulty_contents)?;
                let difficulty: Difficulty = serde_json::from_str(&difficulty_contents)?;

                sub_difficulties.insert(difficulty_beatmap.difficulty_rank.clone(), difficulty);
            }

            difficulties.insert(
                difficulty_beatmap_set.beatmap_characteristic_name.clone(),
                sub_difficulties,
            );
        }

        // Calculate the audio file length
        #[cfg(feature = "audio")]
        let mut length = 0.0;
        #[cfg(feature = "audio")]
        {
            let mut audio_file = archive.by_name(&info.song_filename)?;
            let mut temp_audio_file = tempfile::tempfile()?;
            io::copy(&mut audio_file, &mut temp_audio_file)?;
            temp_audio_file.seek(SeekFrom::Start(0))?;
            let formats = ogg_metadata::read_format(&mut temp_audio_file)?;

            length = Beatmap::calculate_ogg_length(formats, length);
        }

        // Create the Beatmap and return it
        Ok(Beatmap {
            info,
            difficulties,
            #[cfg(feature = "beatsaver")]
            key: Some(String::from(key)),
            #[cfg(feature = "audio")]
            length,
        })
    }

    /// Returns a new Beatmap instance from a BeatSaver url
    #[cfg(feature = "beatsaver")]
    pub fn from_beatsaver_url(url: &str) -> Result<Beatmap, Box<dyn Error>> {
        let url_string = String::from(url);
        if url_string.starts_with("https://beatsaver.com/api/download/key/")
            || url_string.starts_with("https://beatsaver.com/beatmap/")
            || url_string.starts_with("beatsaver://")
        {
            let mut key = String::from(url_string.split("/").last().unwrap_or("invalid"));
            if key == "invalid" {
                return Err(Box::new(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "Can't extract key from url",
                )));
            }
            if key.ends_with("/") {
                key.pop();
            }

            Beatmap::from_beatsaver_key(&key)
        } else {
            Err(Box::new(io::Error::new(
                io::ErrorKind::InvalidInput,
                "Invalid url",
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Beatmap;
    use std::path::PathBuf;

    #[test]
    fn from_file_dat() {
        let mut filename = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
        filename.push("resources/test/info.dat");

        let result = Beatmap::from_file_dat(filename.to_str().unwrap()).unwrap();
        println!("{:#?}", result);
    }

    #[cfg(feature = "beatsaver")]
    #[test]
    fn from_beatsaver_key() {
        let result = Beatmap::from_beatsaver_key("3cf5").unwrap();
        println!("{:#?}", result);
    }

    #[cfg(feature = "beatsaver")]
    #[test]
    fn from_beatsaver_url() {
        let result = Beatmap::from_beatsaver_url("https://beatsaver.com/beatmap/1fef").unwrap();
        println!("{:#?}", result);
    }
}