-
Notifications
You must be signed in to change notification settings - Fork 608
/
index.js
117 lines (100 loc) · 3.18 KB
/
index.js
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
var querystring = require('querystring');
var got = require('got');
var safeEval = require('safe-eval');
var token = require('google-translate-token');
var languages = require('./languages');
function translate(text, opts) {
opts = opts || {};
var e;
[opts.from, opts.to].forEach(function (lang) {
if (lang && !languages.isSupported(lang)) {
e = new Error();
e.code = 400;
e.message = 'The language \'' + lang + '\' is not supported';
}
});
if (e) {
return new Promise(function (resolve, reject) {
reject(e);
});
}
opts.from = opts.from || 'auto';
opts.to = opts.to || 'en';
opts.from = languages.getCode(opts.from);
opts.to = languages.getCode(opts.to);
return token.get(text).then(function (token) {
var url = 'https://translate.google.com/translate_a/single';
var data = {
client: 't',
sl: opts.from,
tl: opts.to,
hl: opts.to,
dt: ['at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't'],
ie: 'UTF-8',
oe: 'UTF-8',
otf: 1,
ssel: 0,
tsel: 0,
kc: 7,
q: text
};
data[token.name] = token.value;
return url + '?' + querystring.stringify(data);
}).then(function (url) {
return got(url).then(function (res) {
var result = {
text: '',
from: {
language: {
didYouMean: false,
iso: ''
},
text: {
autoCorrected: false,
value: '',
didYouMean: false
}
},
raw: ''
};
if (opts.raw) {
result.raw = res.body;
}
var body = safeEval(res.body);
body[0].forEach(function (obj) {
if (obj[0]) {
result.text += obj[0];
}
});
if (body[2] === body[8][0][0]) {
result.from.language.iso = body[2];
} else {
result.from.language.didYouMean = true;
result.from.language.iso = body[8][0][0];
}
if (body[7] && body[7][0]) {
var str = body[7][0];
str = str.replace(/<b><i>/g, '[');
str = str.replace(/<\/i><\/b>/g, ']');
result.from.text.value = str;
if (body[7][5] === true) {
result.from.text.autoCorrected = true;
} else {
result.from.text.didYouMean = true;
}
}
return result;
}).catch(function (err) {
var e;
e = new Error();
if (err.statusCode !== undefined && err.statusCode !== 200) {
e.code = 'BAD_REQUEST';
} else {
e.code = 'BAD_NETWORK';
}
throw e;
});
});
}
module.exports = translate;
module.exports.languages = languages;