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

@@ -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())
// }