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
use derive_more::From;
use err_derive::Error;
use lazy_static::lazy_static;
#[allow(unused)] use log::{debug, error, info, trace, warn};
use regex::Regex;
use validator::Validate;

use crate::{
    api,
    types::*,
    utils::{slugify, u64_from_base36},
};

#[derive(Debug, Error, From)]
pub enum Error {
    #[error(display = "all names were None or zero-length")]
    NoNames,
    #[error(display = "an ID was invalid and could not be decoded: {:?}", _0)]
    InvalidId(crate::utils::Base36DecodingError),
    #[error(display = "internal error: invalid object created. {:?}", _0)]
    InternalValidationErrors(validator::ValidationErrors),
}

pub trait Normalize {
    type Normalized;
    fn normalize(&self) -> Result<Self::Normalized, Error>;
}

impl Normalize for api::User {
    type Normalized = User;

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        let name = self
            .names()
            .normalize()
            .unwrap_or_else(|_| format!("Corrupt User {}", self.id()));
        let slug = slugify(&name);
        let user = User {
            id: u64_from_base36(self.id())?,
            created: *self.signup(),
            name,
            slug,
        };

        user.validate()?;

        Ok(user)
    }
}

impl Normalize for api::Names {
    type Normalized = String;

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        if let Some(name) = self.international() {
            if !name.is_empty() {
                return Ok(name.to_string())
            }
        }
        if let Some(name) = self.international() {
            if !name.is_empty() {
                return Ok(name.to_string())
            }
        }
        if let Some(name) = self.japanese() {
            if !name.is_empty() {
                return Ok(name.to_string())
            }
        }
        Err(Error::NoNames)
    }
}

impl Normalize for api::Game {
    type Normalized = (Game, Vec<Category>, Vec<Level>);

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        let game = Game {
            id:             u64_from_base36(self.id())?,
            name:           self.names().normalize()?,
            slug:           slugify(self.abbreviation()),
            src_slug:       self.abbreviation().to_string(),
            created:        *self.created(),
            primary_timing: self.ruleset().default_time().normalize()?,
        };
        game.validate()?;

        let categories = self
            .categories()
            .iter()
            .map(|api_category| -> Result<Category, Error> {
                let category = Category {
                    game_id: u64_from_base36(self.id())?,
                    id:      u64_from_base36(api_category.id())?,
                    slug:    slugify(api_category.name()),
                    name:    api_category.name().to_string(),
                    rules:   api_category.rules().clone().unwrap_or_else(String::new),
                    per:     api_category.type_().normalize()?,
                };

                category.validate()?;

                Ok(category)
            })
            .collect::<Result<Vec<_>, _>>()?;

        let levels = self
            .levels()
            .iter()
            .map(|api_level| -> Result<Level, Error> {
                let level = Level {
                    game_id: u64_from_base36(self.id())?,
                    id:      u64_from_base36(api_level.id())?,
                    slug:    slugify(api_level.name()),
                    name:    api_level.name().to_string(),
                    rules:   api_level.rules().clone().unwrap_or_default(),
                };

                level.validate()?;

                Ok(level)
            })
            .collect::<Result<_, _>>()?;

        Ok((game, categories, levels))
    }
}

impl Normalize for api::Run {
    // Option because we drop runs that aren't verified.
    type Normalized = Option<Run>;

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        match self.status() {
            api::RunStatus::Verified { .. } => {
                let run = Run {
                    game_id:     u64_from_base36(self.game())?,
                    id:          u64_from_base36(self.id())?,
                    created:     *self.submitted(),
                    date:        *self.date(),
                    category_id: u64_from_base36(self.category())?,
                    level_id:    match self.level() {
                        None => None,
                        Some(level_id) => Some(u64_from_base36(level_id)?),
                    },
                    times_ms:    self.times().normalize()?,
                    players:     self
                        .players()
                        .iter()
                        .map(Normalize::normalize)
                        .map(Result::unwrap)
                        .collect(),
                };
                run.validate()?;
                Ok(Some(run))
            }
            _ => Ok(None),
        }
    }
}

impl Normalize for api::RunPlayer {
    type Normalized = RunPlayer;

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        Ok(match self {
            api::RunPlayer::Guest { name, .. } => RunPlayer::GuestName(name.to_string()),
            api::RunPlayer::User { id, .. } => RunPlayer::UserId(u64_from_base36(id)?),
        })
    }
}

impl Normalize for api::CategoryType {
    type Normalized = CategoryType;

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        Ok(match self {
            api::CategoryType::PerLevel => CategoryType::PerLevel,
            api::CategoryType::PerGame => CategoryType::PerGame,
        })
    }
}

impl Normalize for api::GameRulesetTiming {
    type Normalized = TimingMethod;

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        Ok(match self {
            api::GameRulesetTiming::IGT => TimingMethod::IGT,
            api::GameRulesetTiming::RTA => TimingMethod::RTA,
            api::GameRulesetTiming::RTA_NL => TimingMethod::RTA_NL,
        })
    }
}

impl Normalize for api::RunTimes {
    type Normalized = RunTimesMs;

    fn normalize(&self) -> Result<Self::Normalized, Error> {
        fn u64_or_zero(s: Option<regex::Match<'_>>) -> u64 {
            match s {
                Some(s) => {
                    let s = s.as_str();
                    if s.is_empty() {
                        0
                    } else {
                        s.parse().unwrap()
                    }
                }
                None => 0,
            }
        }

        fn parse_duration_ms(s: &str) -> u64 {
            lazy_static! {
                static ref RE: Regex = Regex::new(
                    r"(?x)
                    P
                    (?:(\d+)D)?
                    T
                    (?:(\d+)H)?
                    (?:(\d+)M)?
                    (?:
                        (\d+)
                        (?:\.(\d\d\d))?
                        S
                    )?
                "
                )
                .unwrap();
            }

            let captures = RE.captures(s).expect("duration regex to cover all cases");
            let days = u64_or_zero(captures.get(1));
            let hours = u64_or_zero(captures.get(2));
            let minutes = u64_or_zero(captures.get(3));
            let seconds = u64_or_zero(captures.get(4));
            let millis = u64_or_zero(captures.get(5));

            ((((days * 24) + hours) * 60 + minutes) * 60 + seconds) * 1000 + millis
        }

        Ok(RunTimesMs {
            igt:    self.ingame().as_ref().map(|s| parse_duration_ms(s)),
            rta:    self.realtime().as_ref().map(|s| parse_duration_ms(s)),
            rta_nl: self
                .realtime_noloads()
                .as_ref()
                .map(|s| parse_duration_ms(s)),
        })
    }
}