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
/*
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/>.
 */

use crate::edit::{EditResponse, SaveOptions, Saveable};
use crate::{Bot, Error, Result, Wikicode};
use log::info;
use mwapi_responses::prelude::*;
use parsoid::Result as ParsoidResult;

/// Represents a wiki page and provides accessors and mutators.
#[derive(Debug, Clone)]
pub struct Page {
    pub(crate) bot: Bot,
    pub(crate) title: String,
}

// Use placeholder inprop for now
#[query(prop = "info", inprop = "associatedpage", redirects = "1")]
struct InfoResponse {}

impl Page {
    /// Get the title of the page
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Whether the page exists or not
    pub async fn exists(&self) -> Result<bool> {
        let mut params = InfoResponse::params().to_vec();
        params.push(("titles", &self.title));
        let resp: InfoResponse = self.bot.api.get(&params).await?;
        Ok(!resp.query.pages[0].missing)
    }

    /// If this page is a redirect, get the page it targets
    pub async fn get_redirect_target(&self) -> Result<Option<Page>> {
        let mut params = InfoResponse::params().to_vec();
        params.push(("titles", &self.title));
        let resp: InfoResponse = self.bot.api.get(&params).await?;
        Ok(resp
            .query
            .redirects
            .get(0)
            .map(|redirect| self.bot.get_page(&redirect.to)))
    }

    /// Get Parsoid HTML for the latest revision of the page
    pub async fn get_html(&self) -> ParsoidResult<Wikicode> {
        Ok(self.bot.parsoid.get(&self.title).await?)
    }

    /// Get Parsoid HTML for the specified revision
    pub async fn get_revision_html(
        &self,
        revid: u32,
    ) -> ParsoidResult<Wikicode> {
        Ok(self.bot.parsoid.get_revision(&self.title, revid).await?)
    }

    pub async fn get_wikitext(&self) -> Result<String> {
        let resp = self
            .bot
            .api
            .get_value(&[
                ("action", "query"),
                ("titles", &self.title),
                ("prop", "revisions"),
                ("rvprop", "content"),
                ("rvslots", "main"),
            ])
            .await?;
        let page = resp["query"]["pages"][0].as_object().unwrap();
        if page.contains_key("missing") {
            Err(Error::PageDoesNotExist(self.title.to_string()))
        } else {
            let revisions = page.get("revisions").unwrap().clone();
            Ok(revisions[0]["slots"]["main"]["content"]
                .as_str()
                .unwrap()
                .to_string())
        }
    }

    /// Save the page using the specified HTML
    pub async fn save<S: Into<Saveable>>(
        &self,
        edit: S,
        opts: &SaveOptions,
    ) -> Result<EditResponse> {
        let edit = edit.into();
        let wikitext = if let Some(html) = edit.html {
            // Check {{nobots}}
            let code: Wikicode = html.into();
            if self.bot.config.respect_nobots {
                let username = self
                    .bot
                    .config
                    .username
                    .clone()
                    .unwrap_or_else(|| "unknown".to_string());
                if !crate::utils::nobots(&code, &username)? {
                    return Err(Error::Nobots);
                }
            }
            self.bot.parsoid.transform_to_wikitext(&code).await?
        } else if let Some(wikitext) = edit.wikitext {
            // TODO: check {{nobots}}
            wikitext
        } else {
            unreachable!("Not possible to construct a EditRequest with no HTML nor wikitext")
        };
        let mut params: Vec<(&'static str, String)> = [
            ("action", "edit".to_string()),
            ("title", self.title.to_string()),
            ("text", wikitext),
            ("summary", opts.summary.to_string()),
        ]
        .to_vec();
        if let Some(revid) = edit.baserevid {
            params.push(("baserevid", revid.to_string()));
        }
        if !opts.mark_as_bot.unwrap_or(self.bot.config.mark_as_bot) {
            params.push(("bot", "1".to_string()));
        }
        if !opts.tags.is_empty() {
            params.push(("tags", opts.tags.join("|")));
        }
        // TODO: would be nice if we could output a sleep message here
        self.bot.state.save_timer.lock().await.tick().await;
        info!("Saving [[{}]]", &self.title);
        let resp = self.bot.api.post_with_token("csrf", &params).await?;
        match resp["edit"]["result"].as_str() {
            Some("Success") => {
                Ok(serde_json::from_value(resp["edit"].clone())?)
            }
            // Some legacy code might return "result": "Failure" but the
            // structure is totally unspecified, so we're best off just
            // passing the entire blob into the error in the hope it
            // contains some clue.
            _ => Err(Error::UnknownSaveFailure(resp)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::{is_authenticated, testwp};
    use crate::Error;
    use std::time::SystemTime;

    #[tokio::test]
    async fn test_exists() {
        let bot = testwp().await;
        let page = bot.get_page("Main Page");
        assert!(page.exists().await.unwrap());
        let page2 = bot.get_page("DoesNotExistPlease");
        assert!(!page2.exists().await.unwrap());
    }

    #[tokio::test]
    async fn test_get_redirect_target() {
        let bot = testwp().await;
        let redir = bot.get_page("Redirect");
        let target = redir.get_redirect_target().await.unwrap().unwrap();
        // "Redirect" points to "Main Page"
        assert_eq!(target.title(), "Main Page");
        // "Main Page" is not a redirect
        assert!(target.get_redirect_target().await.unwrap().is_none());
    }

    #[tokio::test]
    async fn test_get_content() {
        let bot = testwp().await;
        let page = bot.get_page("Main Page");
        let html = page.get_html().await.unwrap();
        assert_eq!(html.get_title().unwrap(), "Main Page".to_string());
        assert_eq!(
            html.select_first("b").unwrap().text_contents(),
            "test wiki".to_string()
        );
        let wikitext = page.get_wikitext().await.unwrap();
        assert!(wikitext.contains("'''test wiki'''"));
    }

    #[tokio::test]
    async fn test_missing_page() {
        let bot = testwp().await;
        let page = bot.get_page("DoesNotExistPlease");
        let err = page.get_html().await.unwrap_err();
        match err {
            Error::PageDoesNotExist(page) => {
                assert_eq!(&page, "DoesNotExistPlease")
            }
            err => {
                panic!("Unexpected error: {:?}", err)
            }
        }
        let err2 = page.get_wikitext().await.unwrap_err();
        match err2 {
            Error::PageDoesNotExist(page) => {
                assert_eq!(&page, "DoesNotExistPlease")
            }
            err => {
                panic!("Unexpected error: {:?}", err)
            }
        }
    }

    #[tokio::test]
    async fn test_save() {
        if !is_authenticated() {
            return;
        }

        let bot = testwp().await;
        let page = bot.get_page("mwbot-rs/Save");
        let wikitext = format!(
            "It has been {} seconds since the epoch.",
            SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_secs()
        );
        let resp = page
            .save(wikitext, &SaveOptions::summary("Test suite edit"))
            .await
            .unwrap();
        dbg!(&resp);
        assert_eq!(&resp.title, "Mwbot-rs/Save");
    }

    #[tokio::test]
    async fn test_protected() {
        if !is_authenticated() {
            return;
        }

        let bot = testwp().await;
        let page = bot.get_page("mwbot-rs/Protected");
        let wikitext = "Wait, I can edit this page?".to_string();
        let error = page
            .save(wikitext, &SaveOptions::summary("Test suite edit"))
            .await
            .unwrap_err();
        dbg!(&error);
        assert!(matches!(error, Error::ProtectedPage));
    }

    #[tokio::test]
    async fn test_spamfilter() {
        if !is_authenticated() {
            return;
        }

        let bot = testwp().await;
        let page = bot.get_page("mwbot-rs/SpamBlacklist");
        let wikitext = "https://bitly.com/12345".to_string();
        let error = page
            .save(wikitext, &SaveOptions::summary("Test suite edit"))
            .await
            .unwrap_err();
        if let Error::SpamFilter { matches, .. } = error {
            assert_eq!(matches, vec!["bitly.com".to_string()])
        } else {
            panic!("{:?} doesn't match", error)
        }
    }
}