residentsleeper/scripting/minecraft/players.go
Tyler b52b38179a
Some checks failed
continuous-integration/drone/push Build is failing
Major updates/patches, functionality, api
2020-07-09 21:01:29 -04:00

126 lines
1.9 KiB
Go

package minecraft
import (
"compress/gzip"
"github.com/ppacher/nbt"
lua "github.com/yuin/gopher-lua"
"meow.tf/residentsleeper/events"
"os"
"path"
"sync"
)
var (
BasePath string
WorldPath string
uuids = make(map[string]string)
uuidLock sync.RWMutex
)
func init() {
events.On(events.Authenticated, onAuthenticated)
events.On(events.Leave, onLeave)
}
func onAuthenticated(args ...interface{}) {
name := args[0].(string)
uuid := args[1].(string)
uuidLock.Lock()
defer uuidLock.Unlock()
uuids[name] = uuid
}
func onLeave(args ...interface{}) {
uuidLock.Lock()
defer uuidLock.Unlock()
delete(uuids, args[0].(string))
}
func GetUUID(name string) (string, bool) {
uuidLock.RLock()
defer uuidLock.RUnlock()
uuid, exists := uuids[name]
return uuid, exists
}
func Loader(L *lua.LState) int {
// register functions to the table
mod := L.SetFuncs(L.NewTable(), exports)
// returns the module
L.Push(mod)
return 1
}
var exports = map[string]lua.LGFunction{
"getUUID": getUuidFunc,
"loadPlayer": loadPlayerFunc,
"isOp": isOpFunc,
}
func getUuidFunc(L *lua.LState) int {
name := L.CheckString(1)
uuid, exists := GetUUID(name)
if exists {
L.Push(lua.LString(uuid))
} else {
L.Push(lua.LNil)
}
return 1
}
func loadPlayerFunc(L *lua.LState) int {
name := L.CheckString(1)
uuid, exists := GetUUID(name)
if !exists {
L.Push(lua.LNil)
L.Push(lua.LString("User does not exist"))
return 2
}
playerPath := path.Join(WorldPath, "playerdata", uuid+".dat")
f, err := os.Open(playerPath)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
defer f.Close()
r, err := gzip.NewReader(f)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
defer r.Close()
tag, err := nbt.ReadNamedTag(r)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(TagToLuaValue(L, tag))
L.Push(lua.LNil)
return 2
}