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

use crate::{Error, Result, Wikicode};
use log::debug;
use reqwest::header::HeaderMap;
use reqwest::{header, Client as HttpClient, Request, Response};
use std::sync::Arc;
use tokio::sync::Semaphore;
use urlencoding::encode;

/// Version of library embedded in user-agent
const VERSION: &str = env!("CARGO_PKG_VERSION");
/// `Accept` header for [content negotiation](https://www.mediawiki.org/wiki/Parsoid/API#Content_Negotiation)
const ACCEPT_2_2_0: &str = "text/html; charset=utf-8; profile=\"https://www.mediawiki.org/wiki/Specs/HTML/2.2.0\"";

/// HTTP client to get Parsoid HTML from MediaWiki's Rest APIs
///
/// Note: This requires the `http` feature is enabled (it is by default).
pub struct Client {
    http: HttpClient,
    base_url: String,
    semaphore: Arc<Semaphore>,
}

impl Client {
    /// Create a new Client. `base_url` should either point to `rest.php` or
    /// Restbase. For Wikimedia projects it would look something like:
    /// `https://en.wikipedia.org/api/rest_v1`. For other wikis it might be:
    /// `https://wiki.example.org/rest.php/wiki.example.org/v3`.
    ///
    /// (Note: no trailing slash on either endpoint style.)
    pub fn new(base_url: &str, user_agent: &str) -> Result<Self> {
        let mut headers = header::HeaderMap::new();
        headers.insert(
            header::ACCEPT,
            ACCEPT_2_2_0.parse().expect("Unable to parse Accept header"),
        );
        Ok(Client {
            http: HttpClient::builder()
                .user_agent(format!("parsoid-rs/{} {}", VERSION, user_agent))
                .default_headers(headers)
                .build()?,
            base_url: base_url.to_string(),
            // TODO: can we do better than just hardcoding a concurrency of 10?
            semaphore: Arc::new(Semaphore::new(10)),
        })
    }

    /// Helper to get a page's HTML
    async fn page_html(
        &self,
        page: &str,
        revid: Option<u32>,
    ) -> Result<Response> {
        let url_part = format!("{}/page/html/{}", self.base_url, encode(page));
        let url = if let Some(revid) = revid {
            format!("{}/{}", url_part, revid)
        } else {
            url_part
        };
        let req = self.http.get(&url).build()?;
        let _lock = self.semaphore.acquire().await?;
        log_request(&req);
        // TODO: improve error handling
        let resp = self.http.execute(req).await?;
        log_response(&resp);
        drop(_lock);
        if resp.status() == 404 {
            Err(Error::PageDoesNotExist(page.to_string()))
        } else {
            Ok(resp.error_for_status()?)
        }
    }

    /// Get a `Wikicode` instance for the specified page
    pub async fn get(&self, page: &str) -> Result<Wikicode> {
        let resp = self.page_html(page, None).await?;
        let etag = match &resp.headers().get("etag") {
            Some(etag) => match etag.to_str() {
                Ok(etag) => etag.to_string(),
                Err(_) => return Err(Error::InvalidEtag),
            },
            None => return Err(Error::InvalidEtag),
        };
        let mut code = Wikicode::new(&resp.text().await?);
        code.set_etag(&etag);
        Ok(code)
    }

    /// Get a `Wikicode` instance for the specified page at the specified revision
    pub async fn get_revision(
        &self,
        page: &str,
        revid: u32,
    ) -> Result<Wikicode> {
        let resp = self.page_html(page, Some(revid)).await?;
        let etag = match &resp.headers().get("etag") {
            Some(etag) => match etag.to_str() {
                Ok(etag) => etag.to_string(),
                Err(_) => return Err(Error::InvalidEtag),
            },
            None => return Err(Error::InvalidEtag),
        };
        let mut code = Wikicode::new(&resp.text().await?);
        code.set_etag(&etag);
        Ok(code)
    }

    /// Get the Parsoid HTML for the specified page
    pub async fn get_raw(&self, page: &str) -> Result<String> {
        Ok(self.page_html(page, None).await?.text().await?)
    }

    /// Get the Parsoid HTML for the specified page at the specified revision
    pub async fn get_revision_raw(
        &self,
        page: &str,
        revid: u32,
    ) -> Result<String> {
        Ok(self.page_html(page, Some(revid)).await?.text().await?)
    }

    /// Get a `Wikicode` instance for the specified wikitext
    pub async fn transform_to_html(&self, wikitext: &str) -> Result<Wikicode> {
        let html = self.transform_to_html_raw(wikitext).await?;
        Ok(Wikicode::new(&html))
    }

    /// Get the Parsoid HTML for the specified wikitext
    pub async fn transform_to_html_raw(
        &self,
        wikitext: &str,
    ) -> Result<String> {
        let url = format!("{}/transform/wikitext/to/html", self.base_url);
        let req = self
            .http
            .post(&url)
            .form(&[("wikitext", wikitext)])
            .build()?;
        let _lock = self.semaphore.acquire().await?;
        log_request(&req);
        let resp = self.http.execute(req).await?;
        log_response(&resp);
        drop(_lock);
        let html = resp.error_for_status()?.text().await?;
        Ok(html)
    }

    /// Get the wikitext for the specified Parsoid HTML
    pub async fn transform_to_wikitext(
        &self,
        code: &Wikicode,
    ) -> Result<String> {
        let mut url = format!("{}/transform/html/to/wikitext", self.base_url);
        if let Some(title) = code.title() {
            url.push_str(&format!("/{}", encode(&title)));
            if let Some(revid) = code.revision_id() {
                url.push_str(&format!("/{}", revid));
            }
        }
        let mut header_map = HeaderMap::new();
        if let Some(etag) = code.get_etag() {
            header_map.insert(header::IF_MATCH, etag.parse().unwrap());
        }

        let req = self
            .http
            .post(&url)
            .form(&[("html", code.to_string())])
            .headers(header_map)
            .build()?;
        let _lock = self.semaphore.acquire().await?;
        log_request(&req);
        let resp = self.http.execute(req).await?;
        log_response(&resp);
        drop(_lock);
        let wikitext = resp.error_for_status()?.text().await?;
        Ok(wikitext)
    }

    /// Get the wikitext for the specified Parsoid HTML
    pub async fn transform_to_wikitext_raw(
        &self,
        html: &str,
    ) -> Result<String> {
        let url = format!("{}/transform/html/to/wikitext", self.base_url);
        let req = self.http.post(&url).form(&[("html", html)]).build()?;
        let _lock = self.semaphore.acquire().await?;
        log_request(&req);
        let resp = self.http.execute(req).await?;
        log_response(&resp);
        drop(_lock);
        let wikitext = resp.error_for_status()?.text().await?;
        Ok(wikitext)
    }
}

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);
}