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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
/*
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 <http://www.gnu.org/licenses/>.
 */

//! A MediaWiki bot and tool framework
//!
//! `mwbot` aims to provide a batteries-included framework for building bots
//! and tools for MediaWiki wikis. It builds on top of the [mwapi](https://docs.rs/mwapi)
//! and [parsoid](https://docs.rs/parsoid) crates, which offer lower-level APIs.
//!
//! ## Quickstart
//! ### Configuration
//! Create a `~/.config/mwbot.toml` file with the following structure:
//! ```toml
//! api_url = "https://en.wikipedia.org/w/api.php"
//! rest_url = "https://en.wikipedia.org/api/rest_v1"
//! ```
//!
//! If want to authenticate, add an auth section:
//! ```toml
//! [auth]
//! username = "Example"
//! oauth2_token = "[...]"
//! ```
//! See [the OAuth documentation](https://www.mediawiki.org/wiki/OAuth/For_Developers#OAuth_2)
//! for how to get an OAuth 2 token. Using an [owner-only consumer](https://www.mediawiki.org/wiki/OAuth/Owner-only_consumers#OAuth_2)
//! is the easiest way to do so.
//!
//! ### Reading a page
//! ```
//! # async fn demo() -> mwbot::Result<()> {
//! # use parsoid::prelude::*;
//! let bot = mwbot::Bot::from_default_config().await.unwrap();
//! let page = bot.page("Rust (programming language)")?;
//! let html = page.html().await?.into_mutable();
//! // The lead section is the second p tag in the first section
//! let lead = html.select("section > p")[1].text_contents();
//! assert!(lead.starts_with("Rust is a multi-paradigm, general-purpose programming language"));
//! # Ok(())
//! # }
//! ```
//! Using `Bot::from_default_config()` will look in the current directory
//! for `mwbot.toml` before looking in the user's config directory. A
//! custom path can be specified by using `Bot::from_config(...)`.
//!
//! ### Editing a page
//! ```
//! # async fn demo() -> mwbot::Result<()> {
//! # use mwbot::SaveOptions;
//! let bot = mwbot::Bot::from_default_config().await.unwrap();
//! let page = bot.page("Project:Sandbox")?;
//! let wikitext = "This is a test edit!";
//! page.save(wikitext, &SaveOptions::summary("test edit!")).await?;
//! # Ok(())
//! # }
//! ```
//! `Page.save()` accepts both HTML and wikitext and supports the [`{{nobots}}`](https://en.wikipedia.org/wiki/Template:Bots)
//! exclusion mechanism, among other features.
//!
//! ### Next steps
//! Try using one of the offered [page generators](./generators/index.html) to fetch and operate on
//! multiple pages.
//!
//! ## Contributing
//! `mwbot` is the flagship crate of the [`mwbot-rs` project](https://www.mediawiki.org/wiki/Mwbot-rs).
//! We're always looking for new contributors, please [reach out](https://www.mediawiki.org/wiki/Mwbot-rs#Contributing)
//! if you're interested!
#![deny(clippy::all)]
#![deny(rustdoc::all)]
#![cfg_attr(docs, feature(doc_cfg))]

mod builder;
mod config;
mod edit;
mod error;
#[cfg(feature = "upload")]
#[cfg_attr(docs, doc(cfg(feature = "upload")))]
pub mod file;
#[cfg(feature = "generators")]
#[cfg_attr(docs, doc(cfg(feature = "generators")))]
pub mod generators;
mod logging;
mod page;
mod siteinfo;
#[cfg(unix)]
mod unix;
#[cfg(feature = "upload")]
#[cfg_attr(docs, doc(cfg(feature = "upload")))]
pub mod upload;
mod utils;

pub use error::{config::ConfigError, Error};
pub use mwapi::Client as ApiClient;
use mwapi::ErrorFormat;
pub use mwtimestamp as timestamp;
use mwtitle::{Title, TitleCodec};
use once_cell::sync::OnceCell;
pub use parsoid;
use std::{path::Path, sync::Arc};
use tokio::{sync::Mutex, time};
use tracing::{debug, info};
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub use builder::Builder;
pub use edit::SaveOptions;
pub use logging::init as init_logging;
pub use page::Page;

use parsoid::prelude::*;

/// Main bot class
#[derive(Clone, Debug)]
pub struct Bot {
    api: ApiClient,
    parsoid: ParsoidClient,
    state: BotState,
    config: Arc<BotConfig>,
}

/// Static, read-only settings
#[derive(Clone, Debug)]
struct BotConfig {
    // TODO: figure out something better than this
    username: Option<String>,
    codec: TitleCodec,
    /// Whether edits should be marked as bot (default: true)
    mark_as_bot: bool,
    /// Whether to respect {{nobots}} (default: true)
    respect_nobots: bool,
}

/// Dynamic state
#[derive(Clone, Debug)]
struct BotState {
    save_timer: Option<Arc<Mutex<time::Interval>>>,
}

impl Bot {
    /// Build a `Bot` instance programmatically.
    pub fn builder(api_url: String, rest_url: String) -> Builder {
        Builder::new(api_url, rest_url)
    }

    /// Load Bot configuration from a default location, first look at
    /// `mwbot.toml` in the current directory, otherwise look in the
    /// platform's config directory:
    ///
    /// * Linux: `$XDG_CONFIG_HOME` or `$HOME/.config`
    /// * macOS: `$HOME/Library/Application Support`
    /// * Windows: `{FOLDERID_RoamingAppData}`
    pub async fn from_default_config() -> Result<Self, ConfigError> {
        let path = {
            let first = Path::new("mwbot.toml");
            if first.exists() {
                first.to_path_buf()
            } else {
                dirs::config_dir()
                    .expect("Cannot find config directory")
                    .join("mwbot.toml")
            }
        };
        Self::from_path(&path).await
    }

    /// Load Bot configuration from the specified path.
    pub async fn from_path(path: &Path) -> Result<Self, ConfigError> {
        debug!("Reading config from {:?}", path);
        let config: config::Config =
            toml::from_str(&std::fs::read_to_string(path)?)?;
        // Check file permissions if there are credentials
        if config.auth.is_some() {
            check_file_permissions(path)?;
        }
        Self::from_config(config).await
    }

    async fn from_config(config: config::Config) -> Result<Self, ConfigError> {
        let mut api = ApiClient::builder(&config.api_url)
            .set_maxlag(config.general.maxlag.unwrap_or(5))
            .set_errorformat(ErrorFormat::Wikitext);
        if let Some(limit) = config.general.retry_limit {
            api = api.set_retry_limit(limit);
        }
        let mut user_agent = vec![];
        if let Some(extra) = config.general.user_agent {
            user_agent.push(extra);
        }
        // FIXME: do better
        let mut username = None;
        if let Some(auth) = config.auth {
            match &auth {
                config::Auth::BotPassword { username, password } => {
                    info!("Logging in as {} with password", username);
                    api = api.set_botpassword(username, password);
                }
                config::Auth::OAuth2 {
                    username,
                    oauth2_token,
                } => {
                    info!("Logging in as {} with OAuth2 token", username);
                    api = api.set_oauth2_token(oauth2_token);
                }
            }
            let normalized = normalize_username(auth.username());
            user_agent.push(format!("User:{}", &normalized));
            username = Some(normalized);
        }
        user_agent.push(format!("mwbot-rs/{}", env!("CARGO_PKG_VERSION")));
        let user_agent = user_agent.join(" ");
        let save_delay = config.edit.save_delay.unwrap_or(10);
        let save_timer = if save_delay > 0 {
            let mut interval =
                time::interval(time::Duration::from_secs(save_delay));
            interval.set_missed_tick_behavior(time::MissedTickBehavior::Delay);
            Some(Arc::new(Mutex::new(interval)))
        } else {
            None
        };
        let api = api
            .set_user_agent(&user_agent)
            .build()
            .await
            .map_err(Error::from)?;
        let siteinfo = siteinfo::get_siteinfo(&api).await?;
        let http = api.http_client().clone();
        Ok(Self {
            api,
            parsoid: ParsoidClient::new_with_client(&config.rest_url, http),
            config: Arc::new(BotConfig {
                username,
                codec: TitleCodec::from_site_info(siteinfo)
                    .map_err(Error::from)?,
                mark_as_bot: config.edit.mark_as_bot.unwrap_or(true),
                respect_nobots: config.edit.respect_nobots.unwrap_or(true),
            }),
            state: BotState { save_timer },
        })
    }

    /// Get a reference to the underlying [`mwapi::Client`](https://docs.rs/mwapi/latest/mwapi/struct.Client.html)
    /// to make arbitrary API requests
    pub fn api(&self) -> &ApiClient {
        &self.api
    }

    /// Get a reference to the underlying [`parsoid::Client`](https://docs.rs/parsoid/latest/parsoid/struct.Client.html)
    /// to make arbitrary Parsoid API requests
    pub fn parsoid(&self) -> &ParsoidClient {
        &self.parsoid
    }

    /// Get a reference to the internal [`mwtitle::TitleCodec`](https://docs.rs/mwtitle/latest/mwtitle/struct.TitleCodec.html)
    /// to parse and construct arbitrary titles.
    pub fn title_codec(&self) -> &TitleCodec {
        &self.config.codec
    }

    /// Get a `Page` on this wiki. The specified title should be a full title,
    /// including namespace. This does some validation on the
    /// provided input.
    pub fn page(&self, title: &str) -> Result<Page> {
        let title = self.config.codec.new_title(title)?.remove_fragment();
        self.page_from_title(title)
    }

    /// Get a `Page` on this wiki using information from a database row.
    ///
    /// The provided input will be validated and may return an
    /// error if invalid.
    pub fn page_from_database(
        &self,
        namespace: i32,
        dbkey: &str,
    ) -> Result<Page> {
        let title = self
            .config
            .codec
            .new_title_from_database(namespace, dbkey)?
            .remove_fragment();
        self.page_from_title(title)
    }

    /// Get a `Page` for a given [`Title`](https://docs.rs/mwtitle/latest/mwtitle/struct.Title.html)
    pub fn page_from_title(&self, title: Title) -> Result<Page> {
        if !title.is_local_page() {
            return Err(Error::InvalidPage);
        }
        Ok(Page {
            bot: self.clone(),
            title,
            title_text: Default::default(),
            info: Default::default(),
            baserevid: Default::default(),
        })
    }

    /// Get a `Page` on this wiki using page id.
    ///
    /// The provided input will be validated and may return an
    /// error if invalid.
    pub async fn page_from_id(&self, page_id: u64) -> Result<Page> {
        let mut resp: page::InfoResponse = mwapi_responses::query_api(
            &self.api,
            [("pageids", page_id.to_string())],
        )
        .await?;
        let info = resp
            .query
            .pages
            .pop()
            .expect("API response returned 0 pages");
        let title = self.config.codec.new_title(&info.title)?.remove_fragment();
        if !title.is_local_page() {
            return Err(Error::InvalidPage);
        }
        Ok(Page {
            bot: self.clone(),
            title,
            title_text: Default::default(),
            info: Arc::new(info.clone().into()),
            baserevid: info
                .lastrevid
                .map_or_else(OnceCell::new, OnceCell::with_value),
        })
    }
}

/// Verify file permissions are not obviously misconfigured:
/// * If the file is owned by the current user, it should only be readable to
///   that user
/// * If the file is owned by another user, it should not be world readable
///
/// TODO: support [extended ACLs](https://wiki.archlinux.org/title/Access_Control_Lists)
#[cfg(unix)]
fn check_file_permissions(path: &Path) -> Result<(), ConfigError> {
    use std::os::unix::fs::{MetadataExt, PermissionsExt};
    let metadata = std::fs::metadata(path)?;
    let mode = metadata.permissions().mode();
    let owner = metadata.uid();
    let current_user = unix::get_current_uid();
    let group_readable = mode & 0o40 != 0;
    let world_readable = mode & 0o4 != 0;
    if owner == current_user {
        // We own the file, so it should be only readable to us
        if group_readable || world_readable {
            Err(ConfigError::ReadableConfig(mode))
        } else {
            Ok(())
        }
    } else {
        // Someone else owns the file, so just check it's not world readable
        if world_readable {
            Err(ConfigError::WorldReadableConfig(mode))
        } else {
            Ok(())
        }
    }
}

#[cfg(not(unix))]
fn check_file_permissions(_path: &Path) -> Result<(), ConfigError> {
    // XXX: Implement this for other platforms
    Ok(())
}

// TODO: Can we reuse TitleCodec here?
fn normalize_username(original: &str) -> String {
    // MW normalization, underscores to spaces
    let name = original.replace('_', " ");
    // If it's a bot password, strip the @<name> part
    match name.split_once('@') {
        Some((name, _)) => name.to_string(),
        None => name,
    }
}

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

    pub(crate) fn is_authenticated() -> bool {
        std::env::var("MWAPI_TOKEN").is_ok()
    }

    pub(crate) async fn testwp() -> Bot {
        let username = std::env::var("MWAPI_USERNAME");
        let token = std::env::var("MWAPI_TOKEN");
        let auth = if let (Ok(username), Ok(oauth2_token)) = (username, token) {
            Some(config::Auth::OAuth2 {
                username,
                oauth2_token,
            })
        } else {
            None
        };

        Bot::from_config(config::Config {
            api_url: "https://test.wikipedia.org/w/api.php".to_string(),
            rest_url: "https://test.wikipedia.org/api/rest_v1".to_string(),
            auth,
            general: Default::default(),
            edit: Default::default(),
        })
        .await
        .unwrap()
    }

    fn assert_send_sync<T: Send + Sync>() {}

    /// Assert all these types are Send + Sync
    #[test]
    fn test_send_sync() {
        assert_send_sync::<Bot>();
        assert_send_sync::<Page>();
    }

    #[test]
    fn test_normalize_username() {
        assert_eq!(&normalize_username("Foo"), "Foo");
        assert_eq!(&normalize_username("Foo_bar"), "Foo bar");
        assert_eq!(&normalize_username("Foo@bar"), "Foo");
    }

    #[tokio::test]
    async fn test_get_api() {
        let bot = testwp().await;
        // No errors
        bot.api().get_value(&[("action", "query")]).await.unwrap();
    }

    #[tokio::test]
    async fn test_page() {
        let bot = testwp().await;
        let page = bot.page("Example").unwrap();
        assert_eq!(page.title(), "Example");
        assert_eq!(page.namespace(), 0);
        let page = bot.page_from_database(1, "Example").unwrap();
        assert_eq!(page.title(), "Talk:Example");
        assert_eq!(page.namespace(), 1);
        let error = bot.page("mw:External").unwrap_err();
        assert!(matches!(error, Error::InvalidPage));
    }

    #[tokio::test]
    async fn test_page_from_id() {
        let bot = testwp().await;
        let page = bot.page_from_id(122863).await.unwrap();
        assert_eq!(page.title(), "Mwbot-rs");
        assert_eq!(page.namespace(), 0);
        let page = bot.page_from_id(153569).await.unwrap();
        assert_eq!(page.title(), "Talk:Mwbot-rs");
        assert_eq!(page.namespace(), 1);
    }

    #[tokio::test]
    #[ignore] // flaky, see T341906
    async fn test_user_agent() {
        let bot = testwp().await;
        let version = env!("CARGO_PKG_VERSION");
        let resp: serde_json::Value = bot
            .api()
            .http_client()
            .get("https://httpbin.org/user-agent")
            .send()
            .await
            .unwrap()
            .json()
            .await
            .unwrap();
        let user_agent = resp["user-agent"].as_str().unwrap();
        match &bot.config.username {
            Some(username) => {
                assert_eq!(
                    user_agent,
                    &format!("User:{username} mwbot-rs/{version}")
                );
            }
            None => {
                assert_eq!(user_agent, &format!("mwbot-rs/{version}"));
            }
        }
    }

    /// T333423 regression test
    #[tokio::test]
    async fn test_zero_save_delay() {
        Bot::builder(
            "https://test.wikipedia.org/w/api.php".to_string(),
            "https://test.wikipedia.org/api/rest_v1".to_string(),
        )
        .set_save_delay(0)
        .build()
        .await
        .unwrap();
    }
}