add db connection, refactor code, add db migration files

This commit is contained in:
lbenedar
2026-04-03 18:59:15 +03:00
parent d5577f10d7
commit a16edb9b61
28 changed files with 587 additions and 345 deletions

View File

@@ -6,8 +6,7 @@ import (
)
var (
ErrorSidWrongFormat = errors.New("Session id wrong format")
ErrorSidNotFound = errors.New("Session id didn't find in response header")
ErrorFoundryNotInit = errors.New("Foundry is not initialized")
ErrorAuthPassWrong = errors.New("Authentication password is wrong")
ErrorNotAuth = errors.New("Admin is not authenticated")
ErrorIsNotReady = errors.New("Connection is not ready for communication")
@@ -21,7 +20,7 @@ var (
type FoundryError struct {
Err error
Type FoundryCode
Type TransportCode
IsFatal bool
}

View File

@@ -4,37 +4,18 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strconv"
"strings"
"gitea.local.lab/Lbenedar/foundry_helper_service/internal/foundry/requests"
"gitea.local.lab/Lbenedar/foundry_helper_service/internal/foundry/types"
"github.com/gorilla/websocket"
)
const (
authPath = "/auth"
licensePath = "/license"
joinPath = "/join"
playersPath = "/players"
setupPath = "/setup"
updatePath = "/update"
socketPath = "/socket.io"
)
var WsTypeData = map[string]string{
authPath: "getAuthData",
licensePath: "getAuthData",
joinPath: "getJoinData",
playersPath: "getPlayersData",
setupPath: "getSetupData",
updatePath: "getUpdateData",
}
type FoundryCode int
const (
WriterCode = FoundryCode(0)
ReaderCode = FoundryCode(1)
RespSessionData = "0"
RespPingCode = "2"
RespSessionId = "40"
@@ -62,17 +43,24 @@ var CodesRespToReq = map[string]string{
}
type Foundry struct {
config foundry_config
//TODO: make check of admin's authentication
isAuth bool
sessionID string
isAuth bool
currPage string
logger *slog.Logger
// db db.DB
ws *webSocketUtil
config requests.Config
ws *webSocketUtil
}
type foundry_config struct {
host string
func NewFoundry() *Foundry {
foundry := &Foundry{config: requests.Config{SessionID: ""}, isAuth: false, ws: NewWebSocketUtil()}
// err := foundry.config.GetSessionId()
// if err != nil {
// return nil, err
// }
return foundry
}
func (foundry *Foundry) checkAuthRespAnswer(r io.Reader, respLength int) error {
@@ -90,42 +78,15 @@ func (foundry *Foundry) checkAuthRespAnswer(r io.Reader, respLength int) error {
return nil
}
func (foundry *Foundry) getSessionTokenFromHeader(resp http.Header) (bool, error) {
setCookieHeader := resp.Get("Set-Cookie")
if setCookieHeader == "" {
return false, nil
}
for value := range strings.SplitSeq(setCookieHeader, ";") {
if strings.Contains(value, "session") {
sessionCookie := strings.Split(value, "=")
if len(sessionCookie) != 2 {
return false, ErrorSidWrongFormat
}
foundry.sessionID = sessionCookie[1]
return true, nil
}
}
return false, nil
}
func (foundry *Foundry) Authenticate(password string) error {
if foundry.sessionID == "" {
err := foundry.setUpSessionId()
func (foundry *Foundry) Authenticate() error {
if foundry.config.SessionID == "" {
err := foundry.config.GetSessionId()
if err != nil {
return err
}
}
req, err := createAuthRequest(foundry.config.host, foundry.sessionID, password)
if err != nil {
return err
}
client := &http.Client{}
resp, err := client.Do(req)
resp, err := foundry.config.PostAuthenticationData()
if err != nil {
return err
}
@@ -140,7 +101,9 @@ func (foundry *Foundry) Authenticate(password string) error {
}
func (foundry *Foundry) StartListen() error {
wsChannels := foundry.ws.InitWsChannels()
foundry.ws.channels = *types.InitWsChannels()
wsChannels := &foundry.ws.channels
defer wsChannels.Close()
go foundry.ListenAndServeWS()
@@ -162,6 +125,54 @@ func (foundry *Foundry) StartListen() error {
}
}
func (foundry *Foundry) ConnectToFoundry() error {
var err error
if foundry == nil {
return ErrorFoundryNotInit
}
ok, err := (*foundry).config.GetSessionToken()
if err != nil {
return err
}
if (*foundry).config.Password != "" && !ok {
err := (*foundry).Authenticate()
if err != nil {
return err
}
}
foundry.logger.Info("Successefully connected to Foundry", "host", foundry.config.Host)
return nil
}
func (foundry *Foundry) ConnectToWebSocket() error {
if !foundry.isAuth {
return ErrorNotAuth
}
query := url.Values{}
query.Add("session", foundry.config.SessionID)
query.Add("EIO", "4")
query.Add("transport", "websocket")
u := url.URL{Scheme: "ws", Host: foundry.config.Host, Path: fmt.Sprintf("%s/", requests.SocketPath), RawQuery: query.Encode()}
wsHeader := http.Header{}
wsHeader.Set("Cookie", fmt.Sprintf("session=%s", foundry.config.SessionID))
wsConn, _, err := websocket.DefaultDialer.Dial(u.String(), wsHeader)
if err != nil {
return err
}
foundry.ws.wsConn = wsConn
foundry.ws.currWsId = 0
foundry.logger.Info("Successefully connected to Foundry Websocket")
return nil
}
func (foundry *Foundry) CloseWebSocketConn() {
foundry.ws.wsConn.Close()
}
@@ -171,26 +182,27 @@ func (foundry *Foundry) ListenAndServeWS() {
foundry.ws.ServeWebSocket()
}
func (foundry *Foundry) CreateWSMessageByPage(page string) *wsMessage {
msgToSend := &wsMessage{code: CodesRespToReq[RespCreateSessionCode], id: foundry.ws.currWsId, msgJson: fmt.Sprintf("[\"%s\"]", WsTypeData[page])}
foundry.ws.currWsId++
func (foundry *Foundry) HandleWSRequest(msgType string) ([]byte, error) {
msg := foundry.ws.CreateWSMessageByPage("/setup")
fmt.Printf("Msg: %s\n", msgToSend.toString())
return msgToSend
}
func (foundry *Foundry) HandleWebsocketRequest(msg *wsMessage) ([]byte, error) {
return foundry.ws.HandleWebsocketRequest(msg)
}
func NewFoundry(host string) (*Foundry, error) {
foundry := &Foundry{config: foundry_config{host: host}, isAuth: false, currPage: authPath, ws: NewWebSocketUtil()}
func (foundry *Foundry) HasSessionId() bool {
return foundry.config.SessionID != ""
}
err := foundry.setUpSessionId()
if err != nil {
return nil, err
}
return foundry, nil
func (foundry *Foundry) SetUpSessionId() error {
return foundry.config.GetSessionId()
}
func (foundry *Foundry) SetConfig(config *requests.Config) {
foundry.config = *config
}
func (foundry *Foundry) SetLogger(slogger *slog.Logger) {
foundry.logger = slogger
foundry.ws.logger = slogger
}
// /**
@@ -206,27 +218,3 @@ func NewFoundry(host string) (*Foundry, error) {
// }).catch(() => {});
// this.#pollActive();
// };
// func (foundry *Foundry) SendPageDataRequest(page string) error {
// msgToSend := &wsComm{code: CodesRespToReq[RespCreateSessionCode], id: foundry.ws.currWsId, msgJson: fmt.Sprintf("[\"%s\"]", WsTypeData[page])}
// foundry.ws.currWsId++
// log.Printf("send: %s\n", msgToSend.toString())
// return foundry.ws.wsConn.WriteMessage(websocket.TextMessage, msgToSend.toByteSlice())
// }
// func (foundry *Foundry) setUpWebSocketConnection() error {
// err := foundry.wsConn.WriteMessage(websocket.TextMessage, []byte("40"))
// if err != nil {
// return err
// }
// return nil
// }
// func (foundry *Foundry) sendPageDataRequest(page string) error {
// msgToSend := &wsComm{code: CodesRespToReq[RespCreateSessionCode], id: foundry.ws.currWsId, msgJson: fmt.Sprintf("[\"%s\"]", WsTypeData[page])}
// foundry.ws.currWsId++
// log.Printf("send: %s\n", msgToSend.toString())
// return foundry.ws.wsConn.WriteMessage(websocket.TextMessage, msgToSend.toByteSlice())
// }

View File

@@ -1,64 +0,0 @@
package foundry
import (
"encoding/json"
"fmt"
"net/http"
"gitea.local.lab/Lbenedar/foundry_helper_service/internal/foundry/models"
)
func (foundry *Foundry) setUpSessionId() error {
getResp, err := http.Get(fmt.Sprintf("http://%s%s", foundry.config.host, authPath))
if err != nil {
return err
}
_, err = foundry.getSessionTokenFromHeader(getResp.Header)
return err
}
func (foundry *Foundry) CheckSessionToken(host string) (bool, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s%s", host, authPath), nil)
if err != nil {
return false, err
}
header := http.Header{}
header.Set("Cookie", fmt.Sprintf("session=%s", foundry.sessionID))
header.Set("Connection", "keep-alive")
header.Set("Host", host)
header.Set("Origin", fmt.Sprintf("http://%s", host))
header.Set("Referer", fmt.Sprintf("http://%s%s", host, authPath))
req.Header = header
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return false, err
}
return foundry.getSessionTokenFromHeader(resp.Header)
}
func (foundry *Foundry) GetStatus() (*models.Status, error) {
getResp, err := http.Get(fmt.Sprintf("http://%s/api/status", foundry.config.host))
if err != nil {
return nil, err
}
defer getResp.Body.Close()
statusByte := make([]byte, 64)
_, err = getResp.Body.Read(statusByte)
if err != nil {
return nil, err
}
var status models.Status
err = json.Unmarshal(statusByte, &status)
if err != nil {
return nil, err
}
return &status, nil
}

View File

@@ -1,32 +0,0 @@
package foundry
import (
"bytes"
"fmt"
"net/http"
"net/url"
)
func createAuthRequest(host, sessionID, password string) (*http.Request, error) {
authData := url.Values{}
authData.Add("adminPassword", password)
authData.Add("action", "adminAuth")
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s%s", host, authPath), bytes.NewBuffer([]byte(authData.Encode())))
if err != nil {
return nil, err
}
header := http.Header{}
header.Set("Cookie", fmt.Sprintf("session=%s", sessionID))
header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
header.Set("Connection", "keep-alive")
header.Set("Content-Length", fmt.Sprintf("%d", len(authData.Encode())))
header.Set("Content-Type", "application/x-www-form-urlencoded")
header.Set("Host", host)
header.Set("Origin", fmt.Sprintf("http://%s", host))
header.Set("Referer", fmt.Sprintf("http://%s%s", host, authPath))
req.Header = header
return req, nil
}

View File

@@ -0,0 +1,59 @@
package requests
import (
"errors"
"net/http"
"strings"
)
var (
ErrorSidWrongFormat = errors.New("Session id wrong format")
ErrorSidNotFound = errors.New("Session id didn't find in response header")
)
const (
AuthPath = "/auth"
LicensePath = "/license"
JoinPath = "/join"
PlayersPath = "/players"
SetupPath = "/setup"
UpdatePath = "/update"
SocketPath = "/socket.io"
)
var WsTypeData = map[string]string{
AuthPath: "getAuthData",
LicensePath: "getAuthData",
JoinPath: "getJoinData",
PlayersPath: "getPlayersData",
SetupPath: "getSetupData",
UpdatePath: "getUpdateData",
}
type Config struct {
Host string
Password string
SessionID string
}
func (conf *Config) SetSessionTokenFromHeader(resp http.Header) (bool, error) {
setCookieHeader := resp.Get("Set-Cookie")
if setCookieHeader == "" {
return false, nil
}
for value := range strings.SplitSeq(setCookieHeader, ";") {
if strings.Contains(value, "session") {
sessionCookie := strings.Split(value, "=")
if len(sessionCookie) != 2 {
return false, ErrorSidWrongFormat
}
conf.SessionID = sessionCookie[1]
return true, nil
}
}
return false, nil
}

View File

@@ -0,0 +1,64 @@
package requests
import (
"encoding/json"
"fmt"
"net/http"
"gitea.local.lab/Lbenedar/foundry_helper_service/internal/foundry/models"
)
func (conf *Config) GetSessionId() error {
getResp, err := http.Get(fmt.Sprintf("http://%s%s", conf.Host, AuthPath))
if err != nil {
return err
}
_, err = conf.SetSessionTokenFromHeader(getResp.Header)
return err
}
func (conf *Config) GetSessionToken() (bool, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("http://%s%s", conf.Host, AuthPath), nil)
if err != nil {
return false, err
}
header := http.Header{}
header.Set("Cookie", fmt.Sprintf("session=%s", conf.SessionID))
header.Set("Connection", "keep-alive")
header.Set("Host", conf.Host)
header.Set("Origin", fmt.Sprintf("http://%s", conf.Host))
header.Set("Referer", fmt.Sprintf("http://%s%s", conf.Host, AuthPath))
req.Header = header
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return false, err
}
return conf.SetSessionTokenFromHeader(resp.Header)
}
func (conf *Config) GetStatus() (*models.Status, error) {
getResp, err := http.Get(fmt.Sprintf("http://%s/api/status", conf.Host))
if err != nil {
return nil, err
}
defer getResp.Body.Close()
statusByte := make([]byte, 64)
_, err = getResp.Body.Read(statusByte)
if err != nil {
return nil, err
}
var status models.Status
err = json.Unmarshal(statusByte, &status)
if err != nil {
return nil, err
}
return &status, nil
}

View File

@@ -0,0 +1,38 @@
package requests
import (
"bytes"
"fmt"
"net/http"
"net/url"
)
func (conf *Config) PostAuthenticationData() (*http.Response, error) {
authData := url.Values{}
authData.Add("adminPassword", conf.Password)
authData.Add("action", "adminAuth")
req, err := http.NewRequest("POST", fmt.Sprintf("http://%s%s", conf.Host, AuthPath), bytes.NewBuffer([]byte(authData.Encode())))
if err != nil {
return nil, err
}
header := http.Header{}
header.Set("Cookie", fmt.Sprintf("session=%s", conf.SessionID))
header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
header.Set("Connection", "keep-alive")
header.Set("Content-Length", fmt.Sprintf("%d", len(authData.Encode())))
header.Set("Content-Type", "application/x-www-form-urlencoded")
header.Set("Host", conf.Host)
header.Set("Origin", fmt.Sprintf("http://%s", conf.Host))
header.Set("Referer", fmt.Sprintf("http://%s%s", conf.Host, AuthPath))
req.Header = header
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}

View File

@@ -1,8 +1,8 @@
package foundry
package types
type Channels struct {
done chan struct{}
msg chan *wsMessage
msg chan *WsMessage
err chan error
}
@@ -10,7 +10,7 @@ func (channels Channels) Err() chan error {
return channels.err
}
func (channels Channels) Msg() chan *wsMessage {
func (channels Channels) Msg() chan *WsMessage {
return channels.msg
}
@@ -23,3 +23,13 @@ func (channels *Channels) Close() {
close(channels.err)
close(channels.msg)
}
func InitWsChannels() *Channels {
channels := Channels{
done: make(chan struct{}),
err: make(chan error, 10),
msg: make(chan *WsMessage, 10),
}
return &channels
}

View File

@@ -0,0 +1,17 @@
package types
import "fmt"
type WsMessage struct {
Code string
Id int
MsgJson string
}
func (w WsMessage) ToString() string {
return fmt.Sprintf("%s%d%s", w.Code, w.Id, w.MsgJson)
}
func (w WsMessage) ToByteSlice() []byte {
return fmt.Appendf([]byte{}, "%s%d%s", w.Code, w.Id, w.MsgJson)
}

View File

@@ -3,26 +3,37 @@ package foundry
import (
"context"
"fmt"
"log"
"net/http"
"net/url"
"log/slog"
"strconv"
"strings"
"sync"
"time"
"gitea.local.lab/Lbenedar/foundry_helper_service/internal/foundry/requests"
"gitea.local.lab/Lbenedar/foundry_helper_service/internal/foundry/types"
"github.com/gorilla/websocket"
)
type TransportCode int
const (
WriterCode = TransportCode(0)
ReaderCode = TransportCode(1)
)
type webSocketUtil struct {
wsConn *websocket.Conn
currWsId int
isReadReady bool
logger *slog.Logger
msgMap map[int](chan []byte)
msgMap map[int](chan []byte)
chanMutex sync.Mutex
channels types.Channels
}
mutex sync.Mutex
channels Channels
func NewWebSocketUtil() *webSocketUtil {
return &webSocketUtil{currWsId: 0, isReadReady: false, msgMap: make(map[int]chan []byte)}
}
func parseCode(msg *string) string {
@@ -54,53 +65,28 @@ func parseId(msg *string, start int) (int, int) {
return msgId, j
}
func parseWsRespMessage(msg string) (*wsMessage, error) {
data := &wsMessage{}
func parseWsRespMessage(msg string) (*types.WsMessage, error) {
data := &types.WsMessage{}
data.code = parseCode(&msg)
if data.code != RespDataCode {
data.Code = parseCode(&msg)
if data.Code != RespDataCode {
return data, nil
}
i := len(data.code)
i := len(data.Code)
if i == 0 {
return nil, ErrorMsgNotHaveNumber
}
data.id, i = parseId(&msg, i)
data.Id, i = parseId(&msg, i)
if i == 0 {
return nil, ErrorMsgNotHaveNumber
}
data.msgJson = msg[i:]
data.MsgJson = msg[i:]
return data, nil
}
func ConnectToWebSocket(foundry *Foundry) error {
if !foundry.isAuth {
return ErrorNotAuth
}
query := url.Values{}
query.Add("session", foundry.sessionID)
query.Add("EIO", "4")
query.Add("transport", "websocket")
u := url.URL{Scheme: "ws", Host: foundry.config.host, Path: fmt.Sprintf("%s/", socketPath), RawQuery: query.Encode()}
wsHeader := http.Header{}
wsHeader.Set("Cookie", fmt.Sprintf("session=%s", foundry.sessionID))
wsConn, _, err := websocket.DefaultDialer.Dial(u.String(), wsHeader)
if err != nil {
return err
}
foundry.ws.wsConn = wsConn
foundry.ws.currWsId = 0
return nil
}
// TODO: Lookup timeout
func (ws *webSocketUtil) ReceiveMessage(id int) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
@@ -130,8 +116,8 @@ func (ws *webSocketUtil) ReceiveMessage(id int) ([]byte, error) {
func (ws *webSocketUtil) closeMsgChannel(id int, timeout time.Duration) bool {
time.Sleep(timeout)
ws.mutex.Lock()
defer ws.mutex.Unlock()
ws.chanMutex.Lock()
defer ws.chanMutex.Unlock()
ok := true
if _, ok = ws.msgMap[id]; !ok {
@@ -147,21 +133,22 @@ func (ws *webSocketUtil) closeMsgChannel(id int, timeout time.Duration) bool {
close(ws.msgMap[id])
delete(ws.msgMap, id)
}
fmt.Printf("Channel has been closed(id=%d, timeout=%d)\n", id, timeout)
ws.logger.Debug("WS: Channel has been closed\n", "id", id, "timeout", timeout.String())
return ok
}
func (ws *webSocketUtil) HandleWebsocketRequest(msg *wsMessage) ([]byte, error) {
func (ws *webSocketUtil) HandleWebsocketRequest(msg *types.WsMessage) ([]byte, error) {
if !ws.IsReadReady() {
return nil, ErrorIsNotReady
}
err := ws.wsConn.WriteMessage(websocket.TextMessage, msg.toByteSlice())
err := ws.wsConn.WriteMessage(websocket.TextMessage, msg.ToByteSlice())
if err != nil {
return nil, err
}
data, err := ws.ReceiveMessage(msg.id)
data, err := ws.ReceiveMessage(msg.Id)
if err != nil {
return nil, err
}
@@ -169,10 +156,9 @@ func (ws *webSocketUtil) HandleWebsocketRequest(msg *wsMessage) ([]byte, error)
}
func (ws *webSocketUtil) sendOnlyCodeRequest(code string) error {
msgToSend := []byte(CodesRespToReq[code])
log.Printf("send: %s\n", msgToSend)
ws.logger.Debug("WS: Data has been send\n", "msg", CodesRespToReq[code])
return ws.wsConn.WriteMessage(websocket.TextMessage, msgToSend)
return ws.wsConn.WriteMessage(websocket.TextMessage, []byte(CodesRespToReq[code]))
}
func (ws *webSocketUtil) ListenWebSocket() {
@@ -195,22 +181,22 @@ func (ws *webSocketUtil) ServeWebSocket() {
for {
select {
case message := <-ws.channels.Msg():
log.Println("recv code:", message.code)
ws.logger.Debug("WS: Data has been received\n", "msgCode", message.Code)
switch message.code {
switch message.Code {
case RespPingCode, RespSessionData:
err := ws.sendOnlyCodeRequest(message.code)
err := ws.sendOnlyCodeRequest(message.Code)
if err != nil {
ws.isReadReady = false
ws.channels.err <- &FoundryError{Type: WriterCode, Err: err}
ws.channels.Err() <- &FoundryError{Type: WriterCode, Err: err}
continue
}
case RespCreateSessionCode:
ws.isReadReady = true
case RespDataCode:
ws.msgMap[message.id] = make(chan []byte, 1)
ws.msgMap[message.id] <- []byte(message.msgJson)
go ws.closeMsgChannel(message.id, 5*time.Second)
ws.msgMap[message.Id] = make(chan []byte, 1)
ws.msgMap[message.Id] <- []byte(message.MsgJson)
go ws.closeMsgChannel(message.Id, 5*time.Second)
default:
}
case <-ws.channels.Done():
@@ -219,18 +205,14 @@ func (ws *webSocketUtil) ServeWebSocket() {
}
}
func (ws *webSocketUtil) InitWsChannels() *Channels {
ws.channels.done = make(chan struct{})
ws.channels.err = make(chan error, 10)
ws.channels.msg = make(chan *wsMessage, 10)
return &ws.channels
}
func NewWebSocketUtil() *webSocketUtil {
return &webSocketUtil{currWsId: 0, isReadReady: false, msgMap: make(map[int]chan []byte), channels: Channels{}}
}
func (ws *webSocketUtil) IsReadReady() bool {
return ws.isReadReady
}
func (ws *webSocketUtil) CreateWSMessageByPage(page string) *types.WsMessage {
msgToSend := &types.WsMessage{Code: CodesRespToReq[RespCreateSessionCode], Id: ws.currWsId, MsgJson: fmt.Sprintf("[\"%s\"]", requests.WsTypeData[page])}
ws.currWsId++
ws.logger.Debug("WS: Data to send\n", "msgToSend", msgToSend.ToString())
return msgToSend
}

View File

@@ -1,17 +0,0 @@
package foundry
import "fmt"
type wsMessage struct {
code string
id int
msgJson string
}
func (w wsMessage) toString() string {
return fmt.Sprintf("%s%d%s", w.code, w.id, w.msgJson)
}
func (w wsMessage) toByteSlice() []byte {
return fmt.Appendf([]byte{}, "%s%d%s", w.code, w.id, w.msgJson)
}