-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslator.js
94 lines (78 loc) · 2.47 KB
/
translator.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
const crypto = require('crypto');
const vscode = require('vscode');
const querystring = require('querystring');
const request = require('./request');
async function translate(word) {
if (!/^\w+$/.test(word)) {
return null;
}
try {
// const config = vscode.workspace.getConfiguration().smartyTranslator;
const client = 'web';
const from = 'webdict';
const code = md5(word + from);
const time = (word + from).length % 10;
const key = 'Mk6hqtUp33DGGtoS63tTJbMUYjRrG1Lu';
const lang = 'en'; // config.language;
const data = {
q: word,
le: lang,
t: time,
client,
sign: md5(client + word + time + key + code),
keyfrom: from,
};
const res = await request.post('/jsonapi_s?doctype=json&jsonversion=4', querystring.stringify(data));
console.log('result', res.data)
if (!res.data?.input) {
vscode.window.showInformationMessage(`
Translation plugin api request error,
if you encounter this problem for a long time,
please Issue contact the author to fix.
`);
return null;
}
return res.data;
} catch(error) {
return Promise.reject(error);
}
}
function formator(data, colorful) {
const msg = [];
const result = data.ec;
const c = (tag) => (colorful ? tag : '');
if (result) {
if (result.word) {
if (result.word.usphone && result.word.ukphone) {
msg.push(`${c('**<span style="color:#fd9720;">')}${data.input}${c('</span>**')} 美 /${c('<span style="color:#8abc25;">')}${result.word.usphone}${c('</span>')}/ 英 /${c('<span style="color:#8abc25;">')}${result.word.ukphone}${c('</span>')}/`);
} else {
msg.push(`${c('**<span style="color:#fd9720;">')}${data.input}${c('</span>**')}`);
}
for (item of result.word.trs) {
msg.push(`${item.pos || ''} ${item.tran}`);
}
} else if (result.web_trans) {
for (item of result.web_trans) {
msg.push(item);
}
}
if (result.exam_type) {
msg.push(c('*<span style="color:#888888;">') + result.exam_type.join(' / ') + c('</span>*'));
}
} else if (data.typos?.typo) {
for (item of data.typos.typo) {
msg.push(`[${item.word || ''}] ${item.trans || ''}`);
}
}
return msg;
}
function md5(text) {
return crypto
.createHash('md5')
.update(text)
.digest('hex');
}
module.exports = {
translate,
formator
};