feat: add simple baidu query api support

This commit is contained in:
JuanZoran
2023-01-30 12:01:58 +08:00
parent ce688eb670
commit d95bb8c8e5
12 changed files with 645 additions and 38 deletions

49
lua/Trans/query/baidu.lua Normal file
View File

@ -0,0 +1,49 @@
local baidu = require('Trans').conf.engine.baidu
local appid = baidu.appid
local appPasswd = baidu.appPasswd
local salt = tostring(math.random(bit.rshift(1, 5)))
local uri = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
if appid == '' or appPasswd == '' then
error('请查看README, 实现在线翻译或者设置将在线翻译设置为false')
end
local ok, curl = pcall(require, 'plenary.curl')
if not ok then
error('plenary not found')
end
local function get_field(word)
local to = 'zh'
local tmp = appid .. word .. salt .. appPasswd
local sign = require('Trans.util.md5').sumhexa(tmp)
return {
q = word,
from = 'auto',
to = to,
appid = appid,
salt = salt,
sign = sign,
}
end
return function(word)
local query = get_field(word)
local output = curl.post(uri, {
data = query,
headers = {
content_type = "application/x-www-form-urlencoded",
}
})
if output.exit == 0 and output.status == 200 then
local res = vim.fn.json_decode(output.body)
if res and res.trans_result then
return {
word = word,
translation = res.trans_result[1].dst,
}
end
end
end

View File

@ -0,0 +1,48 @@
local youdao = require("Trans").conf.engine.youdao
local appKey = youdao.appKey
local appPasswd = youdao.appPasswd
local uri = 'https://openapi.youdao.com/api'
local salt = tostring(math.random(bit.rshift(1, 5)))
local ok, curl = pcall(require, 'plenary.curl')
if not ok then
error('plenary not found')
end
local function get_field(word)
local len = #word
local curtime = tostring(os.time())
local input = len > 20 and
word:sub(1, 10) .. len .. word:sub(-10) or word
-- sign=sha256(应用ID+input+salt+curtime+应用密钥)
local hash = appKey .. input .. salt .. curtime .. appPasswd
local sign = vim.fn.sha256(hash)
return {
q = word,
from = 'auto',
to = 'zh-CHS',
signType = 'v3',
appKey = appKey,
salt = salt,
curtime = curtime,
sign = sign,
}
end
return function(word)
-- return result
local field = get_field(word)
local output = curl.post(uri, {
body = field,
})
if output.exit == 0 and output.status == 200 then
local result = vim.fn.json_decode(output.body)
if result and result.errorCode == 0 then
--- TODO :
end
end
end