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
//! Translate is the first translation crate in Rust
//! This crate is based on Google and Yandex translators
//! The langage detection is also supported
//!
//! Requirements:
//! - An internet connection
//! - OpenSSL
//!
//! Warning:
//! - This crate use reqwest
//!
//! Functionnalities:
//! - Langage detection (supports: [EN,DE,FR,ES,IT,NL,RU])
//! - Translation (supports: [EN,DE,FR,ES,IT,NL,RU])
//!
//! Examples:
//! ```
//! use translate::*;
//! translate(google(),"This is an test for the translation".to_string(),Langage::EN,Langage::FR,|result| {
//!     println!("{}",result.unwrap());
//! });
//! ```
//!
//! ```
//! use translate::*;
//! detect(yandex(),"This is an test for the detection".to_string(),|result| {
//!     println!("{}",result.unwrap());
//! });
//! ```


extern crate reqwest;

#[cfg(test)]
mod tests {
    #[test]
    fn test() {
        crate::translate(crate::Yandex{},"J'aime les biscuits. Et toi".to_string(),crate::Langage::FR,crate::Langage::EN,|x| {
            assert_eq!("I love the biscuits. And you",x.unwrap());
        });
        crate::translate(crate::Google{},"J'aime les biscuits. Et toi".to_string(),crate::Langage::FR,crate::Langage::EN,|x| {
            assert_eq!("I like cookies. And you",x.unwrap());
        });
        crate::translate(crate::Google{},"J'aime les biscuits. Et toi".to_string(),crate::Langage::FR,crate::Langage::ES,|x| {
            assert_eq!("Me gustan las galletas Y tu",x.unwrap());
        });
        crate::detect(crate::Yandex{},"J'aime les biscuits et vous".to_string(), |x| {
            assert_eq!(crate::Langage::FR,x.unwrap());
        });
        std::thread::sleep(std::time::Duration::from_secs(5));
    }
}

pub fn yandex() -> Yandex {
    Yandex{}
}

pub fn google() -> Yandex {
    Yandex{}
}

fn post_connect(url: &str,body: String) -> Option<String> {
    match reqwest::Client::new().post(url)
		.body(body)
		.send() {
        Ok(mut e) => {
            match e.text() {
                Ok(e1) => {
                    Some(e1)
                },
                _ => {
                    None
                }
            }
        },
        Err(o) => {
            panic!("{}",o);
            None
        },
        _ => {
            None
        }
    }
}

/// The langage Enum which has:
/// - EN: English
/// - FR: Français
/// - DE: German
/// - NL: Dutch
/// - ES: Spanish
/// - IT: Italia
/// - RU: Russia
#[derive(Debug, Clone, Copy)]
pub enum Langage {
	EN,
	FR,
	DE,
	NL,
	ES,
	IT,
	RU
}


pub struct Google;
pub struct Yandex;

/// Implementation of EDetect for Yandex
impl EDetect for Yandex {
    fn detect(&self,text: String) -> Option<Langage> {
        let hj = format!("https://translate.yandex.net/api/v1.5/tr.json/detect?key=trnsl.1.1.20190116T152422Z.a2fee223a3bc5eba.42ea6ba7d5338c7c0132eec6fb5374232029fb9d&text={}", text.replace(" ","%20"));
        match post_connect(&hj,"".to_string()) {
            Some(i) => {
                let mut h = false;
                if !i.contains("\"lang\":\"") {
                    return None;
                }
                for j in i.split("\"lang\":\"") {
                    if !h {
                        h = true;
                        continue;
                    }
                    if !i.contains("\"}") {
                        return None;
                    }
                    for w in j.split("\"}") {
                        return string_to_langage(w.to_string());
                    }
                    return None;
                }
                return None;
            },
            _ => {
                return None;
            }
        }
    }
}

/// Implementation of the PartialEq for Langage
impl std::cmp::PartialEq<Langage> for Langage {
    fn eq(&self, other: &Langage) -> bool {
        match (self, other) {
           (Langage::EN,Langage::EN) => true,
           (Langage::FR,Langage::FR) => true,
           (Langage::DE,Langage::DE) => true,
           (Langage::RU,Langage::RU) => true,
           (Langage::NL,Langage::NL) => true,
           (Langage::ES,Langage::ES) => true,
           (Langage::IT,Langage::IT) => true,
           (_, _) => false,
        }
    }
}

/// Implementation for yandex
impl ETranslate for Yandex {
    fn translate(&self,text: String,_in: Langage,_out: Langage) -> Option<String> {
        let hj = format!("https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20190116T152422Z.a2fee223a3bc5eba.42ea6ba7d5338c7c0132eec6fb5374232029fb9d&text={}&lang={}", text.replace(" ","%20"), format!("{:?}-{:?}", _in, _out).to_lowercase());
        match post_connect(&hj,"".to_string()) {
            Some(i) => {
                let mut h = false;
                if !i.contains("\",\"text\":[\"") {
                    return None;
                }
                for j in i.split("\",\"text\":[\"") {
                    if !h {
                        h = true;
                        continue;
                    }
                    if !i.contains("\"]}") {
                        return None;
                    }
                    for w in j.split("\"]}") {
                        return Some(w.to_string());
                    }
                    return None;
                }
                None
            },
            _ => None
        }
    }
}

/// Implementation for google
impl ETranslate for Google {

	 fn translate(&self,text: String,_in: Langage,_out: Langage) -> Option<String> {
         let ol = [("sl", format!("{:?}",_in)), ("tl", format!("{:?}",_out)), ("q", text)];
         match reqwest::Client::new().post("https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=fr-FR&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e")
            .header("User-Agent","AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1".to_string())
      		.form(&ol)
      		.send() {
            Ok(mut e) => {
                match e.text() {
                    Ok(i) => {
                        if !i.contains("{\"trans\":\"") {
                            return None;
                        }
                        let mut a = "".to_string();
                        let mut h = false;
                        for j in i.split("{\"trans\":\"") {
                            if !h {
                                h = true;
                                continue;
                            }
                            for m in j.split("\",\"orig\":\"") {
                                a = format!("{}{}",a,m);
                                break;
                            }
                        }
                        Some(a)
                    },
                    _ => None
                }
            },
            _ => None
        }
     }
}

/// Trait for text Translation
pub trait ETranslate {
	 fn translate(&self,text: String,_in: Langage,_out: Langage) -> Option<String>;
}

/// Trait for langage Detection
pub trait EDetect {
	 fn detect(&self,text: String) -> Option<Langage>;
}

/// This function translate a text from the first langage to the second.
/// Actually Google and Yandex as the ETranslate trait implemented
/// You need to pass arguments: (<ETranslate implementation>,<text: String>,<srclang: Langage>,<outlang: Langage>,<The callback function which take an Option<String> parameter)
pub fn translate<T,Q>(tr: T,text: String,_in: Langage,_out: Langage,end: Q)
    where T: Send + 'static + ETranslate,
        Q: Send + 'static + FnOnce(Option<String>){
    std::thread::spawn(move || {
        let mut newtext = "".to_string();
        for (_i, c) in text.chars().enumerate() {
            newtext = format!("{}{}",newtext,c);
        }
        end(tr.translate(newtext,_in,_out));
    });
}

/// This function detect the langage of a text.
/// Actually only Yandex as the EDetect trait implemented
/// You need to pass arguments: (<EDetect implementation>,<text: String>,<The callback function which take an Option<Langage> parameter)
pub fn detect<T,Q>(tr: T,text: String,end: Q)
    where T: Send + 'static + EDetect,
        Q: Send + 'static + FnOnce(Option<Langage>){
    std::thread::spawn(move || {
        let mut newtext = "".to_string();
        for (_i, c) in text.chars().enumerate() {
            newtext = format!("{}{}",newtext,c);
        }
        end(tr.detect(newtext));
    });
}

/// Implements the Diplay for langage so you can use the default formatter
impl std::fmt::Display for Langage {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

/// Convert lang code like EN, FR in lower of upper case to a Langage::<lang>
/// Supported langs: [EN, FR, DE, ES, NL, IT, RU]
pub fn string_to_langage(st: String) -> Option<Langage> {
    let fg: &str = &(st.to_lowercase());
    match fg {
        "en" => Some(Langage::EN),
        "fr" => Some(Langage::FR),
        "de" => Some(Langage::DE),
        "es" => Some(Langage::ES),
        "nl" => Some(Langage::NL),
        "it" => Some(Langage::IT),
        "ru" => Some(Langage::RU),
        _ => None

    }
}