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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/*
Copyright (C) 2021 Kunal Mehta <legoktm@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use crate::responses;
use crate::{tokens::TokenStore, Assert, Error, ErrorFormat, Result};
use log::debug;
use mwapi_errors::ApiError;
use reqwest::{header, Client as HttpClient, Request, Response};
use serde_json::Value;
use std::{collections::HashMap, fmt::Display, sync::Arc};
use tokio::sync::{RwLock, Semaphore};

/// Build a new API client.
/// ```
/// # use mwapi::{Client, Result};
/// # async fn doc() -> Result<()> {
/// let client: Client = Client::builder("https://example.org/w/api.php")
///     .set_oauth2_token("foobar")
///     .set_errorformat(mwapi::ErrorFormat::Html)
///     .build().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Debug)]
pub struct Builder {
    api_url: String,
    assert: Assert,
    concurrency: usize,
    maxlag: Option<u32>,
    user_agent: Option<String>,
    oauth2_token: Option<String>,
    errorformat: ErrorFormat,
    botpassword: Option<BotPassword>,
}

#[derive(Clone, Debug)]
struct BotPassword {
    username: String,
    password: String,
}

impl Builder {
    /// Create a new `Builder` instance. Typically you will use
    /// `Client::builder()` instead.
    pub fn new(api_url: &str) -> Self {
        Self {
            api_url: api_url.to_string(),
            assert: Default::default(),
            concurrency: 1,
            maxlag: None,
            user_agent: None,
            oauth2_token: None,
            errorformat: Default::default(),
            botpassword: None,
        }
    }

    /// Create a `Builder` with defaults aimed for interactive operation.
    /// Typically you will use `Client::interactive_builder()` instead.
    pub fn new_interactive(api_url: &str) -> Self {
        Self::new(api_url)
    }

    /// Actually build the `Client` instance.
    pub async fn build(self) -> Result<Client> {
        let client = Client {
            api_url: self.api_url,
            assert: self.assert,
            http: HttpClient::builder()
                .cookie_store(true)
                .user_agent(
                    self.user_agent
                        .unwrap_or(format!("mwapi-rs/{}", crate::VERSION)),
                )
                .build()?,
            tokens: Arc::new(RwLock::new(TokenStore::default())),
            semaphore: Arc::new(Semaphore::new(self.concurrency)),
            oauth2_token: self.oauth2_token,
            errorformat: self.errorformat,
            maxlag: self.maxlag,
        };
        if let Some(botpassword) = self.botpassword {
            client.login(&botpassword).await?;
        }
        Ok(client)
    }

    /// Set a custom User-agent. Ideally follow the [Wikimedia User-agent policy](https://meta.wikimedia.org/wiki/User-Agent_policy).
    pub fn set_user_agent(mut self, user_agent: &str) -> Self {
        self.user_agent = Some(user_agent.to_string());
        self
    }

    /// Set an [OAuth2 token](https://www.mediawiki.org/wiki/OAuth/For_Developers#OAuth_2)
    /// for authentication
    pub fn set_oauth2_token(mut self, oauth2_token: &str) -> Self {
        self.oauth2_token = Some(oauth2_token.to_string());
        self
    }

    /// Set the format error messages from the API should be in
    pub fn set_errorformat(mut self, errorformat: ErrorFormat) -> Self {
        self.errorformat = errorformat;
        self
    }

    /// Set how many requests should be processed in parallel. On Wikimedia
    /// wikis, you shouldn't exceed the default of 1 without getting permission
    /// from a sysadmin.
    pub fn set_concurrency(mut self, concurrency: usize) -> Self {
        self.concurrency = concurrency;
        self
    }

    /// Pause when the servers are lagged for how many seconds?
    /// Typically bots should set this to 5, while interactive
    /// usage should be much higher.
    ///
    /// See [mediawiki.org](https://www.mediawiki.org/wiki/Special:MyLanguage/Manual:Maxlag_parameter)
    /// for more details.
    pub fn set_maxlag(mut self, maxlag: u32) -> Self {
        self.maxlag = Some(maxlag);
        self
    }

    pub fn set_botpassword(mut self, username: &str, password: &str) -> Self {
        self.botpassword = Some(BotPassword {
            username: username.to_string(),
            password: password.to_string(),
        });
        // If no assert is set, add assert=user
        if self.assert == Assert::None {
            self.assert = Assert::User
        }
        self
    }

    pub fn set_assert(mut self, assert: Assert) -> Self {
        self.assert = assert;
        self
    }
}

#[derive(Clone, Debug)]
pub struct Client {
    api_url: String,
    assert: Assert,
    http: HttpClient,
    tokens: Arc<RwLock<TokenStore>>,
    semaphore: Arc<Semaphore>,
    oauth2_token: Option<String>,
    errorformat: ErrorFormat,
    maxlag: Option<u32>,
}

impl Client {
    /// Get a `Builder` instance to further customize the API `Client`.
    /// The API URL should be the absolute path to [api.php](https://www.mediawiki.org/wiki/API:Main_page).
    pub fn builder(api_url: &str) -> Builder {
        Builder::new(api_url)
    }

    /// Same as `Client::builder`, but with defaults tuned for interactive operation.
    pub fn interactive_builder(api_url: &str) -> Builder {
        Builder::new_interactive(api_url)
    }

    /// Get an API `Client` instance. The API URL should be the absolute
    /// path to [api.php](https://www.mediawiki.org/wiki/API:Main_page).
    pub async fn new(api_url: &str) -> Result<Self> {
        Builder::new(api_url).build().await
    }

    /// Get headers that should be applied to every request
    fn headers(&self) -> Result<header::HeaderMap> {
        let mut headers = header::HeaderMap::new();
        if let Some(token) = &self.oauth2_token {
            headers.insert(
                header::AUTHORIZATION,
                format!("Bearer {}", token).parse()?,
            );
        }

        Ok(headers)
    }

    async fn login(&self, botpassword: &BotPassword) -> Result<()> {
        // Don't use a cached token, we need a fresh one
        let token = self.tokens.write().await.load("login", self).await?;
        let resp = self
            .post(&[
                ("action", "login"),
                ("lgname", &botpassword.username),
                ("lgpassword", &botpassword.password),
                ("lgtoken", &token),
            ])
            .await?;
        let login_resp: responses::LoginResponse =
            serde_json::from_value(resp)?;
        // Convert "result": "Failed" into API errors
        if login_resp.login.result == "Failed" {
            Err(match login_resp.login.reason {
                Some(reason) => Error::ApiError(reason),
                None => Error::UnknownError("Login failed".to_string()),
            })
        } else {
            Ok(())
        }
    }

    fn fix_params<P: Display>(
        &self,
        params: &[(P, P)],
    ) -> HashMap<String, String> {
        let mut params: HashMap<String, String> = params
            .iter()
            .map(|(key, val)| (key.to_string(), val.to_string()))
            .collect();
        params.insert("format".to_string(), "json".to_string());
        params.insert("formatversion".to_string(), "2".to_string());
        params.insert("errorformat".to_string(), self.errorformat.to_string());
        if let Some(maxlag) = self.maxlag {
            params.insert("maxlag".to_string(), maxlag.to_string());
        }
        // Set assert if this is not a login or login token request
        if !(params.get("action") == Some(&"login".to_string())
            || (params.get("meta") == Some(&"tokens".to_string())
                && params.get("type") == Some(&"login".to_string())))
        {
            if let Some(value) = self.assert.get_value() {
                params.insert("assert".to_string(), value.to_string());
            }
        }
        params
    }

    /// Make an arbitrary API request using HTTP GET.
    pub async fn get<P: Display>(&self, params: &[(P, P)]) -> Result<Value> {
        let params = self.fix_params(params);
        let req = self
            .http
            .get(&self.api_url)
            .headers(self.headers()?)
            .query(&params)
            .build()?;
        let _lock = self.semaphore.acquire().await?;
        log_request(&req);
        let resp = self.http.execute(req).await?;
        log_response(&resp);
        drop(_lock);
        let value: Value = resp.error_for_status()?.json().await?;
        match value.get("errors") {
            Some(errors) => {
                let errors: Vec<ApiError> =
                    serde_json::from_value(errors.clone())?;
                // FIXME: What about the other errors?
                Err(Error::ApiError(errors[0].clone()))
            }
            None => Ok(value),
        }
    }

    /// Make an API POST request with a [CSRF token](https://www.mediawiki.org/wiki/API:Tokens).
    /// The correct token will automatically be fetched, and in case of a
    /// bad token error (if it expired), a new one will automatically be
    /// fetched and the request retried.
    pub async fn post_with_token<P: AsRef<str>>(
        &self,
        token_type: &str,
        params: &[(P, P)],
    ) -> Result<Value> {
        let mut params: HashMap<_, _> = params
            .iter()
            .map(|(key, val)| {
                (key.as_ref().to_string(), val.as_ref().to_string())
            })
            .collect();
        // Note: This is in a separate line to avoid holding the read lock
        // while also trying to get the write lock in the None clause.
        let get = self.tokens.read().await.get(token_type);
        let token = match get {
            Some(token) => token,
            None => self.tokens.write().await.load(token_type, self).await?,
        };
        params.insert("token".to_string(), token.to_string());
        let params_vec: Vec<_> = params.iter().collect();
        match self.post(params_vec.as_slice()).await {
            Ok(val) => {
                return Ok(val);
            }
            Err(Error::ApiError(err)) => {
                if err.code != "badtoken" {
                    return Err(Error::ApiError(err));
                }
            }
            Err(err) => {
                return Err(err);
            }
        };
        // badtoken error, let's try one more time
        let token = self.tokens.write().await.load(token_type, self).await?;
        params.insert("token".to_string(), token.to_string());
        let params_vec: Vec<_> = params.iter().collect();
        self.post(params_vec.as_slice()).await
    }

    /// Make an API POST request
    pub async fn post<P: Display>(&self, params: &[(P, P)]) -> Result<Value> {
        let params = self.fix_params(params);
        let req = self
            .http
            .post(&self.api_url)
            .headers(self.headers()?)
            .form(&params)
            .build()?;
        let _lock = self.semaphore.acquire().await?;
        log_request(&req);
        let resp = self.http.execute(req).await?;
        log_response(&resp);
        drop(_lock);
        let value: Value = resp.error_for_status()?.json().await?;
        match value.get("errors") {
            Some(errors) => {
                let errors: Vec<ApiError> =
                    serde_json::from_value(errors.clone())?;
                Err(Error::ApiError(errors[0].clone()))
            }
            None => Ok(value),
        }
    }
}

fn log_request(req: &Request) {
    let method = req.method().to_string();
    let url = req.url().to_string();
    // TODO: form body?
    debug!("Sending: HTTP {}: {}", method, url);
}

fn log_response(resp: &Response) {
    let status = resp.status().as_u16();
    let request_id = match resp.headers().get("x-request-id") {
        // Not worth logging an error if the header is invalid utf-8
        Some(val) => val.to_str().unwrap_or("unknown"),
        None => "unknown",
    };
    let url = resp.url().to_string();
    debug!("Received: {} (req: {}): {}", status, request_id, url);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_basic_get() {
        let client = Client::new("https://www.mediawiki.org/w/api.php")
            .await
            .unwrap();
        let resp = client
            .get(&[("action", "query"), ("meta", "siteinfo")])
            .await
            .unwrap();
        assert_eq!(
            resp["query"]["general"]["sitename"].as_str().unwrap(),
            "MediaWiki"
        );
    }

    #[tokio::test]
    async fn test_basic_errors() {
        let client = Client::new("https://www.mediawiki.org/w/api.php")
            .await
            .unwrap();
        let error = client.get(&[("action", "nonexistent")]).await.unwrap_err();
        assert_eq!(
            &error.to_string(),
            "API error: (code: badvalue): Unrecognized value for parameter \"action\": nonexistent."
        );
    }

    #[tokio::test]
    async fn test_builder() {
        let client = Client::builder("https://www.mediawiki.org/w/api.php")
            .set_oauth2_token("foobarbaz")
            .build()
            .await
            .unwrap();
        assert_eq!(client.oauth2_token, Some("foobarbaz".to_string()));
    }

    #[tokio::test]
    async fn test_login() {
        let username = std::env::var("MWAPI_USERNAME");
        let password = std::env::var("MWAPI_PASSWORD");
        if username.is_err() || password.is_err() {
            // Skip
            return;
        }
        let username = username.unwrap();
        let password = password.unwrap();
        let client = Client::builder("https://test.wikipedia.org/w/api.php")
            .set_botpassword(&username, &password)
            .build()
            .await
            .unwrap();
        let resp = client
            .get(&[("action", "query"), ("meta", "userinfo")])
            .await
            .unwrap();
        dbg!(&resp);
        // Check the botpassword username ("Foo@something") starts with the real wiki username ("Foo")
        assert!(&username
            .starts_with(resp["query"]["userinfo"]["name"].as_str().unwrap()));
    }

    #[tokio::test]
    async fn test_good_assert() {
        let client = Client::builder("https://test.wikipedia.org/w/api.php")
            .set_assert(Assert::Anonymous)
            .build()
            .await
            .unwrap();
        // No error
        client.get(&[("action", "query")]).await.unwrap();
    }

    #[tokio::test]
    async fn test_bad_assert() {
        let client = Client::builder("https://test.wikipedia.org/w/api.php")
            .set_assert(Assert::User)
            .build()
            .await
            .unwrap();
        let error = client.get(&[("action", "query")]).await.unwrap_err();
        match error {
            Error::ApiError(err) => {
                assert_eq!(&err.code, "assertuserfailed")
            }
            err => {
                panic!("Unexpected error: {:?}", err);
            }
        }
    }

    #[tokio::test]
    async fn test_bad_login() {
        let error = Client::builder("https://test.wikipedia.org/w/api.php")
            .set_botpassword("ThisAccountDoesNotExistPlease", "password")
            .build()
            .await
            .unwrap_err();
        match error {
            Error::ApiError(err) => {
                assert_eq!(&err.code, "wrongpassword");
            }
            err => {
                panic!("Unexpected error: {:?}", err);
            }
        }
    }
}