-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathkey.js
79 lines (72 loc) · 2.15 KB
/
key.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
const axios = require("axios");
const sha256 = require("./sha256.js");
var id = "应用id";
var key = "应用密钥";
function truncate(q){
var len = q.length;
if(len<=20) return q;
return q.substring(0, 10) + len + q.substring(len-10, len);
}
async function search(query) {
var s = (new Date).getTime();
var time = Math.round(new Date().getTime()/1000);
var str1 = id + truncate(query) + s + time + key;
var sig = sha256.sha256(str1);
response = await axios({
method: 'post',
url: 'https://openapi.youdao.com/api',
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
data:{
q:query,
from:"auto",
to:"auto",
appKey:id,
salt:s.toString(),
sign:sig,
signType:"v3",
curtime:time.toString(),
},
transformRequest: [function (data) {
// Do whatever you want to transform the data
let ret = ''
for (let it in data) {
ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
}
return ret
}]
})
const json = response.data;
console.log(json);
if (response.status != 200) {
return [{
title: "错误"
}];
}
if (json.errorCode==0) {
var trans = {title:json.translation.join(";")};
var r = [trans];
if ("basic" in json){
var basic = json.basic.explains.map(each=>{return {title:each}})
r = r.concat(basic);
}
if ("web" in json){
var web = json.web.map(each=>{
return {title:
each.key + ' ' + each.value.join(";")
}
});
r = r.concat(web);
}
// console.log(r);
return r;
}
else {
return [{
title: "错误,请到issue反馈"
}];
}
}
module.exports = {
search: search
};
// search("testtest").then(function(r){console.log(r)});