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
/*
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 framework
//!
//! `mwbot` provides a batteries-included framework for building bots
//! for MediaWiki wikis. The goal is to provide a high-level API on top
//! of the [mwapi](https://docs.rs/mwapi) and
//! [parsoid](https://docs.rs/parsoid) crates.
//!
//! ## Configuration
//! Create a `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"
//!
//! [auth]
//! username = "Example"
//! oauth2_token = "[...]"
//! ```
//! See [the 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.
//!
//! You can alternatively use a [BotPassword](https://www.mediawiki.org/wiki/Manual:Bot_passwords) with:
//! ```toml
//! [auth]
//! username = "Example"
//! password = "[...]"
//! ```
//!
//! 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(...)`.
//!
//! ## 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)]

mod builder;
mod config;
mod edit;
mod error;
pub mod file;
pub mod generators;
mod logging;
mod page;
mod siteinfo;
#[cfg(unix)]
mod unix;
pub mod upload;
mod utils;

pub use mwapi::Client as ApiClient;
use mwapi::ErrorFormat;
pub use mwapi_errors::Error;
use mwtitle::{Title, TitleCodec};
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 error::ConfigError;
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: 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![];
        // 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 mut interval = time::interval(time::Duration::from_secs(
            config.edit.save_delay.unwrap_or(10),
        ));
        interval.set_missed_tick_behavior(time::MissedTickBehavior::Delay);
        let api = api.set_user_agent(&user_agent).build().await?;
        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: Arc::new(Mutex::new(interval)),
            },
        })
    }

    /// 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 `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();
        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(),
        })
    }
}

/// 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 username.is_err() || token.is_err() {
            None
        } else {
            Some(config::Auth::OAuth2 {
                username: username.unwrap(),
                oauth2_token: token.unwrap(),
            })
        };

        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 error = bot.page("mw:External").unwrap_err();
        assert!(matches!(error, Error::InvalidPage));
    }

    #[tokio::test]
    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}"));
            }
        }
    }
}