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
/*
Copyright (C) 2020-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 2 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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
//! # parsoid-rs
//!
//! The `parsoid` crate is a wrapper around [Parsoid HTML](https://www.mediawiki.org/wiki/Specs/HTML/2.2.0)
//! that provides convenient accessors for processing and extraction.

//! Inspired by [mwparserfromhell](https://github.com/earwig/mwparserfromhell/),
//! [parsoid-jsapi](https://github.com/wikimedia/parsoid-jsapi) and built on top
//! of [Kuchiki (朽木)](https://github.com/kuchiki-rs/kuchiki).
//!
//! # Quick starts
//!
//! Fetch HTML and extract the value of a template parameter:
//! ```rust
//! use parsoid::prelude::*;
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let client = ParsoidClient::new("https://en.wikipedia.org/api/rest_v1", "parsoid-rs demo")?;
//! let code = client.get("Taylor_Swift").await?;
//! for template in code.filter_templates()? {
//!     if template.name() == "Template:Infobox person" {
//!         let birth_name = template.get_param("birth_name").unwrap();
//!         assert_eq!(birth_name, "Taylor Alison Swift");
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! Add a link to a page and convert it to wikitext:
//! ```rust
//! use parsoid::prelude::*;
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let client = ParsoidClient::new("https://en.wikipedia.org/api/rest_v1", "parsoid-rs demo")?;
//! let code = client.get("Wikipedia:Sandbox").await?;
//! let link = WikiLink::new(
//!     "./Special:Random",
//!     &Wikicode::new_text("Visit a random page")
//! );
//! code.append(&link);
//! let wikitext = client.transform_to_wikitext(&code).await?;
//! assert!(wikitext.ends_with("[[Special:Random|Visit a random page]]"));
//! # Ok(())
//! # }
//! ```
//! This crate provides no functionality for actually saving a page, you'll
//! need to use something like [`mediawiki`](https://github.com/magnusmanske/mediawiki_rust).
//!
//! ## Architecture
//! Conceptually this crate provides wiki-related types on top of an HTML processing
//! library. There are three primary constructs to be aware of: `Wikicode`,
//! `Wikinode`, and `Template`.
//!
//! `Wikicode` represents a container of an entire wiki page, equivalent to a
//! `<html>` or `<body>` node. It some provides convenience functions like
//! `filter_links()` to easily operate on and mutate a specific Wikinode.
//! (For convenience, `Wikicode` is also a `Wikinode`.)
//!
//! ```rust
//! use parsoid::prelude::*;
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let client = ParsoidClient::new("https://en.wikipedia.org/api/rest_v1", "parsoid-rs demo")?;
//! let code = client.get("Taylor Swift").await?;
//! for link in code.filter_links() {
//!     if link.target() == "You Belong with Me" {
//!         // ...do something
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! Filter functions are only provided for common types as an optimization,
//! but it's straightforward to implement for other types:
//! ```rust
//! use parsoid::prelude::*;
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let client = ParsoidClient::new("https://en.wikipedia.org/api/rest_v1", "parsoid-rs demo")?;
//! let code = client.get("Taylor Swift").await?;
//! let entities: Vec<HtmlEntity> = code
//!     .descendants()
//!     .filter_map(|node| node.as_html_entity())
//!     .collect();
//! # Ok(())
//! # }
//! ```
//!
//! `Wikinode` is an enum representing all of the different types of Wikinodes,
//! mostly to enable functions that accept/return various types of nodes.
//!
//! A Wikinode provides convenience functions for working with specific
//! types of MediaWiki constructs. For example, the `WikiLink` type wraps around
//! a node of `<a rel="mw:WikiLink" href="...">...</a>`. It provides functions
//! for accessing or mutating the `href` attribute. To access the link text
//! you would need to use `.children()` and modify or append to those nodes.
//! Standard mutators like `.append()` and `.insert_after()` are part of the
//! `WikinodeIterator` trait, which is automatically imported in the prelude.
//!
//! The following nodes have been implemented so far:
//! * `BehaviorSwitch`: `__TOC__`, `{{DISPLAYTITLE:}}`
//! * `Category`: `[[Category:Foo]]`
//! * `Comment`: `<!-- ... -->`
//! * `ExtLink`: `[https://example.org Text]`
//! * `Heading`: `== Some text ==`
//! * `HtmlEntity`: `&nbsp;`
//! * `InterwikiLink`: `[[:en:Foo]]`
//! * `LanguageLink`: `[[en:Foo]]`
//! * `Nowiki`: `<nowiki>[[foo]]</nowiki>`
//! * `Redirect`: `#REDIRECT [[Foo]]`
//! * `Section`: Contains a `Heading` and its contents
//! * `WikiLink`: `[[Foo|bar]]`
//! * `Generic` - any node that we don't have a more specific type for.
//!
//! Each Wikinode is effectively a wrapper around `Rc<Node>`, making it cheap to
//! clone around (I think). However, this also makes it not thread-safe.
//!
//! ## Templates
//! Unlike Wikinodes, Templates do not have a 1:1 mapping with a HTML node, it's
//! possible to have multiple templates in one node. The main way to get
//! `Template` instances is to call `Wikicode::filter_templates()`.
//!
//! See the [`Template`](./struct.Template.html) documentation for more details
//! and examples.

#[cfg(feature = "http")]
mod api;
/// Errors
pub mod error;
mod iter;
/// Re-export of IndexMap
pub mod map {
    pub use indexmap::IndexMap;
}
pub mod node;

/// Prelude to import to pull in traits and useful types
///
/// ```rust
/// use parsoid::prelude::*;
/// ```
pub mod prelude {
    #[cfg(feature = "http")]
    pub use crate::api::Client as ParsoidClient;
    pub use crate::iter::WikinodeIterator;
    pub use crate::map;
    pub use crate::node::{
        BehaviorSwitch, Category, Comment, ExtLink, Heading, HtmlEntity,
        InterwikiLink, LanguageLink, Nowiki, Redirect, Section, WikiLink,
        Wikinode,
    };
    pub use crate::template::Template;
    pub use crate::{Result, Wikicode};
}
mod template;

#[cfg(feature = "http")]
pub use crate::api::Client;
pub use crate::error::Error;
pub use crate::iter::WikinodeIterator;
use crate::node::{Comment, Redirect, Wikinode};
pub use crate::template::Template;
use kuchiki::traits::*;
use kuchiki::NodeRef;
use markup5ever::{LocalName, QualName};
use std::ops::Deref;

pub type Result<T> = std::result::Result<T, Error>;

#[macro_use]
extern crate markup5ever;

/// Helper wrapper to create a new `QualName`
fn build_qual_name(tag: LocalName) -> QualName {
    QualName::new(None, ns!(html), tag)
}

/// Container for HTML, usually represents the entire page
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Wikicode {
    document: NodeRef,
    etag: Option<String>,
}

impl Deref for Wikicode {
    type Target = NodeRef;

    fn deref(&self) -> &Self::Target {
        &self.document
    }
}

impl Wikicode {
    /// Create a new `Wikicode` instance from raw Parsoid HTML.
    pub fn new(body: &str) -> Self {
        Self {
            document: kuchiki::parse_html().one(body),
            etag: None,
        }
    }

    /// Create a new HTML node with the given tag
    /// ```
    /// # use parsoid::prelude::*;
    /// let node = Wikicode::new_node("b");
    /// // Append your list items
    /// node.append(&Wikicode::new_text("bolded text"));
    /// assert_eq!(&node.to_string(), "<b>bolded text</b>")
    /// ```
    pub fn new_node(tag: &str) -> Self {
        let document =
            NodeRef::new_element(crate::build_qual_name(tag.into()), vec![]);
        Self {
            document,
            etag: None,
        }
    }

    /// Create a text node with the given contents
    /// ```
    /// # use parsoid::prelude::*;
    /// let node = Wikicode::new_text("foo bar");
    /// assert_eq!(&node.to_string(), "foo bar");
    /// // Tags will be escaped
    /// let weird_node = Wikicode::new_text("foo <bar>");
    /// assert_eq!(&weird_node.to_string(), "foo &lt;bar&gt;");
    /// ```
    pub fn new_text(text: &str) -> Self {
        let document = NodeRef::new_text(text);
        Self {
            document,
            etag: None,
        }
    }

    /// Create a new `Wikicode` instance from a node we already have
    fn new_from_node(node: &NodeRef) -> Self {
        Wikicode {
            document: node.clone(),
            etag: None,
        }
    }

    /// Set the etag that came with this request. This allows Parsoid to
    /// preserve formatting and avoid dirty diffs when converting modified
    /// HTML back to wikitext.
    pub fn set_etag(&mut self, etag: &str) {
        self.etag = Some(etag.to_string());
    }

    /// Get the etag that was set on this Wikicode instance.
    pub fn get_etag(&self) -> Option<&str> {
        self.etag.as_deref()
    }

    /// Get the revision id associated with the Parsoid HTML, if it has one.
    pub fn revision_id(&self) -> Option<u32> {
        match self.html_element() {
            Some(element) => element
                .as_element()
                .unwrap()
                .attributes
                .borrow()
                .get("about")
                .map(|url| {
                    url.to_string()
                        .split('/')
                        .last()
                        .unwrap()
                        .to_string()
                        .parse()
                        .unwrap()
                }),
            None => None,
        }
    }

    /// Get the title associated with the Parsoid HTML, if it has one.
    pub fn title(&self) -> Option<String> {
        match self.document.select_first("title") {
            Ok(element) => Some(element.as_node().text_contents()),
            Err(_) => None,
        }
    }

    pub fn get_redirect(&self) -> Option<Redirect> {
        match self.document.select_first(Redirect::SELECTOR) {
            Ok(element) => Some(Redirect::new_from_node(element.as_node())),
            Err(_) => None,
        }
    }

    /// Get the root <html> element if it exists, primarily intended to help
    /// getting metadata.
    fn html_element(&self) -> Option<NodeRef> {
        match self.document.select_first("html") {
            Ok(element) => Some(element.as_node().clone()),
            Err(_) => None,
        }
    }

    /// Get the <body> element or everything if there is no body. This is
    /// intented to help ensure nodes (e.g. comments) just come from the body.
    fn body_element(&self) -> Wikinode {
        match self.document.select_first("body") {
            // Just the <body>
            Ok(element) => Wikinode::new_from_node(element.as_node()),
            // Everything as there is no <body>
            Err(_) => Wikinode::Generic(self.clone()),
        }
    }

    /// Get a plain text representation of the Parsoid HTML with all markup
    /// stripped.
    pub fn text_contents(&self) -> String {
        self.body_element().text_contents()
    }

    /// Get a list of all comments (`<!-- example -->`)
    pub fn filter_comments(&self) -> Vec<Comment> {
        self.body_element()
            .inclusive_descendants()
            .filter_map(|node| node.as_comment())
            .collect()
    }
}

impl From<Wikinode> for Wikicode {
    fn from(node: Wikinode) -> Self {
        Wikicode::new_from_node(node.as_node())
    }
}

impl WikinodeIterator for Wikicode {
    fn as_node(&self) -> &NodeRef {
        &self.document
    }
}

fn clean_link(link: &str) -> String {
    link.trim_start_matches("./").replace("_", " ")
}

fn full_link(title: &str) -> String {
    format!("./{}", title.replace(" ", "_"))
}

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

    #[test]
    fn test_clean_link() {
        assert_eq!(
            clean_link("./Template:Foo_bar"),
            "Template:Foo bar".to_string()
        );
        assert_eq!(clean_link("ifeq"), "ifeq".to_string());
    }

    #[test]
    fn test_full_link() {
        assert_eq!(
            full_link("Template:Foo bar"),
            "./Template:Foo_bar".to_string()
        );
        // Yes, this is not what you'd expect. It's not a direct reversal of clean_link()
        assert_eq!(full_link("ifeq"), "./ifeq".to_string());
    }
}