-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmicrosoft-translator-client.js
239 lines (227 loc) · 6.19 KB
/
microsoft-translator-client.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
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
'use babel'
let request = null
let queryString = null
let htmlparser = null
let Promise = null
let Language = null
import Translator from './translator'
// Constants used to call Microft Translator APIs
const ACCESS_TOKEN_URI = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13'
const TRANSLATE_URL = 'http://api.microsofttranslator.com/V2/Http.svc/Translate'
const SCOPE = 'http://api.microsofttranslator.com'
const GRANT_TYPE = 'client_credentials'
let isInitialized = false
function initialize() {
if (isInitialized) return
//Initialize the modules
request = require('request')
queryString = require("query-string")
htmlparser = require("htmlparser")
Promise = require('bluebird')
Language = require('./language')
isInitialized = true
}
class MicrosoftTranslatorClient extends Translator {
name() { return "Microsoft Translator" }
constructor(clientId, clientSecret) {
super()
initialize()
// Initialize a field
this.setClientIdAndSecret(clientId, clientSecret)
}
canBeUsed(from, to) {
const x1 = MicrosoftTranslatorClient.languageToCode(from)
const x2 = MicrosoftTranslatorClient.languageToCode(to)
if (x1 && x2) return true
else return false
}
setClientIdAndSecret(id, secret) {
this.accessTokenRequestOptions = {
uri: ACCESS_TOKEN_URI,
form: {
client_id: id,
client_secret: secret,
scope: SCOPE,
grant_type: GRANT_TYPE,
},
json: true
}
this.accessToken = null
}
translate(text, from, to) {
const fromCode = MicrosoftTranslatorClient.languageToCode(from)
const toCode = MicrosoftTranslatorClient.languageToCode(to)
return new Promise((resolve, reject) => {
if (!fromCode) {
reject ({
message: `${from.name} cannot be used in Microsoft Translator`
})
} else if (!toCode) {
reject ({
message: `${to.name} cannot be used in Microsoft Translator`
})
} else {
// Check whether the previous access token is valid
const currentTime = new Date().getTime()
if (this.accessToken && this.accessToken.expired > currentTime) {
// valid
resolve(this.accessToken.token)
} else {
const requestedTime = new Date().getTime()
// Get an access token via API if the previous access token is invalid
request.post(this.accessTokenRequestOptions, (error, response, body) => {
if (!error || (200 <= response.statusCode && response.statusCode < 400)) {
// Update the access token
if (body.expires_in) {
this.accessToken = {
token: body.access_token,
expired: requestedTime + body.expires_in * 1000 // sec -> msec
}
}
resolve(body.access_token)
} else {
reject({
message: "Cannot obtain an access token",
statusCode: response.statusCode,
err: error
})
}
})
}
}
}).then(
(token) => {
// Translate via Microft Translator API
const query = {
appId: `Bearer ${token}`,
text: text,
to: toCode,
from: fromCode,
}
const options = {
url: `${TRANSLATE_URL}?${queryString.stringify(query)}`,
json: true
}
return new Promise((resolve, reject) => {
request.get(options, (error, response, body) => {
if (!error || (200 <= response.statusCode && response.statusCode < 400)) {
resolve(body)
} else {
reject({
message: "Cannot translate via MS Translator API",
statusCode: response.statusCode,
err: error
})
}
})
})
}
).then(
(result) => {
// Parse the result
return new Promise((resolve, reject) => {
const handler = new htmlparser.DefaultHandler((error, dom) => {
if (error) {
reject({
message: "Cannot parse the API result",
err: error
})
} else {
resolve(dom[0].children[0].data)
}
})
const parser = new htmlparser.Parser(handler)
parser.parseComplete(result)
})
}
)
}
static languageToCode (language) {
// Language code: https://msdn.microsoft.com/en-us/library/hh456380.aspx
switch (language.code) {
case "cmn":
return "zh-CHS" // TODO I do not know the difference of zu-CHS, zu-CHT, and Mandarin Chinise
case "spa":
return "es"
case "eng":
return "en"
case "rus":
return "ru"
case "arb":
return "ar"
case "hin":
return "hi"
case "por":
return "pt"
case "ind":
return "id"
case "jpn":
return "ja"
case "fra":
return "fr"
case "deu":
return "de"
case "kor":
return "ko"
case "vie":
return "vi"
case "ita":
return "it"
case "tur":
return "tr"
case "urd":
return "ur"
case "pol":
return "pl"
case "ukr":
return "uk"
case "mal":
return "mt"
case "swh":
return "sw"
case "ron":
return "ro"
case "bos":
return "bs-Latn"
case "hrv":
return "hr"
case "Dutch":
return "nl"
case "srp":
return "sr-Latn" // TODO sr-Cyrl?
case "tha":
return "th"
case "ell":
return "el"
case "ces":
return "cs"
case "bul":
return "bg"
case "swe":
return "sv"
case "hat":
return "ht"
case "fin":
return "fi"
case "slk":
return "sk"
case "dan":
return "da"
case "heb":
return "he"
case "cat":
return "ca"
case "lit":
return "lt"
case "slv":
return "sl"
case "lav":
return "lv"
case "est":
return "et"
default:
null
}
}
}
export default MicrosoftTranslatorClient