feat: add online query support

This commit is contained in:
JuanZoran
2023-01-30 20:09:57 +08:00
parent d95bb8c8e5
commit 2377dbc0a7
9 changed files with 272 additions and 133 deletions

View File

@ -1,17 +1,14 @@
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 salt = tostring(math.random(bit.lshift(1, 15)))
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 post = require('Trans.util.curl').POST
local function get_field(word)
local to = 'zh'
@ -28,22 +25,40 @@ local function get_field(word)
}
end
--- this is a nice plugin
---返回一个channel
---@param word string
---@return function
return function(word)
local query = get_field(word)
local output = curl.post(uri, {
local result
post(uri, {
data = query,
headers = {
content_type = "application/x-www-form-urlencoded",
}
},
callback = function(str)
if result then
return
elseif str ~= '' then
local res = vim.fn.json_decode(str)
if res and res.trans_result then
result = {
word = word,
translation = res.trans_result[1].dst,
}
else
result = false
end
else
result = false
end
end,
})
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
return function()
return result
end
end