-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (41 loc) · 1.26 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
const got = require('got')
const op = require('object-path')
const { LANGUAGE } = require('./const')
const QQ_TRANSLATE_HOME_URL = 'https://fanyi.qq.com/'
const QQ_TRANSLATE_API_URL = 'https://fanyi.qq.com/api/translate'
const QQ_TRANSLATE_API_ORIGIN = 'https://fanyi.qq.com'
const TRANSLATE_DEFAULT_OPTIONS = {
source: 'auto',
target: LANGUAGE.EN,
text: '',
}
exports.translate = async function translate (options) {
options = Object.assign({}, TRANSLATE_DEFAULT_OPTIONS, options)
let { body } = await got(QQ_TRANSLATE_HOME_URL)
let cookie = (body.match(/\s*document\.cookie.*/g) || []).map((assign) => {
let matched = assign.match(/document.cookie\s=\s\"(.*?)\"/)
if (!matched) {
return
}
return matched[1]
}).filter(Boolean).join('; ')
let response = await got.post(QQ_TRANSLATE_API_URL, {
body: {
source: options.source,
target: options.target,
sourceText: options.text,
},
json: true,
headers: {
origin: QQ_TRANSLATE_API_ORIGIN,
cookie: cookie,
},
})
let records = op.get(response, 'body.translate.records') || []
let result = records.map(({ targetText }) => targetText).join('')
if (!result) {
console.error(response)
throw new Error('Response fault.')
}
return result
}