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
use std::{
    error::Error as StdError,
    fmt::{Debug, Display, Formatter, Result as FmtResult},
    str::from_utf8 as str_from_utf8,
};

use hyper::{body::Bytes, Body, Error as HyperError, Response};
use serde::{
    de::{Deserializer, Error as DeError, Unexpected, Visitor},
    Deserialize,
};
use serde_json::Error as JsonError;
use serde_urlencoded::ser::Error as UrlError;
use thiserror::Error as ThisError;

use crate::model::SkinDeleted;

#[derive(Debug, ThisError)]
#[non_exhaustive]
pub enum ClientError {
    #[error("Failed to build the request")]
    BuildingRequest {
        #[source]
        source: Box<dyn StdError + Send + Sync + 'static>,
    },
    #[error("Failed to chunk the response")]
    ChunkingResponse {
        #[source]
        source: HyperError,
    },
    #[error("Failed to deserialize response body: {body}")]
    Parsing {
        body: StringOrBytes,
        #[source]
        source: JsonError,
    },
    #[error("Parsing or sending the response failed")]
    RequestError {
        #[source]
        source: HyperError,
    },
    #[error("Response error: status code {status_code}, {error}")]
    Response {
        body: Bytes,
        error: ApiError,
        status_code: u16,
    },
    #[error("Failed to serialize the query")]
    SerdeQuery {
        #[from]
        source: UrlError,
    },
    #[error("API may be temporarily unavailable (received a 503)")]
    ServiceUnavailable { response: Response<Body> },
    #[error("Skin was not found (received a 404)")]
    SkinDeleted { error: SkinDeleted },
    #[error("Banned from o!rdr. All future requests will fail.")]
    Unauthorized,
}

impl ClientError {
    pub(crate) fn response_error(bytes: Bytes, status_code: u16) -> Self {
        match serde_json::from_slice(&bytes) {
            Ok(error) => Self::Response {
                body: bytes,
                error,
                status_code,
            },
            Err(source) => Self::Parsing {
                body: bytes.into(),
                source,
            },
        }
    }
}

#[derive(Clone, Debug)]
pub struct StringOrBytes {
    bytes: Bytes,
}

impl Display for StringOrBytes {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match str_from_utf8(&self.bytes) {
            Ok(string) => f.write_str(string),
            Err(_) => <[u8] as Debug>::fmt(&*self.bytes, f),
        }
    }
}

impl From<Bytes> for StringOrBytes {
    fn from(bytes: Bytes) -> Self {
        Self { bytes }
    }
}

#[derive(Debug, Deserialize)]
pub struct ApiError {
    /// The response of the server.
    pub message: Box<str>,
    /// The reason of the ban (if provided by admins).
    pub reason: Option<Box<str>>,
    /// The error code of the creation of this render.
    #[serde(rename = "errorCode")]
    pub code: Option<ErrorCode>,
}

impl Display for ApiError {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        if let Some(ref code) = self.code {
            write!(f, "Error code {code}: ")?;
        }

        f.write_str(&self.message)?;

        if let Some(ref reason) = self.reason {
            write!(f, " (reason: {reason})")?;
        }

        Ok(())
    }
}

/// Error codes as defined by o!rdr
///
/// See <https://ordr.issou.best/docs/#section/Error-codes>
#[derive(Copy, Clone, Debug, ThisError, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[repr(u8)]
pub enum ErrorCode {
    #[error("Emergency stop (triggered manually)")]
    EmergencyStop,
    #[error("Replay parsing error (bad upload from the sender)")]
    ReplayParsingError,
    #[error("Replay download error (bad download from the server), can happen because of invalid characters")]
    ReplayDownloadError,
    #[error("All beatmap mirrors are unavailable")]
    MirrorsUnavailable,
    #[error("Replay file corrupted")]
    ReplayFileCorrupted,
    #[error("Invalid osu! gamemode (not 0 = std)")]
    InvalidGameMode,
    #[error("The replay has no input data")]
    ReplayWithoutInputData,
    #[error("Beatmap does not exist on osu! (probably because of custom difficulty or non-submitted map)")]
    BeatmapNotFound,
    #[error("Audio for the map is unavailable (because of copyright claim)")]
    BeatmapAudioUnavailable,
    #[error("Cannot connect to osu! api")]
    OsuApiConnection,
    #[error("The replay has the autoplay mod")]
    ReplayIsAutoplay,
    #[error("The replay username has invalid characters")]
    InvalidReplayUsername,
    #[error("The beatmap is longer than 15 minutes")]
    BeatmapTooLong,
    #[error("This player is banned from o!rdr")]
    PlayerBannedFromOrdr,
    #[error("Beatmap not found on all the beatmap mirrors")]
    MapNotFound,
    #[error("This IP is banned from o!rdr")]
    IpBannedFromOrdr,
    #[error("This username is banned from o!rdr")]
    UsernameBannedFromOrdr,
    #[error("Unknown error from the renderer")]
    UnknownRendererError,
    #[error("The renderer cannot download the map")]
    CannotDownloadMap,
    #[error("Beatmap version on the mirror is not the same as the replay")]
    InconsistentMapVersion,
    #[error("The replay is corrupted (danser cannot process it)")]
    ReplayFileCorrupted2,
    #[error("Server-side problem while finalizing the generated video")]
    FailedFinalizing,
    #[error("Server-side problem while preparing the render")]
    ServerFailedPreparation,
    #[error("The beatmap has no name")]
    BeatmapHasNoName,
    #[error("The replay is missing input data")]
    ReplayMissingInputData,
    #[error("The replay has incompatible mods")]
    ReplayIncompatibleMods,
    #[error(
        "Something with the renderer went wrong: it probably has an unstable internet connection \
        (multiple renders at the same time)"
    )]
    RendererIssue,
    #[error("The renderer cannot download the replay")]
    CannotDownloadReplay,
    #[error("The replay is already rendering or in queue")]
    ReplayAlreadyInQueue,
    #[error("The star rating is greater than 20")]
    StarRatingTooHigh,
    #[error("The mapper is blacklisted")]
    MapperIsBlacklisted,
    #[error("The beatmapset is blacklisted")]
    BeatmapsetIsBlacklisted,
    #[error("The replay has already errored less than an hour ago")]
    ReplayErroredRecently,
    #[error("Unknown error code {0}")]
    Other(u8),
}

impl ErrorCode {
    #[must_use]
    pub fn to_u8(self) -> u8 {
        match self {
            Self::EmergencyStop => 1,
            Self::ReplayParsingError => 2,
            Self::ReplayDownloadError => 3,
            Self::MirrorsUnavailable => 4,
            Self::ReplayFileCorrupted => 5,
            Self::InvalidGameMode => 6,
            Self::ReplayWithoutInputData => 7,
            Self::BeatmapNotFound => 8,
            Self::BeatmapAudioUnavailable => 9,
            Self::OsuApiConnection => 10,
            Self::ReplayIsAutoplay => 11,
            Self::InvalidReplayUsername => 12,
            Self::BeatmapTooLong => 13,
            Self::PlayerBannedFromOrdr => 14,
            Self::MapNotFound => 15,
            Self::IpBannedFromOrdr => 16,
            Self::UsernameBannedFromOrdr => 17,
            Self::UnknownRendererError => 18,
            Self::CannotDownloadMap => 19,
            Self::InconsistentMapVersion => 20,
            Self::ReplayFileCorrupted2 => 21,
            Self::FailedFinalizing => 22,
            Self::ServerFailedPreparation => 23,
            Self::BeatmapHasNoName => 24,
            Self::ReplayMissingInputData => 25,
            Self::ReplayIncompatibleMods => 26,
            Self::RendererIssue => 27,
            Self::CannotDownloadReplay => 28,
            Self::ReplayAlreadyInQueue => 29,
            Self::StarRatingTooHigh => 30,
            Self::MapperIsBlacklisted => 31,
            Self::BeatmapsetIsBlacklisted => 32,
            Self::ReplayErroredRecently => 33,
            Self::Other(code) => code,
        }
    }
}

impl<'de> Deserialize<'de> for ErrorCode {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct ErrorCodeVisitor;

        impl<'de> Visitor<'de> for ErrorCodeVisitor {
            type Value = ErrorCode;

            fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
                f.write_str("u8")
            }

            fn visit_u8<E: DeError>(self, v: u8) -> Result<Self::Value, E> {
                let code = match v {
                    2 => ErrorCode::ReplayParsingError,
                    5 => ErrorCode::ReplayFileCorrupted,
                    6 => ErrorCode::InvalidGameMode,
                    7 => ErrorCode::ReplayWithoutInputData,
                    8 => ErrorCode::BeatmapNotFound,
                    9 => ErrorCode::BeatmapAudioUnavailable,
                    10 => ErrorCode::OsuApiConnection,
                    11 => ErrorCode::ReplayIsAutoplay,
                    12 => ErrorCode::InvalidReplayUsername,
                    13 => ErrorCode::BeatmapTooLong,
                    14 => ErrorCode::PlayerBannedFromOrdr,
                    16 => ErrorCode::IpBannedFromOrdr,
                    17 => ErrorCode::UsernameBannedFromOrdr,
                    23 => ErrorCode::ServerFailedPreparation,
                    24 => ErrorCode::BeatmapHasNoName,
                    25 => ErrorCode::ReplayMissingInputData,
                    26 => ErrorCode::ReplayIncompatibleMods,
                    29 => ErrorCode::ReplayAlreadyInQueue,
                    30 => ErrorCode::StarRatingTooHigh,
                    31 => ErrorCode::MapperIsBlacklisted,
                    32 => ErrorCode::BeatmapsetIsBlacklisted,
                    33 => ErrorCode::ReplayErroredRecently,
                    other => ErrorCode::Other(other),
                };

                Ok(code)
            }

            fn visit_u64<E: DeError>(self, v: u64) -> Result<Self::Value, E> {
                let code = u8::try_from(v).map_err(|_| {
                    DeError::invalid_value(Unexpected::Unsigned(v), &"a valid error code")
                })?;

                self.visit_u8(code)
            }
        }

        d.deserialize_u8(ErrorCodeVisitor)
    }
}