add user scripting with lua
This commit is contained in:
+94
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/Shopify/go-lua"
|
||||
"github.com/Shopify/goluago/util"
|
||||
)
|
||||
|
||||
var networkFunctions = []lua.RegistryFunction{
|
||||
{Name: "get", Function: func(l *lua.State) int {
|
||||
url := lua.CheckString(l, 1)
|
||||
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
if err != nil {
|
||||
lua.Errorf(l, "unable to build new request: %s", err.Error())
|
||||
return 0
|
||||
}
|
||||
|
||||
if !l.IsNil(2) {
|
||||
headers, err := util.PullStringTable(l, 2)
|
||||
if err != nil {
|
||||
lua.Errorf(l, "unable to acces headers table: %s", err.Error())
|
||||
return 0
|
||||
}
|
||||
for key, value := range headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
lua.Errorf(l, "error fetching: %s", err.Error())
|
||||
return 0
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
lua.Errorf(l, "error reading body: %s", err.Error())
|
||||
return 0
|
||||
}
|
||||
l.PushString(string(b))
|
||||
l.PushInteger(resp.StatusCode)
|
||||
|
||||
return 2
|
||||
}},
|
||||
}
|
||||
|
||||
var jsonFunctions = []lua.RegistryFunction{
|
||||
{Name: "decode", Function: func(l *lua.State) int {
|
||||
payload := lua.CheckString(l, 1)
|
||||
var output any
|
||||
if err := json.Unmarshal([]byte(payload), &output); err != nil {
|
||||
lua.Errorf(l, "error parsing json: %s", err.Error())
|
||||
return 0
|
||||
}
|
||||
return util.DeepPush(l, output)
|
||||
}},
|
||||
}
|
||||
|
||||
func RunScript(fileName string, token string) (string, error) {
|
||||
l := lua.NewState()
|
||||
lua.OpenLibraries(l)
|
||||
lua.Require(l, "http", func(state *lua.State) int {
|
||||
lua.NewLibrary(l, networkFunctions)
|
||||
return 1
|
||||
|
||||
}, true)
|
||||
|
||||
lua.Require(l, "json", func(state *lua.State) int {
|
||||
lua.NewLibrary(l, jsonFunctions)
|
||||
return 1
|
||||
}, false)
|
||||
err := lua.DoFile(l, fileName)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
l.Global("get_user_info")
|
||||
l.PushString(token)
|
||||
err = l.ProtectedCall(1, 1, 0)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
myStr, ok := l.ToString(-1)
|
||||
if !ok {
|
||||
return "", errors.New("unable to get function result as string")
|
||||
}
|
||||
return myStr, nil
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user