1 /++ Translations. 2 Test: dmd -version=integration_test -version=show -vcolumns -preview=in -preview=dip1000 -g -checkaction=context -allinst -unittest -i -I.. -main -run translation.d 3 +/ 4 module nxt.translation; 5 6 // version = integration_test; 7 8 import nxt.iso_639_1 : Language; 9 10 @safe: 11 12 /++ Translate `text` from `sourceLanguage` to `targetLanguage` via Google Translate. 13 +/ 14 string translateByGoogle(in char[] text, in Language sourceLanguage, in Language targetLanguage) @trusted { 15 import std.conv : to; 16 return translateByGoogle(text, sourceLanguage.to!string, targetLanguage.to!string); 17 ; 18 } 19 20 /++ Translate `text` from `sourceLangCodeCode` to `targetLangCodeCode` via Google Translate. 21 +/ 22 string translateByGoogle(in char[] text, in char[] sourceLangCode, in char[] targetLangCode) @trusted { 23 import std.conv : to; 24 import std.uri : encode; 25 26 import std.net.curl : HTTP; 27 const msg = "http://translate.googleapis.com/translate_a/single?client=gtx&sl="~sourceLangCode ~"&tl="~targetLangCode ~ "&dt=t&q="~encode(text); 28 auto http = HTTP(msg); 29 http.onReceiveStatusLine = (HTTP.StatusLine status) { 30 if (status.code != 200) 31 throw new Exception("Error " ~ status.code.to!string ~ " (" ~ status.reason.to!string ~ ")"); 32 }; 33 34 string responseJson; 35 http.onReceive = (ubyte[] data) { 36 responseJson = cast(string) data; 37 return data.length; 38 }; 39 40 http.perform(); 41 42 typeof(return) result; 43 import std.json : parseJSON, JSONType; 44 foreach (const entry; responseJson.parseJSON().array) { 45 import std.exception : enforce; 46 if (entry.type is JSONType.array) { 47 import std.algorithm : each; 48 foreach (const second; entry.array) { 49 if (second.type is JSONType.array && second[0].type is JSONType..string) { 50 result ~= second[0].str; 51 } 52 } 53 } 54 } 55 56 return result; 57 } 58 59 version(integration_test) 60 @safe unittest { 61 const text = "Text intended for translation into LANGUAGE"; 62 assert(text.tr(Language.en, Language.de) == "Text, der in die SPRACHE übersetzt werden soll"); 63 assert(text.tr(Language.en, Language.tr) == "LANGUAGE diline çevrilmesi amaçlanan metin"); 64 assert(text.tr(Language.en, Language.sv) == "Text avsedd för översättning till SPRÅK"); 65 assert(text.tr("engb", "sv") == "Text avsedd för översättning till SPRÅK"); 66 assert(text.tr("en-GB", "sv") == "Text avsedd för översättning till SPRÅK"); 67 assert(text.tr("en", "zh-CN") == "打算翻译成语言的文本"); 68 assert(text.tr("en", "zh-TW") == "打算翻譯成語言的文本"); 69 } 70 71 version(unittest) 72 private static alias tr = translateByGoogle;