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
#![deny(clippy::all)]
#![cfg_attr(docs, feature(doc_cfg))]
use serde::Deserialize;
use serde_json::Value;
use std::fmt::{Display, Formatter};
use std::sync::Arc;
use thiserror::Error as ThisError;
#[derive(Clone, Debug, Deserialize)]
pub struct ApiError {
pub code: String,
pub text: String,
pub data: Option<Value>,
}
impl Display for ApiError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "(code: {}): {}", self.code, self.text)
}
}
#[non_exhaustive]
#[derive(ThisError, Debug, Clone)]
pub enum Error {
#[cfg(feature = "from-reqwest")]
#[cfg_attr(docs, doc(cfg(feature = "from-reqwest")))]
#[error("HTTP error: {0}")]
HttpError(Arc<reqwest::Error>),
#[cfg(feature = "from-reqwest")]
#[cfg_attr(docs, doc(cfg(feature = "from-reqwest")))]
#[error("Invalid header value")]
InvalidHeaderValue,
#[error("JSON error: {0}")]
InvalidJson(Arc<serde_json::Error>),
#[cfg(feature = "from-tokio")]
#[cfg_attr(docs, doc(cfg(feature = "from-tokio")))]
#[error("Unable to get request lock")]
LockFailure,
#[cfg(feature = "from-mwtitle")]
#[cfg_attr(docs, doc(cfg(feature = "from-mwtitle")))]
#[error("Invalid title: {0}")]
InvalidTitle(#[from] mwtitle::Error),
#[error("The etag for this request is missing or invalid")]
InvalidEtag,
#[error("Invalid CSRF token")]
BadToken,
#[error("Unable to get token `{0}`")]
TokenFailure(String),
#[error("Heading levels must be between 1 and 6, '{0}' was provided")]
InvalidHeadingLevel(u32),
#[error("You're not logged in")]
NotLoggedIn,
#[error("You're not logged in as a bot account")]
NotLoggedInAsBot,
#[error("Missing permission: {0}")]
PermissionDenied(String),
#[error("Blocked sitewide: {info}")]
Blocked { info: String, details: BlockDetails },
#[error("Partially blocked: {info}")]
PartiallyBlocked { info: String, details: BlockDetails },
#[error("Globally blocked: {0}")]
GloballyBlocked(String),
#[error("Globally range blocked: {0}")]
GloballyRangeBlocked(String),
#[error("Globally XFF blocked: {0}")]
GloballyXFFBlocked(String),
#[error("Blocked: {0}")]
UnknownBlock(String),
#[error("You've made too many recent login attempts.")]
LoginThrottled,
#[error("Incorrect username or password entered.")]
WrongPassword,
#[error("The specified title is not a valid page")]
InvalidPage,
#[error("{{nobots}} prevents editing this page")]
Nobots,
#[error("Page does not exist: {0}")]
PageDoesNotExist(String),
#[error("Page is protected")]
ProtectedPage,
#[error("Edit conflict")]
EditConflict,
#[error("Content too big: {0}")]
ContentTooBig(String),
#[error("{info}")]
SpamFilter { info: String, matches: Vec<String> },
#[error("Unknown save failure: {0}")]
UnknownSaveFailure(Value),
#[error("maxlag tripped: {0}")]
Maxlag(String),
#[error("MediaWiki is readonly: {0}")]
Readonly(String),
#[error("Internal MediaWiki exception: {0}")]
InternalException(ApiError),
#[error("API error: {0}")]
ApiError(ApiError),
#[error("Unknown error: {0}")]
Unknown(String),
}
#[cfg(feature = "from-tokio")]
#[cfg_attr(docs, doc(cfg(feature = "from-tokio")))]
impl From<tokio::sync::AcquireError> for Error {
fn from(_: tokio::sync::AcquireError) -> Self {
Self::LockFailure
}
}
#[cfg(feature = "from-reqwest")]
#[cfg_attr(docs, doc(cfg(feature = "from-reqwest")))]
impl From<reqwest::header::InvalidHeaderValue> for Error {
fn from(_: reqwest::header::InvalidHeaderValue) -> Self {
Self::InvalidHeaderValue
}
}
#[cfg(feature = "from-reqwest")]
#[cfg_attr(docs, doc(cfg(feature = "from-reqwest")))]
impl From<reqwest::Error> for Error {
fn from(err: reqwest::Error) -> Self {
Self::HttpError(Arc::new(err))
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Self {
Self::InvalidJson(Arc::new(err))
}
}
impl Error {
pub fn is_page_related(&self) -> bool {
matches!(
self,
Error::InvalidPage
| Error::ProtectedPage
| Error::Nobots
| Error::PartiallyBlocked { .. }
| Error::EditConflict
| Error::SpamFilter { .. }
| Error::ContentTooBig(_)
)
}
pub fn is_sitewide_block(&self) -> bool {
matches!(
self,
Error::Blocked { .. }
| Error::GloballyBlocked(_)
| Error::GloballyRangeBlocked(_)
| Error::GloballyXFFBlocked(_)
| Error::UnknownBlock(_)
)
}
pub fn should_retry(&self) -> bool {
matches!(self, Error::Maxlag { .. } | Error::Readonly(_))
}
}
#[derive(Deserialize)]
struct SpamFilterData {
matches: Vec<String>,
}
#[derive(Deserialize, Debug, Clone)]
pub struct BlockDetails {
pub blockid: u32,
pub blockedby: String,
pub blockedbyid: u32,
pub blockreason: String,
pub blockedtimestamp: String,
pub blockpartial: bool,
pub blocknocreate: bool,
pub blockanononly: bool,
pub systemblocktype: Option<String>,
}
impl From<ApiError> for Error {
fn from(apierr: ApiError) -> Self {
match apierr.code.as_str() {
"assertuserfailed" => Self::NotLoggedIn,
"assertbotfailed" => Self::NotLoggedInAsBot,
"badtoken" => Self::BadToken,
"blocked" => {
let details = if let Some(data) = apierr.data {
serde_json::from_value::<BlockDetails>(
data["blockinfo"].clone(),
)
.ok()
} else {
None
};
match details {
Some(details) => {
if details.blockpartial {
Self::PartiallyBlocked {
info: apierr.text,
details,
}
} else {
Self::Blocked {
info: apierr.text,
details,
}
}
}
None => Self::UnknownBlock(apierr.text),
}
}
"contenttoobig" => Self::ContentTooBig(apierr.text),
"editconflict" => Self::EditConflict,
"globalblocking-ipblocked"
| "wikimedia-globalblocking-ipblocked" => {
Self::GloballyBlocked(apierr.text)
}
"globalblocking-ipblocked-range"
| "wikimedia-globalblocking-ipblocked-range" => {
Self::GloballyRangeBlocked(apierr.text)
}
"globalblocking-ipblocked-xff"
| "wikimedia-globalblocking-ipblocked-xff" => {
Self::GloballyXFFBlocked(apierr.text)
}
"login-throttled" => Self::LoginThrottled,
"maxlag" => Self::Maxlag(apierr.text),
"protectedpage" => Self::ProtectedPage,
"readonly" => Self::Readonly(apierr.text),
"spamblacklist" => {
let matches = if let Some(data) = apierr.data {
match serde_json::from_value::<SpamFilterData>(
data["spamblacklist"].clone(),
) {
Ok(data) => data.matches,
Err(_) => vec![],
}
} else {
vec![]
};
Self::SpamFilter {
info: apierr.text,
matches,
}
}
"wrongpassword" => Self::WrongPassword,
code => {
if code.starts_with("internal_api_error_") {
Self::InternalException(apierr)
} else {
Self::ApiError(apierr)
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_page_related() {
assert!(Error::EditConflict.is_page_related());
assert!(!Error::Unknown("bar".to_string()).is_page_related());
}
#[test]
fn test_from_apierror() {
let apierr = ApiError {
code: "assertbotfailed".to_string(),
text: "Something something".to_string(),
data: None,
};
let err = Error::from(apierr);
if let Error::NotLoggedInAsBot = err {
assert!(true);
} else {
panic!("Expected NotLoggedInAsBot error");
}
}
#[test]
fn test_to_string() {
let apierr = ApiError {
code: "errorcode".to_string(),
text: "Some description".to_string(),
data: None,
};
assert_eq!(&apierr.to_string(), "(code: errorcode): Some description");
}
#[test]
fn test_spamfilter() {
let apierr = ApiError {
code: "spamblacklist".to_string(),
text: "blah blah".to_string(),
data: Some(serde_json::json!({
"spamblacklist": {
"matches": [
"example.org"
]
}
})),
};
let err = Error::from(apierr);
if let Error::SpamFilter { matches, .. } = err {
assert_eq!(matches, vec!["example.org".to_string()]);
} else {
panic!("Unexpected error: {:?}", err);
}
}
}