init
This commit is contained in:
32
internal/foundry/errors.go
Normal file
32
internal/foundry/errors.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package foundry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrorSidWrongFormat = errors.New("Session id wrong format")
|
||||
ErrorSidNotFound = errors.New("Session id didn't find in response header")
|
||||
ErrorAuthPassWrong = errors.New("Authentication password is wrong")
|
||||
ErrorNotAuth = errors.New("Admin is not authenticated")
|
||||
ErrorIsNotReady = errors.New("Connection is not ready for communication")
|
||||
|
||||
ErrorMsgNotHaveNumber = errors.New("Message doesn't have dataCode and id")
|
||||
ErrorTimeout = errors.New("Answer has not been received after timeout")
|
||||
ErrorReadChannel = errors.New("Error when reading from msg channel")
|
||||
|
||||
ListenIsDone = errors.New("Listen for websocket data in foundry is stopped")
|
||||
)
|
||||
|
||||
type FoundryError struct {
|
||||
Err error
|
||||
Type FoundryCode
|
||||
IsFatal bool
|
||||
}
|
||||
|
||||
func (e *FoundryError) Error() string {
|
||||
return fmt.Sprintf("Received from %d: %s", e.Type, e.Err.Error())
|
||||
}
|
||||
|
||||
func (e *FoundryError) Unwrap() error { return e.Err }
|
||||
232
internal/foundry/foundry.go
Normal file
232
internal/foundry/foundry.go
Normal file
@@ -0,0 +1,232 @@
|
||||
package foundry
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
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"
|
||||
RespCreateSessionCode = "42"
|
||||
RespDataCode = "43"
|
||||
|
||||
ReqPongCode = "3"
|
||||
ReqCreateSessionCode = "40"
|
||||
ReqDataCode = "42"
|
||||
)
|
||||
|
||||
var RequestCodes = []string{
|
||||
RespSessionData,
|
||||
RespPingCode,
|
||||
RespSessionId,
|
||||
RespCreateSessionCode,
|
||||
RespDataCode,
|
||||
}
|
||||
|
||||
var CodesRespToReq = map[string]string{
|
||||
RespSessionData: ReqCreateSessionCode,
|
||||
RespPingCode: ReqPongCode,
|
||||
RespCreateSessionCode: ReqDataCode,
|
||||
//ReqDataCode: RespCreateSessionCode,
|
||||
}
|
||||
|
||||
type Foundry struct {
|
||||
config foundry_config
|
||||
|
||||
sessionID string
|
||||
isAuth bool
|
||||
currPage string
|
||||
|
||||
ws *webSocketUtil
|
||||
}
|
||||
|
||||
type foundry_config struct {
|
||||
host string
|
||||
}
|
||||
|
||||
func (foundry *Foundry) checkAuthRespAnswer(r io.Reader, respLength int) error {
|
||||
authBody := make([]byte, respLength)
|
||||
|
||||
_, err := r.Read(authBody)
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
|
||||
if !strings.Contains(string(authBody), "Admin authentication successful") {
|
||||
return ErrorAuthPassWrong
|
||||
}
|
||||
foundry.isAuth = true
|
||||
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()
|
||||
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)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
contentLen, err := strconv.Atoi(resp.Header.Get("Content-Length"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return foundry.checkAuthRespAnswer(resp.Body, contentLen)
|
||||
}
|
||||
|
||||
func (foundry *Foundry) StartListen() error {
|
||||
wsChannels := foundry.ws.InitWsChannels()
|
||||
defer wsChannels.Close()
|
||||
go foundry.ListenAndServeWS()
|
||||
|
||||
var err error
|
||||
for {
|
||||
select {
|
||||
case err = <-wsChannels.Err():
|
||||
var foundryErr *FoundryError
|
||||
if errors.As(err, &foundryErr) {
|
||||
if foundryErr.IsFatal {
|
||||
foundry.CloseWebSocketConn()
|
||||
return foundryErr
|
||||
}
|
||||
}
|
||||
case <-wsChannels.Done():
|
||||
foundry.CloseWebSocketConn()
|
||||
return ListenIsDone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (foundry *Foundry) CloseWebSocketConn() {
|
||||
foundry.ws.wsConn.Close()
|
||||
}
|
||||
|
||||
func (foundry *Foundry) ListenAndServeWS() {
|
||||
go foundry.ws.ListenWebSocket()
|
||||
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++
|
||||
|
||||
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()}
|
||||
|
||||
err := foundry.setUpSessionId()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return foundry, nil
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Poll the server to see if a World has become active, and automatically refresh if so.
|
||||
// * @returns {Promise<void>}
|
||||
// */
|
||||
// async #pollActive() {
|
||||
// const poll = () => {
|
||||
// const status = foundry.utils.getRoute("/api/status");
|
||||
// this.#activePollState.last = Date.now();
|
||||
// this.#activePollState.polling = foundry.utils.fetchJsonWithTimeout(status, {}, {
|
||||
// timeoutMs: 10000
|
||||
// }).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())
|
||||
// }
|
||||
64
internal/foundry/get_requests.go
Normal file
64
internal/foundry/get_requests.go
Normal file
@@ -0,0 +1,64 @@
|
||||
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
|
||||
}
|
||||
44
internal/foundry/models/data.go
Normal file
44
internal/foundry/models/data.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
type FoundryState struct {
|
||||
IsAdmin bool `json:"isAdmin,omitempty"`
|
||||
IsSetup bool `json:"isSetup,omitempty"`
|
||||
Languages []Language `json:"languages,omitempty"`
|
||||
Modules []DataTemplate `json:"modules"`
|
||||
Release Release `json:"release"`
|
||||
Systems []DataTemplate `json:"systems,omitempty"`
|
||||
Worlds []DataTemplate `json:"worlds,omitempty"`
|
||||
World *DataTemplate `json:"world,omitempty"`
|
||||
Users Users `json:"users,omitempty"`
|
||||
Options struct {
|
||||
Language string `json:"language,omitempty"`
|
||||
} `json:"options,omitempty"`
|
||||
|
||||
//coreUpdate struct{}
|
||||
//featuredContent struct{}
|
||||
//files struct{}
|
||||
//news struct{}
|
||||
|
||||
//packageWarnings struct{} think about it
|
||||
}
|
||||
|
||||
func (state FoundryState) GetRelease() Release {
|
||||
return state.Release
|
||||
}
|
||||
|
||||
func ParseSetupModel(data []byte) (*FoundryState, error) {
|
||||
var modelSetup []FoundryState
|
||||
err := json.Unmarshal(data, &modelSetup)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(modelSetup) > 1 {
|
||||
return nil, ErrorSetupMoreThanOne
|
||||
}
|
||||
return &modelSetup[0], nil
|
||||
}
|
||||
8
internal/foundry/models/errors.go
Normal file
8
internal/foundry/models/errors.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package models
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrorSetupMoreThanOne = errors.New("Passed more than one setupData")
|
||||
ErrorSetupNotFound = errors.New("Not found setup data from your request")
|
||||
)
|
||||
13
internal/foundry/models/language.go
Normal file
13
internal/foundry/models/language.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package models
|
||||
|
||||
type Language struct {
|
||||
Id string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Modules []LangModule `json:"modules"`
|
||||
}
|
||||
|
||||
type LangModule struct {
|
||||
Id string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
49
internal/foundry/models/module.go
Normal file
49
internal/foundry/models/module.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package models
|
||||
|
||||
type Module struct {
|
||||
Id string
|
||||
Title string
|
||||
Description string
|
||||
Url string
|
||||
Version string
|
||||
Compatibility Compatibility
|
||||
Languages []DataLanguage
|
||||
Availability int
|
||||
}
|
||||
|
||||
type Modules []Module
|
||||
|
||||
func (modules Modules) GetById(id int) *Module {
|
||||
return &modules[id]
|
||||
}
|
||||
|
||||
func (state *FoundryState) GetModules() Modules {
|
||||
modulesCopy := make([]Module, 0, 8)
|
||||
for i := range state.Modules {
|
||||
module := &(state.Modules[i])
|
||||
moduleCopy := Module{
|
||||
Id: module.Id,
|
||||
Title: module.Title,
|
||||
Description: module.Description,
|
||||
Compatibility: Compatibility{
|
||||
Minimum: module.Compatibility.Minimum,
|
||||
Maximum: module.Compatibility.Maximum,
|
||||
},
|
||||
Url: module.Url,
|
||||
Version: module.CoreVersion,
|
||||
|
||||
Availability: module.Availability,
|
||||
}
|
||||
for j := range module.Languages {
|
||||
lang := DataLanguage{
|
||||
Lang: module.Languages[j].Lang,
|
||||
Name: module.Languages[j].Name,
|
||||
Path: module.Languages[j].Path,
|
||||
Flags: module.Languages[j].Flags,
|
||||
}
|
||||
moduleCopy.Languages = append(moduleCopy.Languages, lang)
|
||||
}
|
||||
modulesCopy = append(modulesCopy, moduleCopy)
|
||||
}
|
||||
return modulesCopy
|
||||
}
|
||||
59
internal/foundry/models/modules/dice-stats.go
Normal file
59
internal/foundry/models/modules/dice-stats.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package modules
|
||||
|
||||
type DiceStats struct {
|
||||
PlayerRollData DiceStatsRollData `json:"player_roll_data"`
|
||||
}
|
||||
|
||||
type DiceStatsRollData struct {
|
||||
PlayerDice []DicePlayerDice `json:"PLAYER_DICE"`
|
||||
Username string `json:"USERNAME"`
|
||||
Userid string `json:"USERID"`
|
||||
Gm bool `json:"GM"`
|
||||
PlayerRollInfo DiceRollInfo `json:"PLAYER_ROLL_INFO"`
|
||||
}
|
||||
|
||||
type DicePlayerDice struct {
|
||||
Type string `json:"TYPE"`
|
||||
Max int `json:"MAX"`
|
||||
TotalRolls int `json:"TOTAL_ROLLS"`
|
||||
Rolls []int `json:"ROLLS"`
|
||||
BlindRolls []int `json:"BLIND_ROLLS"`
|
||||
StreakSize int `json:"STREAK_SIZE"`
|
||||
StreakInit int `json:"STREAK_INIT"`
|
||||
StreakIsBlind bool `json:"STREAK_ISBLIND"`
|
||||
LongestStreak int `json:"LONGEST_STREAK"`
|
||||
LongestStreakInit int `json:"LONGEST_STREAK_INIT"`
|
||||
Mean int `json:"MEAN"`
|
||||
Median int `json:"MEDIAN"`
|
||||
Mode int `json:"MODE"`
|
||||
Means []int `json:"MEANS"`
|
||||
Medians []int `json:"MEDIANS"`
|
||||
Modes []int `json:"MODES"`
|
||||
RollCounters []int `json:"ROLL_COUNTERS"`
|
||||
AtkRolls []int `json:"ATK_ROLLS"`
|
||||
DmgRolls []int `json:"DMG_ROLLS"`
|
||||
SavesRolls []int `json:"SAVES_ROLLS"`
|
||||
SkillsRolls []int `json:"SKILLS_ROLLS"`
|
||||
AbilityRolls []int `json:"ABILITY_ROLLS"`
|
||||
UnknownRolls []int `json:"UNKNOWN_ROLLS"`
|
||||
PerceptionRolls []int `json:"PERCEPTION_ROLLS"`
|
||||
InitiativeRolls []int `json:"INITIATIVE_ROLLS"`
|
||||
AtkRollsBlind []int `json:"ATK_ROLLS_BLIND"`
|
||||
DmgRollsBlind []int `json:"DMG_ROLLS_BLIND"`
|
||||
SavesRollsBlind []int `json:"SAVES_ROLLS_BLIND"`
|
||||
SkillsRollsBlind []int `json:"SKILLS_ROLLS_BLIND"`
|
||||
AbilityRollsBlind []int `json:"ABILITY_ROLLS_BLIND"`
|
||||
UnknownRollsBlind []int `json:"UNKNOWN_ROLLS_BLIND"`
|
||||
PerceptionRollsBlind []int `json:"PERCEPTION_ROLLS_BLIND"`
|
||||
InitiativeRollsBlind []int `json:"INITIATIVE_ROLLS_BLIND"`
|
||||
}
|
||||
|
||||
type DiceRollInfo struct {
|
||||
IsRollInfoTracked bool `json:"IS_ROLL_INFO_TRACKED"`
|
||||
AtkOutcomeTracker []int `json:"ATK_OUTCOME_TRACKER"`
|
||||
NumUntargetedAtks int `json:"NUM_UNTARGETED_ATKS"`
|
||||
TotalAttacks int `json:"TOTAL_ATTACKS"`
|
||||
SaveOutcomeTracker []int `json:"SAVE_OUTCOME_TRACKER"`
|
||||
NumUntargetedSaves int `json:"NUM_UNTARGETED_SAVES"`
|
||||
TotalSaves int `json:"TOTAL_SAVES"`
|
||||
}
|
||||
12
internal/foundry/models/modules/pf2e.go
Normal file
12
internal/foundry/models/modules/pf2e.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package modules
|
||||
|
||||
type Pf2eModule struct {
|
||||
settings Pf2eSettings
|
||||
}
|
||||
|
||||
type Pf2eSettings struct {
|
||||
showEffectPanel bool
|
||||
showCheckDialogs bool
|
||||
showDamageDialogs bool
|
||||
monochromeDarkvision bool
|
||||
}
|
||||
11
internal/foundry/models/release.go
Normal file
11
internal/foundry/models/release.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package models
|
||||
|
||||
type Release struct {
|
||||
Generation int `json:"generation"`
|
||||
Channel string `json:"channel"`
|
||||
Suffix string `json:"suffix"`
|
||||
Build int `json:"build"`
|
||||
Node_version int `json:"node_version"`
|
||||
Time int64 `json:"time"`
|
||||
flags struct{} `json:"-"`
|
||||
}
|
||||
11
internal/foundry/models/status.go
Normal file
11
internal/foundry/models/status.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package models
|
||||
|
||||
type Status struct {
|
||||
Active bool `json:"active"`
|
||||
Version string `json:"version"`
|
||||
World string `json:"world,omitempty"`
|
||||
System string `json:"system,omitempty"`
|
||||
SystemVersion string `json:"systemVersion,omitempty"`
|
||||
Users int `json:"users,omitempty"`
|
||||
Uptime int64 `json:"uptime,omitempty"`
|
||||
}
|
||||
36
internal/foundry/models/system.go
Normal file
36
internal/foundry/models/system.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package models
|
||||
|
||||
type System struct {
|
||||
Id string
|
||||
Title string
|
||||
Description string
|
||||
Url string
|
||||
Compatibility Compatibility
|
||||
Download string
|
||||
}
|
||||
|
||||
type Systems []System
|
||||
|
||||
func (systems Systems) GetById(id int) *System {
|
||||
return &systems[id]
|
||||
}
|
||||
|
||||
func (state *FoundryState) GetSystems() Systems {
|
||||
systemsCopy := make([]System, 0, 8)
|
||||
for i := range state.Systems {
|
||||
system := &(state.Systems[i])
|
||||
systemCopy := System{
|
||||
Id: system.Id,
|
||||
Title: system.Title,
|
||||
Description: system.Description,
|
||||
Url: system.Url,
|
||||
Compatibility: Compatibility{
|
||||
Minimum: system.Compatibility.Minimum,
|
||||
Maximum: system.Compatibility.Maximum,
|
||||
},
|
||||
Download: system.Download,
|
||||
}
|
||||
systemsCopy = append(systemsCopy, systemCopy)
|
||||
}
|
||||
return systemsCopy
|
||||
}
|
||||
132
internal/foundry/models/template.go
Normal file
132
internal/foundry/models/template.go
Normal file
@@ -0,0 +1,132 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type DataTemplate struct {
|
||||
Id string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Authors []DataAuthor `json:"authors,omitempty"`
|
||||
Url string `json:"url,omitempty"`
|
||||
Flags Flags `json:"flags,omitempty"`
|
||||
License string `json:"license,omitempty"`
|
||||
Readme string `json:"readme,omitempty"`
|
||||
Bugs string `json:"bugs,omitempty"`
|
||||
Changelog string `json:"changelog,omitempty"`
|
||||
Media []DataMedia `json:"media,omitempty"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Compatibility Compatibility `json:"compatibility,omitempty"`
|
||||
Scripts []string `json:"scripts"`
|
||||
Esmodules []string `json:"esmodules"`
|
||||
Styles []struct {
|
||||
Src string `json:"src,omitempty"`
|
||||
} `json:"styles,omitempty"`
|
||||
Languages []DataLanguage `json:"languages,omitempty"`
|
||||
Packs []DataPack `json:"packs,omitempty"`
|
||||
PackFolder []DataPackFolder `json:"packFolder,omitempty"`
|
||||
Relationships Relationship `json:"relationships,omitempty"`
|
||||
Socket bool `json:"socket,omitempty"`
|
||||
Manifest string `json:"manifest,omitempty"`
|
||||
Download string `json:"download,omitempty"`
|
||||
Protected bool `json:"protected,omitempty"`
|
||||
Exclusive bool `json:"exclusive,omitempty"`
|
||||
PersistentStorage bool `json:"persistentStorage,omitempty"`
|
||||
Availability int `json:"availability,omitempty"`
|
||||
Locked bool `json:"locked,omitempty"`
|
||||
Owned bool `json:"owned,omitempty"`
|
||||
HasStorage bool `json:"hasStorage,omitempty"`
|
||||
|
||||
//module
|
||||
CoreTranslation bool `json:"coreTranslation,omitempty"`
|
||||
Library bool `json:"library,omitempty"`
|
||||
|
||||
//system
|
||||
Background string `json:"background,omitempty"`
|
||||
Grid DataGrid `json:"grid,omitempty"`
|
||||
PrimaryTokenAttribute string `json:"primaryTokenAttribute,omitempty"`
|
||||
|
||||
//world
|
||||
System string `json:"system,omitempty"`
|
||||
JoinTheme string `json:"joinTheme,omitempty"`
|
||||
CoreVersion string `json:"coreVersion,omitempty"`
|
||||
SystemVersion string `json:"systemVersion,omitempty"`
|
||||
LastPlayed string `json:"lastPlayed,omitempty"`
|
||||
PlayTime int64 `json:"playTime,omitempty"`
|
||||
NextSession time.Time `json:"nextSession,omitempty"`
|
||||
}
|
||||
|
||||
type DataAuthor struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Url string `json:"url,omitempty"`
|
||||
Discord string `json:"discord,omitempty"`
|
||||
flags struct{} `json:"-"`
|
||||
}
|
||||
|
||||
type DataMedia struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Url string `json:"url,omitempty"`
|
||||
Loop bool `json:"loop,omitempty"`
|
||||
flags struct{} `json:"-"`
|
||||
}
|
||||
|
||||
type DataLanguage struct {
|
||||
Lang string `json:"lang,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Flags struct{} `json:"-"`
|
||||
}
|
||||
|
||||
type DataPack struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Label string `json:"label,omitempty"`
|
||||
Banner string `json:"banner,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
System string `json:"system,omitempty"`
|
||||
Ownership map[string]string `json:"ownership,omitempty"`
|
||||
flags struct{} `json:"-"`
|
||||
}
|
||||
|
||||
type DataPackFolder struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Sorting string `json:"sorting,omitempty"`
|
||||
Color string `json:"color,omitempty"`
|
||||
Packs []string `json:"packs,omitempty"`
|
||||
Folders []DataPackFolder `json:"folders,omitempty"`
|
||||
}
|
||||
|
||||
type DataGrid struct {
|
||||
Type int `json:"type,omitempty"`
|
||||
Distance int `json:"distance,omitempty"`
|
||||
Units string `json:"units,omitempty"`
|
||||
Diagonals int `json:"diagonals,omitempty"`
|
||||
}
|
||||
|
||||
type Compatibility struct {
|
||||
Minimum string `json:"minimum,omitempty"`
|
||||
Verified string `json:"verified,omitempty"`
|
||||
Maximum string `json:"maximum,omitempty"`
|
||||
}
|
||||
|
||||
type Flags struct {
|
||||
HotReload FlagsHotReload `json:"hotReload"`
|
||||
Styles []string `json:"styles"`
|
||||
}
|
||||
|
||||
type FlagsHotReload struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Extensions []string `json:"extensions"`
|
||||
Paths []string `json:"paths"`
|
||||
}
|
||||
|
||||
type Relationship struct {
|
||||
systems []struct{} `json:"-"`
|
||||
requires []struct{} `json:"-"`
|
||||
Recommends []struct {
|
||||
Id string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
compatibility struct{} `json:"-"`
|
||||
} `json:"recommends"`
|
||||
conflicts []struct{} `json:"-"`
|
||||
flags struct{} `json:"-"`
|
||||
}
|
||||
45
internal/foundry/models/users.go
Normal file
45
internal/foundry/models/users.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package models
|
||||
|
||||
import "gitea.local.lab/Lbenedar/foundry_helper_service/internal/foundry/models/modules"
|
||||
|
||||
type User struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Role int `json:"role,omitempty"`
|
||||
Id string `json:"_id,omitempty"`
|
||||
avatar struct{} `json:"-"`
|
||||
Character string `json:"character,omitempty"`
|
||||
Color string `json:"color,omitempty"`
|
||||
Pronouns string `json:"pronouns,omitempty"`
|
||||
Hotbar map[string]string `json:"hotbar,omitempty"`
|
||||
permissions struct{} `json:"-"`
|
||||
Flags UserFlags `json:"flags,omitempty"`
|
||||
Stats UserStats `json:"_stats,omitempty"`
|
||||
}
|
||||
|
||||
type UserFlags struct {
|
||||
World map[string]bool `json:"world,omitempty"`
|
||||
Pf2e modules.Pf2eModule `json:"pf2e,omitempty"`
|
||||
DiceStats modules.DiceStats `json:"diceStats,omitempty"`
|
||||
}
|
||||
|
||||
type UserStats struct {
|
||||
compendiumSource struct{} `json:"-"`
|
||||
duplicateSource struct{} `json:"-"`
|
||||
exportSource struct{} `json:"-"`
|
||||
CoreVersion string `json:"coreVersion,omitempty"`
|
||||
SystemId string `json:"systemId,omitempty"`
|
||||
SystemVersion string `json:"systemVersion,omitempty"`
|
||||
CreatedTime int64 `json:"createdTime,omitempty"`
|
||||
ModifiedTime int64 `json:"modifiedTime,omitempty"`
|
||||
LastModifiedBy string `json:"lastModifiedBy,omitempty"`
|
||||
}
|
||||
|
||||
type Users []User
|
||||
|
||||
func (users Users) GetById(id int) *User {
|
||||
return &users[id]
|
||||
}
|
||||
|
||||
func (state *FoundryState) GetUsers() *Users {
|
||||
return &state.Users
|
||||
}
|
||||
88
internal/foundry/models/world.go
Normal file
88
internal/foundry/models/world.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type World struct {
|
||||
Id string
|
||||
Title string
|
||||
Description string
|
||||
Compatibility Compatibility
|
||||
System string
|
||||
CoreVersion string
|
||||
SystemVersion string
|
||||
LastPlayed string
|
||||
PlayTime int64
|
||||
NextSession time.Time
|
||||
}
|
||||
|
||||
type Worlds []World
|
||||
|
||||
func (worlds Worlds) GetById(id int) *World {
|
||||
return &worlds[id]
|
||||
}
|
||||
|
||||
func (state *FoundryState) GetWorld() World {
|
||||
return World{
|
||||
Id: state.World.Id,
|
||||
Title: state.World.Title,
|
||||
Description: state.World.Description,
|
||||
Compatibility: Compatibility{
|
||||
Minimum: state.World.Compatibility.Minimum,
|
||||
Maximum: state.World.Compatibility.Maximum,
|
||||
},
|
||||
System: state.World.System,
|
||||
CoreVersion: state.World.CoreVersion,
|
||||
SystemVersion: state.World.SystemVersion,
|
||||
LastPlayed: state.World.LastPlayed,
|
||||
PlayTime: state.World.PlayTime,
|
||||
NextSession: state.World.NextSession,
|
||||
}
|
||||
}
|
||||
|
||||
func (state *FoundryState) GetWorlds() Worlds {
|
||||
worldsCopy := make([]World, 0, 8)
|
||||
for i := range state.Worlds {
|
||||
world := &(state.Worlds[i])
|
||||
worldCopy := World{
|
||||
Id: world.Id,
|
||||
Title: world.Title,
|
||||
Description: world.Description,
|
||||
Compatibility: Compatibility{
|
||||
Minimum: world.Compatibility.Minimum,
|
||||
Maximum: world.Compatibility.Maximum,
|
||||
},
|
||||
System: world.System,
|
||||
CoreVersion: world.CoreVersion,
|
||||
SystemVersion: world.SystemVersion,
|
||||
LastPlayed: world.LastPlayed,
|
||||
PlayTime: world.PlayTime,
|
||||
NextSession: world.NextSession,
|
||||
}
|
||||
worldsCopy = append(worldsCopy, worldCopy)
|
||||
}
|
||||
return worldsCopy
|
||||
}
|
||||
|
||||
func (worlds Worlds) GetSessionTime(worldName string) (*time.Time, error) {
|
||||
if worldName == "" && len(worlds) != 1 {
|
||||
return nil, ErrorSetupNotFound
|
||||
}
|
||||
|
||||
if worldName == "" {
|
||||
return &worlds.GetById(0).NextSession, nil
|
||||
} else {
|
||||
for i := range worlds {
|
||||
if worlds[i].Id == worldName {
|
||||
return &worlds.GetById(0).NextSession, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, ErrorSetupNotFound
|
||||
}
|
||||
|
||||
func (world World) GetSessionTime() *time.Time {
|
||||
return &world.NextSession
|
||||
}
|
||||
32
internal/foundry/post_requests.go
Normal file
32
internal/foundry/post_requests.go
Normal file
@@ -0,0 +1,32 @@
|
||||
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
|
||||
}
|
||||
236
internal/foundry/websocket.go
Normal file
236
internal/foundry/websocket.go
Normal file
@@ -0,0 +1,236 @@
|
||||
package foundry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type webSocketUtil struct {
|
||||
wsConn *websocket.Conn
|
||||
currWsId int
|
||||
isReadReady bool
|
||||
|
||||
msgMap map[int](chan []byte)
|
||||
|
||||
mutex sync.Mutex
|
||||
channels Channels
|
||||
}
|
||||
|
||||
func parseCode(msg *string) string {
|
||||
for j := range RequestCodes {
|
||||
if !strings.HasPrefix(*msg, RequestCodes[j]) {
|
||||
continue
|
||||
}
|
||||
return RequestCodes[j]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseId(msg *string, start int) (int, int) {
|
||||
msgLen := len(*msg)
|
||||
j := start
|
||||
for ; j < msgLen; j++ {
|
||||
if (*msg)[j] < '0' || (*msg)[j] > '9' {
|
||||
break
|
||||
}
|
||||
}
|
||||
if j >= msgLen || j <= 0 {
|
||||
return 0, 0
|
||||
}
|
||||
|
||||
msgId, err := strconv.Atoi((*msg)[start:j])
|
||||
if err != nil {
|
||||
return 0, 0
|
||||
}
|
||||
return msgId, j
|
||||
}
|
||||
|
||||
func parseWsRespMessage(msg string) (*wsMessage, error) {
|
||||
data := &wsMessage{}
|
||||
|
||||
data.code = parseCode(&msg)
|
||||
if data.code != RespDataCode {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
i := len(data.code)
|
||||
if i == 0 {
|
||||
return nil, ErrorMsgNotHaveNumber
|
||||
}
|
||||
|
||||
data.id, i = parseId(&msg, i)
|
||||
if i == 0 {
|
||||
return nil, ErrorMsgNotHaveNumber
|
||||
}
|
||||
|
||||
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)
|
||||
defer cancel()
|
||||
|
||||
for {
|
||||
select {
|
||||
case msg, ok := <-ws.msgMap[id]:
|
||||
if !ok {
|
||||
time.Sleep(5 * time.Microsecond)
|
||||
continue
|
||||
}
|
||||
ws.closeMsgChannel(id, 0)
|
||||
return msg, nil
|
||||
case <-ctx.Done():
|
||||
err := ctx.Err()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, ErrorTimeout
|
||||
default:
|
||||
time.Sleep(5 * time.Microsecond)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *webSocketUtil) closeMsgChannel(id int, timeout time.Duration) bool {
|
||||
time.Sleep(timeout)
|
||||
|
||||
ws.mutex.Lock()
|
||||
defer ws.mutex.Unlock()
|
||||
|
||||
ok := true
|
||||
if _, ok = ws.msgMap[id]; !ok {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case _, ok = <-ws.msgMap[id]:
|
||||
if ok {
|
||||
close(ws.msgMap[id])
|
||||
delete(ws.msgMap, id)
|
||||
}
|
||||
default:
|
||||
close(ws.msgMap[id])
|
||||
delete(ws.msgMap, id)
|
||||
}
|
||||
fmt.Printf("Channel has been closed(id=%d, timeout=%d)\n", id, timeout)
|
||||
return ok
|
||||
}
|
||||
|
||||
func (ws *webSocketUtil) HandleWebsocketRequest(msg *wsMessage) ([]byte, error) {
|
||||
if !ws.IsReadReady() {
|
||||
return nil, ErrorIsNotReady
|
||||
}
|
||||
|
||||
err := ws.wsConn.WriteMessage(websocket.TextMessage, msg.toByteSlice())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data, err := ws.ReceiveMessage(msg.id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (ws *webSocketUtil) sendOnlyCodeRequest(code string) error {
|
||||
msgToSend := []byte(CodesRespToReq[code])
|
||||
log.Printf("send: %s\n", msgToSend)
|
||||
|
||||
return ws.wsConn.WriteMessage(websocket.TextMessage, msgToSend)
|
||||
}
|
||||
|
||||
func (ws *webSocketUtil) ListenWebSocket() {
|
||||
for {
|
||||
_, message, err := ws.wsConn.ReadMessage()
|
||||
if err != nil {
|
||||
ws.channels.Err() <- &FoundryError{Type: ReaderCode, Err: err, IsFatal: true}
|
||||
return
|
||||
}
|
||||
data, err := parseWsRespMessage(string(message))
|
||||
if err != nil {
|
||||
ws.channels.Err() <- &FoundryError{Type: ReaderCode, Err: err}
|
||||
continue
|
||||
}
|
||||
ws.channels.Msg() <- data
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *webSocketUtil) ServeWebSocket() {
|
||||
for {
|
||||
select {
|
||||
case message := <-ws.channels.Msg():
|
||||
log.Println("recv code:", message.code)
|
||||
|
||||
switch message.code {
|
||||
case RespPingCode, RespSessionData:
|
||||
err := ws.sendOnlyCodeRequest(message.code)
|
||||
if err != nil {
|
||||
ws.isReadReady = false
|
||||
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)
|
||||
default:
|
||||
}
|
||||
case <-ws.channels.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
25
internal/foundry/ws_channels.go
Normal file
25
internal/foundry/ws_channels.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package foundry
|
||||
|
||||
type Channels struct {
|
||||
done chan struct{}
|
||||
msg chan *wsMessage
|
||||
err chan error
|
||||
}
|
||||
|
||||
func (channels Channels) Err() chan error {
|
||||
return channels.err
|
||||
}
|
||||
|
||||
func (channels Channels) Msg() chan *wsMessage {
|
||||
return channels.msg
|
||||
}
|
||||
|
||||
func (channels Channels) Done() chan struct{} {
|
||||
return channels.done
|
||||
}
|
||||
|
||||
func (channels *Channels) Close() {
|
||||
close(channels.done)
|
||||
close(channels.err)
|
||||
close(channels.msg)
|
||||
}
|
||||
17
internal/foundry/ws_message.go
Normal file
17
internal/foundry/ws_message.go
Normal file
@@ -0,0 +1,17 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user