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
extern crate reqwest;
#[macro_use]
extern crate serde;
extern crate serde_json;

use serde::de::Error as DeError;
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use std::error::Error as StdError;
use std::fmt;

pub struct LanguageTool {
    instance_url: String,
    http_client: reqwest::Client,
}

#[derive(Debug)]
pub enum Error {
    ReqwestError(reqwest::Error),
    BadStatusError(reqwest::StatusCode),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::ReqwestError(ref e) => fmt::Display::fmt(e, f),
            Error::BadStatusError(ref e) => fmt::Display::fmt(e, f),
        }
    }
}

impl StdError for Error {
    fn description(&self) -> &str {
        match *self {
            Error::ReqwestError(ref e) => e.description(),
            Error::BadStatusError(ref e) => {
                e.canonical_reason().unwrap_or("Unregistered status code")
            }
        }
    }

    fn cause(&self) -> Option<&StdError> {
        match *self {
            Error::ReqwestError(ref e) => Some(e),
            Error::BadStatusError(_) => None,
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Language {
    pub name: String,
    pub code: String,
    pub long_code: String,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Request {
    pub text: String,
    pub language: String,
    pub mother_tongue: Option<String>,
    pub preferred_variants: Option<String>,
    pub enabled_rules: Option<String>,
    pub disabled_rules: Option<String>,
    pub enabled_categories: Option<String>,
    pub disabled_categories: Option<String>,
    pub enabled_only: Option<bool>,
}

impl Request {
    pub fn new(text: String, language: String) -> Self {
        Request {
            text: text,
            language: language,
            mother_tongue: None,
            preferred_variants: None,
            enabled_rules: None,
            disabled_rules: None,
            enabled_categories: None,
            disabled_categories: None,
            enabled_only: None,
        }
    }
}

#[derive(Debug, Deserialize)]
pub struct Response {
    pub software: Option<Software>,
    pub language: Option<ResponseLanguage>,
    pub matches: Option<Vec<Match>>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Software {
    pub name: String,
    pub version: String,
    pub build_date: String,
    // In older versions the version is a String:
    // https://github.com/languagetool-org/languagetool/issues/712
    #[serde(deserialize_with = "number_or_numeric_string")]
    pub api_version: i64,
    pub status: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct ResponseLanguage {
    pub name: String,
    pub code: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Match {
    pub message: String,
    pub short_message: Option<String>,
    pub offset: i64,
    pub length: i64,
    pub replacements: Vec<Replacement>,
    pub context: Context,
    pub rule: Option<Rule>,
}

#[derive(Debug, Deserialize)]
pub struct Replacement {
    pub value: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Context {
    pub text: String,
    pub offset: i64,
    pub length: i64,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Rule {
    pub id: String,
    pub sub_id: Option<String>,
    pub description: String,
    pub urls: Option<Vec<Url>>,
    pub issue_type: Option<String>,
    pub category: Category,
}

#[derive(Debug, Deserialize)]
pub struct Url {
    pub value: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct Category {
    pub id: Option<String>,
    pub name: Option<String>,
}

impl LanguageTool {
    pub fn new(instance_url: &str) -> Result<Self, Error> {
        let instance_url = String::from(instance_url.trim_end_matches('/'));
        let http_client = reqwest::Client::builder()
            .build()
            .map_err(Error::ReqwestError)?;

        Ok(LanguageTool {
            instance_url: instance_url,
            http_client: http_client,
        })
    }

    pub fn list_languages(&self) -> Result<Vec<Language>, Error> {
        let mut res = self
            .http_client
            .get(&(self.instance_url.clone() + "/v2/languages"))
            .send()
            .map_err(Error::ReqwestError)?;

        if res.status().is_success() {
            res.json().map_err(Error::ReqwestError)
        } else {
            Err(Error::BadStatusError(res.status()))
        }
    }

    pub fn check(&self, req: Request) -> Result<Response, Error> {
        let mut res = self
            .http_client
            .post(&(self.instance_url.clone() + "/v2/check"))
            .form(&req)
            .send()
            .map_err(Error::ReqwestError)?;

        if res.status().is_success() {
            res.json().map_err(Error::ReqwestError)
        } else {
            Err(Error::BadStatusError(res.status()))
        }
    }
}

fn number_or_numeric_string<'de, D>(de: D) -> Result<i64, D::Error>
where
    D: Deserializer<'de>,
{
    let helper: Value = Deserialize::deserialize(de)?;

    match helper {
        Value::Number(n) => n.as_i64().ok_or_else(|| DeError::custom("Not an integer")),
        Value::String(s) => s.parse().map_err(DeError::custom),
        _ => Err(DeError::custom("Neither number nor a numeric string")),
    }
}