Compare commits

...

40 Commits

Author SHA1 Message Date
Flashfyre df92ff8b6f Add last activity update on verify 2024-05-15 13:37:36 -04:00
Up 509ca8df12
better errors 2024-05-15 07:28:49 +02:00
Up f31f130c14
also check for empty 2024-05-15 06:47:06 +02:00
Up c17c583321
update active session if none is found 2024-05-15 06:46:08 +02:00
Up 76e7ba02ad
always delete claimed vouchers 2024-05-15 04:27:53 +02:00
Up a063b1740c
add missing foreign key declarations 2024-05-15 04:12:20 +02:00
Up e4713e6ea3
fall back to legacy save ID 2024-05-15 04:08:42 +02:00
Up 2aab022ce3
properly use client session ID 2024-05-15 04:07:47 +02:00
Up e7cff35d69
delete vouchers when claiming them 2024-05-15 00:50:50 +02:00
Up 174b962f19
update verify endpoint 2024-05-15 00:00:38 +02:00
Up e2efcd550c
fix faulty sql query 2024-05-14 23:17:14 +02:00
Up 834d1e62a0
add foreign key constraint on client session table 2024-05-14 14:33:53 +02:00
Up c0aade2e65
simplify ID handling 2024-05-14 14:30:04 +02:00
Up 983e17c894
continue if linting fails 2024-05-14 13:23:22 +02:00
Up b88b3f6fab
explicitly define linter config 2024-05-14 13:18:39 +02:00
Up c24d006f88
move linter args to config file 2024-05-14 13:07:07 +02:00
Up 12b0a0df0b
try make linter ignore unused stuff 2024-05-14 13:01:29 +02:00
Up 436fce8759
add client session ID tokens 2024-05-14 12:54:06 +02:00
Up 8439519d8e
start on splitting api call handler function 2024-05-12 20:42:07 +02:00
Up d70c082aa9
simplify json response writing 2024-05-12 20:05:46 +02:00
Up f0c283af42
merge token and uuid lookups to reduce roundtrips 2024-05-12 19:44:04 +02:00
Up 81853b1863
forgot to update stats column 2024-05-12 08:38:57 +02:00
Up a44a6c382f
save data when applying vouchers 2024-05-12 08:30:46 +02:00
Up c06b1496a3
add watchtower in example compose file 2024-05-12 08:11:36 +02:00
Up 4430a18dae
update example compose file 2024-05-12 08:05:40 +02:00
Up 5d6bfe0c22
add accounts activity index 2024-05-12 05:12:46 +02:00
Up 2700afafdb
cleanup 2024-05-12 04:41:56 +02:00
Up 94df201bf7
update endpoint name 2024-05-12 03:42:35 +02:00
Up 884bb88cd3
add combined update endpoint 2024-05-12 03:34:08 +02:00
Up ab69d940e6
update action step name 2024-05-12 01:23:29 +02:00
Up 43f2f5a163
Merge pull request #11 from slsyy/run-golangci-lint-in-CI 2024-05-12 00:28:46 +02:00
Krystian Chmura 03865f9b94
run golangci-lint in CI 2024-05-11 14:41:25 +02:00
maru 36f353b8a6
Clean up db.go 2024-05-11 02:30:20 -04:00
maru 5656fb96d1
Use log.Fatal isntead of panic 2024-05-11 02:24:20 -04:00
Up dd013a1626
Merge pull request #8 from cgnetsec/master 2024-05-11 05:44:57 +02:00
ser3n1ty 8c209163db
Update README.md 2024-05-10 20:38:28 -07:00
ser3n1ty 1cec1d313d
Update README.md 2024-05-10 20:36:03 -07:00
ser3n1ty e01364e1a6
Update README.md 2024-05-09 01:44:04 -07:00
ser3n1ty d5e7b438f3
Update README.md
added updated information for the docker compose container that is being implemented
2024-05-09 00:57:07 -07:00
ser3n1ty b00321f501
Update README.md 2024-05-09 00:51:44 -07:00
14 changed files with 734 additions and 139 deletions

View File

@ -33,6 +33,12 @@ jobs:
go-version: ${{ env.GO_VERSION }}
- name: Install dependencies
run: go mod download
- name: Lint Codebase
continue-on-error: true
uses: golangci/golangci-lint-action@v6
with:
version: latest
args: --config .golangci.yml
- name: Test
run: go test -v
- name: Build

8
.golangci.yml Normal file
View File

@ -0,0 +1,8 @@
run:
timeout: 10m
severity:
default-severity: error
rules:
- linters:
- unused
severity: info

View File

@ -1 +1,83 @@
# rogueserver
# Hosting in Docker
It is advised that you host this in a docker container as it will be much easier to manage.
There is a sample docker-compose file for setting up a docker container to setup this server.
# Self Hosting outside of Docker:
## Required Tools:
- Golang
- Node: **18.3.0**
- npm: [how to install](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
## Installation:
The docker compose file should automatically implement a container with mariadb with an empty database and the default user and password combo of pokerogue:pokerogue
### src/utils.ts:224-225 (in pokerogue)
Replace both URLs (one on each line) with the local API server address from rogueserver.go (0.0.0.0:8001) (or whatever port you picked)
# If you are on Windows
Now that all of the files are configured: start up powershell as administrator:
```
cd C:\api\server\location\
go build .
.\rogueserver.exe --debug --dbuser yourusername --dbpass yourpassword
```
The other available flags are located in rogueserver.go:34-43.
Then in another run this the first time then run `npm run start` from the rogueserver location from then on:
```
powershell -ep bypass
cd C:\server\location\
npm install
npm run start
```
You will need to allow the port youre running the API (8001) on and port 8000 to accept inbound connections through the [Windows Advanced Firewall](https://www.youtube.com/watch?v=9llH5_CON-Y).
# If you are on Linux
In whatever shell you prefer, run the following:
```
cd /api/server/location/
go build .
./rogueserver --debug --dbuser yourusername --dbpass yourpassword &
cd /server/location/
npm run start
```
If you have a firewall running such as ufw on your linux machine, make sure to allow inbound connections on the ports youre running the API and the pokerogue server (8000,8001).
An example to allow incoming connections using UFW:
```
sudo ufw allow 8000,8001/tcp
```
This should allow you to reach the game from other computers on the same network.
## Tying to a Domain
If you want to tie it to a domain like I did and make it publicly accessible, there is some extra work to be done.
I setup caddy and would recommend using it as a reverse proxy.
[caddy installation](https://caddyserver.com/docs/install)
once its installed setup a config file for caddy:
```
pokerogue.exampledomain.com {
reverse_proxy localhost:8000
}
pokeapi.exampledomain.com {
reverse_proxy localhost:8001
}
```
Preferably set up caddy as a service from [here.](https://caddyserver.com/docs/running)
Once this is good to go, take your API url (https://pokeapi.exampledomain.com) and paste it on
### src/utils.ts:224-225
in place of the previous 0.0.0.0:8001 address
Make sure that both 8000 and 8001 are portforwarded on your router.
Test that the server's game and game authentication works from other machines both in and outside of the network. Once this is complete, enjoy!

View File

@ -19,6 +19,7 @@ package account
import (
"database/sql"
"errors"
"fmt"
"github.com/pagefaultgames/rogueserver/db"
@ -28,7 +29,7 @@ import (
func Logout(token []byte) error {
err := db.RemoveSessionFromToken(token)
if err != nil {
if err == sql.ErrNoRows {
if errors.Is(err, sql.ErrNoRows) {
return fmt.Errorf("token not found")
}

View File

@ -19,18 +19,22 @@ package api
import (
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/pagefaultgames/rogueserver/api/account"
"github.com/pagefaultgames/rogueserver/api/daily"
"github.com/pagefaultgames/rogueserver/db"
"log"
"net/http"
)
func Init(mux *http.ServeMux) {
scheduleStatRefresh()
daily.Init()
func Init(mux *http.ServeMux) error {
if err := scheduleStatRefresh(); err != nil {
return err
}
if err := daily.Init(); err != nil {
return err
}
// account
mux.HandleFunc("GET /account/info", handleAccountInfo)
@ -44,16 +48,23 @@ func Init(mux *http.ServeMux) {
mux.HandleFunc("GET /game/classicsessioncount", handleGameClassicSessionCount)
// savedata
mux.HandleFunc("GET /savedata/get", handleSaveData)
mux.HandleFunc("POST /savedata/update", handleSaveData)
mux.HandleFunc("GET /savedata/delete", handleSaveData)
mux.HandleFunc("POST /savedata/clear", handleSaveData)
mux.HandleFunc("GET /savedata/newclear", handleNewClear)
mux.HandleFunc("GET /savedata/get", legacyHandleGetSaveData)
mux.HandleFunc("POST /savedata/update", legacyHandleSaveData)
mux.HandleFunc("GET /savedata/delete", legacyHandleSaveData) // TODO use deleteSystemSave
mux.HandleFunc("POST /savedata/clear", legacyHandleSaveData) // TODO use clearSessionData
mux.HandleFunc("GET /savedata/newclear", legacyHandleNewClear)
// new session
mux.HandleFunc("POST /savedata/updateall", handleUpdateAll)
mux.HandleFunc("POST /savedata/system/verify", handleSystemVerify)
mux.HandleFunc("GET /savedata/system", handleGetSystemData)
mux.HandleFunc("GET /savedata/session", handleGetSessionData)
// daily
mux.HandleFunc("GET /daily/seed", handleDailySeed)
mux.HandleFunc("GET /daily/rankings", handleDailyRankings)
mux.HandleFunc("GET /daily/rankingpagecount", handleDailyRankingPageCount)
return nil
}
func tokenFromRequest(r *http.Request) ([]byte, error) {
@ -74,20 +85,34 @@ func tokenFromRequest(r *http.Request) ([]byte, error) {
}
func uuidFromRequest(r *http.Request) ([]byte, error) {
_, uuid, err := tokenAndUuidFromRequest(r)
return uuid, err
}
func tokenAndUuidFromRequest(r *http.Request) ([]byte, []byte, error) {
token, err := tokenFromRequest(r)
if err != nil {
return nil, err
return nil, nil, err
}
uuid, err := db.FetchUUIDFromToken(token)
if err != nil {
return nil, fmt.Errorf("failed to validate token: %s", err)
return nil, nil, fmt.Errorf("failed to validate token: %s", err)
}
return uuid, nil
return token, uuid, nil
}
func httpError(w http.ResponseWriter, r *http.Request, err error, code int) {
log.Printf("%s: %s\n", r.URL.Path, err)
http.Error(w, err.Error(), code)
}
func jsonResponse(w http.ResponseWriter, r *http.Request, data any) {
w.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(w).Encode(data)
if err != nil {
httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
return
}
}

View File

@ -20,6 +20,7 @@ package api
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
@ -58,13 +59,7 @@ func handleAccountInfo(w http.ResponseWriter, r *http.Request) {
return
}
err = json.NewEncoder(w).Encode(response)
if err != nil {
httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
jsonResponse(w, r, response)
}
func handleAccountRegister(w http.ResponseWriter, r *http.Request) {
@ -96,13 +91,7 @@ func handleAccountLogin(w http.ResponseWriter, r *http.Request) {
return
}
err = json.NewEncoder(w).Encode(response)
if err != nil {
httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
jsonResponse(w, r, response)
}
func handleAccountChangePW(w http.ResponseWriter, r *http.Request) {
@ -144,25 +133,66 @@ func handleAccountLogout(w http.ResponseWriter, r *http.Request) {
}
// game
func handleGameTitleStats(w http.ResponseWriter, r *http.Request) {
err := json.NewEncoder(w).Encode(defs.TitleStats{
stats := defs.TitleStats{
PlayerCount: playerCount,
BattleCount: battleCount,
})
if err != nil {
httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
jsonResponse(w, r, stats)
}
func handleGameClassicSessionCount(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(strconv.Itoa(classicSessionCount)))
_, _ = w.Write([]byte(strconv.Itoa(classicSessionCount)))
}
func handleSaveData(w http.ResponseWriter, r *http.Request) {
func handleGetSessionData(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
var slot int
if r.URL.Query().Has("slot") {
slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
var clientSessionId string
if r.URL.Query().Has("clientSessionId") {
clientSessionId = r.URL.Query().Get("clientSessionId")
} else {
httpError(w, r, fmt.Errorf("missing clientSessionId"), http.StatusBadRequest)
}
err = db.UpdateActiveSession(uuid, clientSessionId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
return
}
var save any
save, err = savedata.Get(uuid, 1, slot)
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
jsonResponse(w, r, save)
}
const legacyClientSessionId = "LEGACY_CLIENT"
func legacyHandleGetSaveData(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
@ -187,6 +217,231 @@ func handleSaveData(w http.ResponseWriter, r *http.Request) {
}
}
var save any
if datatype == 0 {
err = db.UpdateActiveSession(uuid, legacyClientSessionId) // we dont have a client id
if err != nil {
httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
return
}
}
save, err = savedata.Get(uuid, datatype, slot)
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
jsonResponse(w, r, save)
}
// FIXME UNFINISHED!!!
func clearSessionData(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
var slot int
if r.URL.Query().Has("slot") {
slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
var save any
var session defs.SessionSaveData
err = json.NewDecoder(r.Body).Decode(&session)
if err != nil {
httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
return
}
save = session
var active bool
active, err = db.IsActiveSession(uuid, legacyClientSessionId) //TODO unfinished, read token from query
if err != nil {
httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
return
}
var trainerId, secretId int
if r.URL.Query().Has("trainerId") && r.URL.Query().Has("secretId") {
trainerId, err = strconv.Atoi(r.URL.Query().Get("trainerId"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
secretId, err = strconv.Atoi(r.URL.Query().Get("secretId"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
storedTrainerId, storedSecretId, err := db.FetchTrainerIds(uuid)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
if storedTrainerId > 0 || storedSecretId > 0 {
if trainerId != storedTrainerId || secretId != storedSecretId {
httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
return
}
} else {
err = db.UpdateTrainerIds(trainerId, secretId, uuid)
if err != nil {
httpError(w, r, fmt.Errorf("unable to update trainer ID: %s", err), http.StatusInternalServerError)
return
}
}
if !active {
save = savedata.ClearResponse{Error: "session out of date: not active"}
}
var seed string
seed, err = db.GetDailyRunSeed()
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
response, err := savedata.Clear(uuid, slot, seed, save.(defs.SessionSaveData))
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
jsonResponse(w, r, response)
}
// FIXME UNFINISHED!!!
func deleteSystemSave(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
datatype := 0
if r.URL.Query().Has("datatype") {
datatype, err = strconv.Atoi(r.URL.Query().Get("datatype"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
var slot int
if r.URL.Query().Has("slot") {
slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
var active bool
active, err = db.IsActiveSession(uuid, legacyClientSessionId) //TODO unfinished, read token from query
if err != nil {
httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusInternalServerError)
return
}
if !active {
httpError(w, r, fmt.Errorf("session out of date: not active"), http.StatusBadRequest)
return
}
var trainerId, secretId int
if r.URL.Query().Has("trainerId") && r.URL.Query().Has("secretId") {
trainerId, err = strconv.Atoi(r.URL.Query().Get("trainerId"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
secretId, err = strconv.Atoi(r.URL.Query().Get("secretId"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
storedTrainerId, storedSecretId, err := db.FetchTrainerIds(uuid)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
if storedTrainerId > 0 || storedSecretId > 0 {
if trainerId != storedTrainerId || secretId != storedSecretId {
httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
return
}
} else {
if err := db.UpdateTrainerIds(trainerId, secretId, uuid); err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
}
err = savedata.Delete(uuid, datatype, slot)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func legacyHandleSaveData(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
datatype := -1
if r.URL.Query().Has("datatype") {
datatype, err = strconv.Atoi(r.URL.Query().Get("datatype"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
var slot int
if r.URL.Query().Has("slot") {
slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
}
var clientSessionId string
if r.URL.Query().Has("clientSessionId") {
clientSessionId = r.URL.Query().Get("clientSessionId")
}
if clientSessionId == "" {
clientSessionId = legacyClientSessionId
}
var save any
// /savedata/get and /savedata/delete specify datatype, but don't expect data in body
if r.URL.Path != "/savedata/get" && r.URL.Path != "/savedata/delete" {
@ -212,24 +467,17 @@ func handleSaveData(w http.ResponseWriter, r *http.Request) {
}
}
var token []byte
token, err = tokenFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
var active bool
if r.URL.Path == "/savedata/get" {
if datatype == 0 {
err = db.UpdateActiveSession(uuid, token)
err = db.UpdateActiveSession(uuid, clientSessionId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
return
}
}
} else {
active, err = db.IsActiveSession(token)
active, err = db.IsActiveSession(uuid, clientSessionId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
return
@ -237,7 +485,7 @@ func handleSaveData(w http.ResponseWriter, r *http.Request) {
// TODO: make this not suck
if !active && r.URL.Path != "/savedata/clear" {
httpError(w, r, fmt.Errorf("session out of date"), http.StatusBadRequest)
httpError(w, r, fmt.Errorf("session out of date: not active"), http.StatusBadRequest)
return
}
@ -270,11 +518,14 @@ func handleSaveData(w http.ResponseWriter, r *http.Request) {
if storedTrainerId > 0 || storedSecretId > 0 {
if trainerId != storedTrainerId || secretId != storedSecretId {
httpError(w, r, fmt.Errorf("session out of date"), http.StatusBadRequest)
httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
return
}
} else {
db.UpdateTrainerIds(trainerId, secretId, uuid)
if err := db.UpdateTrainerIds(trainerId, secretId, uuid); err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
}
}
@ -292,7 +543,7 @@ func handleSaveData(w http.ResponseWriter, r *http.Request) {
case "/savedata/clear":
if !active {
// TODO: make this not suck
save = savedata.ClearResponse{Error: "session out of date"}
save = savedata.ClearResponse{Error: "session out of date: not active"}
break
}
@ -316,16 +567,178 @@ func handleSaveData(w http.ResponseWriter, r *http.Request) {
return
}
err = json.NewEncoder(w).Encode(save)
jsonResponse(w, r, save)
}
type CombinedSaveData struct {
System defs.SystemSaveData `json:"system"`
Session defs.SessionSaveData `json:"session"`
SessionSlotId int `json:"sessionSlotId"`
ClientSessionId string `json:"clientSessionId"`
}
// TODO wrap this in a transaction
func handleUpdateAll(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
httpError(w, r, err, http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
var data CombinedSaveData
err = json.NewDecoder(r.Body).Decode(&data)
if err != nil {
httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
return
}
if data.ClientSessionId == "" {
data.ClientSessionId = legacyClientSessionId
}
var active bool
active, err = db.IsActiveSession(uuid, data.ClientSessionId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
return
}
if !active {
httpError(w, r, fmt.Errorf("session out of date: not active"), http.StatusBadRequest)
return
}
trainerId := data.System.TrainerId
secretId := data.System.SecretId
storedTrainerId, storedSecretId, err := db.FetchTrainerIds(uuid)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
if storedTrainerId > 0 || storedSecretId > 0 {
if trainerId != storedTrainerId || secretId != storedSecretId {
httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
return
}
} else {
if err = db.UpdateTrainerIds(trainerId, secretId, uuid); err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
}
err = savedata.Update(uuid, data.SessionSlotId, data.Session)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
err = savedata.Update(uuid, 0, data.System)
if err != nil {
httpError(w, r, err, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func handleNewClear(w http.ResponseWriter, r *http.Request) {
type SystemVerifyResponse struct {
Valid bool `json:"valid"`
SystemData *defs.SystemSaveData `json:"systemData"`
}
type SystemVerifyRequest struct {
ClientSessionId string `json:"clientSessionId"`
}
func handleSystemVerify(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
var input SystemVerifyRequest
err = json.NewDecoder(r.Body).Decode(&input)
if err != nil {
httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
return
}
var active bool
active, err = db.IsActiveSession(uuid, input.ClientSessionId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
return
}
response := SystemVerifyResponse{
Valid: active,
}
// not valid, send server state
if !active {
err = db.UpdateActiveSession(uuid, input.ClientSessionId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
return
}
var storedSaveData defs.SystemSaveData
storedSaveData, err = db.ReadSystemSaveData(uuid)
if err != nil {
httpError(w, r, fmt.Errorf("failed to read session save data: %s", err), http.StatusInternalServerError)
return
}
response.SystemData = &storedSaveData
}
err = db.UpdateAccountLastActivity(uuid)
if err != nil {
httpError(w, r, fmt.Errorf("failed to update account last activity: %s", err), http.StatusInternalServerError)
return
}
jsonResponse(w, r, response)
}
func handleGetSystemData(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
return
}
var clientSessionId string
if r.URL.Query().Has("clientSessionId") {
clientSessionId = r.URL.Query().Get("clientSessionId")
} else {
httpError(w, r, fmt.Errorf("missing clientSessionId"), http.StatusBadRequest)
}
err = db.UpdateActiveSession(uuid, clientSessionId)
if err != nil {
httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
return
}
var save any //TODO this is always system save data
save, err = savedata.Get(uuid, 0, 0)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
httpError(w, r, err, http.StatusInternalServerError)
}
return
}
//TODO apply vouchers
jsonResponse(w, r, save)
}
func legacyHandleNewClear(w http.ResponseWriter, r *http.Request) {
uuid, err := uuidFromRequest(r)
if err != nil {
httpError(w, r, err, http.StatusBadRequest)
@ -347,17 +760,10 @@ func handleNewClear(w http.ResponseWriter, r *http.Request) {
return
}
err = json.NewEncoder(w).Encode(newClear)
if err != nil {
httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
jsonResponse(w, r, newClear)
}
// daily
func handleDailySeed(w http.ResponseWriter, r *http.Request) {
seed, err := db.GetDailyRunSeed()
if err != nil {
@ -365,7 +771,10 @@ func handleDailySeed(w http.ResponseWriter, r *http.Request) {
return
}
w.Write([]byte(seed))
_, err = w.Write([]byte(seed))
if err != nil {
httpError(w, r, fmt.Errorf("failed to write seed: %s", err), http.StatusInternalServerError)
}
}
func handleDailyRankings(w http.ResponseWriter, r *http.Request) {
@ -395,13 +804,7 @@ func handleDailyRankings(w http.ResponseWriter, r *http.Request) {
return
}
err = json.NewEncoder(w).Encode(rankings)
if err != nil {
httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
jsonResponse(w, r, rankings)
}
func handleDailyRankingPageCount(w http.ResponseWriter, r *http.Request) {
@ -420,5 +823,5 @@ func handleDailyRankingPageCount(w http.ResponseWriter, r *http.Request) {
httpError(w, r, err, http.StatusInternalServerError)
}
w.Write([]byte(strconv.Itoa(count)))
_, _ = w.Write([]byte(strconv.Itoa(count)))
}

View File

@ -38,13 +38,34 @@ func Get(uuid []byte, datatype, slot int) (any, error) {
return nil, err
}
// TODO this should be a transaction
compensations, err := db.FetchAndClaimAccountCompensations(uuid)
if err != nil {
return nil, fmt.Errorf("failed to fetch compensations: %s", err)
}
needsUpdate := false
for compensationType, amount := range compensations {
system.VoucherCounts[strconv.Itoa(compensationType)] += amount
if amount > 0 {
needsUpdate = true
}
}
if needsUpdate {
err = db.StoreSystemSaveData(uuid, system)
if err != nil {
return nil, fmt.Errorf("failed to update system save data: %s", err)
}
err = db.DeleteClaimedAccountCompensations(uuid)
if err != nil {
return nil, fmt.Errorf("failed to delete claimed compensations: %s", err)
}
err = db.UpdateAccountStats(uuid, system.GameStats, system.VoucherCounts)
if err != nil {
return nil, fmt.Errorf("failed to update account stats: %s", err)
}
}
return system, nil

View File

@ -20,15 +20,11 @@ package savedata
import (
"fmt"
"log"
"strconv"
"github.com/klauspost/compress/zstd"
"github.com/pagefaultgames/rogueserver/db"
"github.com/pagefaultgames/rogueserver/defs"
)
var zstdEncoder, _ = zstd.NewWriter(nil)
// /savedata/update - update save data
func Update(uuid []byte, slot int, save any) error {
err := db.UpdateAccountLastActivity(uuid)
@ -62,12 +58,6 @@ func Update(uuid []byte, slot int, save any) error {
if slot < 0 || slot >= defs.SessionSlotCount {
return fmt.Errorf("slot id %d out of range", slot)
}
filename := "session"
if slot != 0 {
filename += strconv.Itoa(slot)
}
return db.StoreSessionSaveData(uuid, save, slot)
default:

View File

@ -32,15 +32,19 @@ var (
classicSessionCount int
)
func scheduleStatRefresh() {
scheduler.AddFunc("@every 30s", func() {
func scheduleStatRefresh() error {
_, err := scheduler.AddFunc("@every 30s", func() {
err := updateStats()
if err != nil {
log.Printf("failed to update stats: %s", err)
}
})
if err != nil {
return err
}
scheduler.Start()
return nil
}
func updateStats() error {

View File

@ -18,6 +18,8 @@
package db
import (
"database/sql"
"errors"
"fmt"
"slices"
@ -40,11 +42,6 @@ func AddAccountSession(username string, token []byte) error {
return err
}
_, err = handle.Exec("UPDATE sessions s JOIN accounts a ON a.uuid = s.uuid SET s.active = 1 WHERE a.username = ? AND a.lastLoggedIn IS NULL", username)
if err != nil {
return err
}
_, err = handle.Exec("UPDATE accounts SET lastLoggedIn = UTC_TIMESTAMP() WHERE username = ?", username)
if err != nil {
return err
@ -213,18 +210,25 @@ func UpdateTrainerIds(trainerId, secretId int, uuid []byte) error {
return nil
}
func IsActiveSession(token []byte) (bool, error) {
var active int
err := handle.QueryRow("SELECT `active` FROM sessions WHERE token = ?", token).Scan(&active)
func IsActiveSession(uuid []byte, clientSessionId string) (bool, error) {
var storedId string
err := handle.QueryRow("SELECT clientSessionId FROM activeClientSessions WHERE uuid = ?", uuid).Scan(&storedId)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
err = UpdateActiveSession(uuid, clientSessionId)
if err != nil {
return false, err
}
return true, nil
}
return false, err
}
return active == 1, nil
return storedId == "" || storedId == clientSessionId, nil
}
func UpdateActiveSession(uuid []byte, token []byte) error {
_, err := handle.Exec("UPDATE sessions SET `active` = CASE WHEN token = ? THEN 1 ELSE 0 END WHERE uuid = ?", token, uuid)
func UpdateActiveSession(uuid []byte, clientSessionId string) error {
_, err := handle.Exec("REPLACE INTO activeClientSessions VALUES (?, ?)", uuid, clientSessionId)
if err != nil {
return err
}

View File

@ -50,57 +50,33 @@ func Init(username, password, protocol, address, database string) error {
tx, err := handle.Begin()
if err != nil {
panic(err)
log.Fatal(err)
}
// accounts
tx.Exec("CREATE TABLE IF NOT EXISTS accounts (uuid BINARY(16) NOT NULL PRIMARY KEY, username VARCHAR(16) UNIQUE NOT NULL, hash BINARY(32) NOT NULL, salt BINARY(16) NOT NULL, registered TIMESTAMP NOT NULL, lastLoggedIn TIMESTAMP DEFAULT NULL, lastActivity TIMESTAMP DEFAULT NULL, banned TINYINT(1) NOT NULL DEFAULT 0, trainerId SMALLINT(5) UNSIGNED DEFAULT 0, secretId SMALLINT(5) UNSIGNED DEFAULT 0)")
// sessions
tx.Exec("CREATE TABLE IF NOT EXISTS sessions (token BINARY(32) NOT NULL PRIMARY KEY, uuid BINARY(16) NOT NULL, active TINYINT(1) NOT NULL DEFAULT 0, expire TIMESTAMP DEFAULT NULL, CONSTRAINT sessions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)")
tx.Exec("CREATE INDEX IF NOT EXISTS sessionsByUuid ON sessions (uuid)")
// stats
tx.Exec("CREATE TABLE IF NOT EXISTS accountStats (uuid BINARY(16) NOT NULL PRIMARY KEY, playTime INT(11) NOT NULL DEFAULT 0, battles INT(11) NOT NULL DEFAULT 0, classicSessionsPlayed INT(11) NOT NULL DEFAULT 0, sessionsWon INT(11) NOT NULL DEFAULT 0, highestEndlessWave INT(11) NOT NULL DEFAULT 0, highestLevel INT(11) NOT NULL DEFAULT 0, pokemonSeen INT(11) NOT NULL DEFAULT 0, pokemonDefeated INT(11) NOT NULL DEFAULT 0, pokemonCaught INT(11) NOT NULL DEFAULT 0, pokemonHatched INT(11) NOT NULL DEFAULT 0, eggsPulled INT(11) NOT NULL DEFAULT 0, regularVouchers INT(11) NOT NULL DEFAULT 0, plusVouchers INT(11) NOT NULL DEFAULT 0, premiumVouchers INT(11) NOT NULL DEFAULT 0, goldenVouchers INT(11) NOT NULL DEFAULT 0, CONSTRAINT accountStats_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)")
// compensations
tx.Exec("CREATE TABLE IF NOT EXISTS accountCompensations (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, uuid BINARY(16) NOT NULL, voucherType INT(11) NOT NULL, count INT(11) NOT NULL DEFAULT 1, claimed BIT(1) NOT NULL DEFAULT b'0', CONSTRAINT accountCompensations_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)")
tx.Exec("CREATE INDEX IF NOT EXISTS accountCompensationsByUuid ON accountCompensations (uuid)")
// daily runs
tx.Exec("CREATE TABLE IF NOT EXISTS dailyRuns (date DATE NOT NULL PRIMARY KEY, seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL)")
tx.Exec("CREATE INDEX IF NOT EXISTS dailyRunsByDateAndSeed ON dailyRuns (date, seed)")
tx.Exec("CREATE TABLE IF NOT EXISTS dailyRunCompletions (uuid BINARY(16) NOT NULL, seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, mode INT(11) NOT NULL DEFAULT 0, score INT(11) NOT NULL DEFAULT 0, timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (uuid, seed), CONSTRAINT dailyRunCompletions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)")
tx.Exec("CREATE INDEX IF NOT EXISTS dailyRunCompletionsByUuidAndSeed ON dailyRunCompletions (uuid, seed)")
tx.Exec("CREATE TABLE IF NOT EXISTS accountDailyRuns (uuid BINARY(16) NOT NULL, date DATE NOT NULL, score INT(11) NOT NULL DEFAULT 0, wave INT(11) NOT NULL DEFAULT 0, timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (uuid, date), CONSTRAINT accountDailyRuns_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT accountDailyRuns_ibfk_2 FOREIGN KEY (date) REFERENCES dailyRuns (date) ON DELETE NO ACTION ON UPDATE NO ACTION)")
tx.Exec("CREATE INDEX IF NOT EXISTS accountDailyRunsByDate ON accountDailyRuns (date)")
// save data
tx.Exec("CREATE TABLE IF NOT EXISTS systemSaveData (uuid BINARY(16) PRIMARY KEY, data LONGBLOB, timestamp TIMESTAMP)")
tx.Exec("CREATE TABLE IF NOT EXISTS sessionSaveData (uuid BINARY(16), slot TINYINT, data LONGBLOB, timestamp TIMESTAMP, PRIMARY KEY (uuid, slot))")
err = setupDb(tx)
if err != nil {
_ = tx.Rollback()
log.Fatal(err)
}
err = tx.Commit()
if err != nil {
panic(err)
log.Fatal(err)
}
// TODO temp code
_, err = os.Stat("userdata")
if err != nil {
if os.IsNotExist(err) { // not found, do not migrate
return nil
} else {
if !os.IsNotExist(err) { // not found, do not migrate
log.Fatalf("failed to stat userdata directory: %s", err)
return err
}
return nil
}
entries, err := os.ReadDir("userdata")
if err != nil {
log.Fatalln(err)
return nil
log.Fatal(err)
}
for _, entry := range entries {
@ -131,7 +107,6 @@ func Init(username, password, protocol, address, database string) error {
err = StoreSystemSaveData(uuid, systemData)
if err != nil {
log.Fatalf("failed to store system save data for %v: %s\n", uuidString, err)
continue
}
// delete old system data
@ -167,3 +142,47 @@ func Init(username, password, protocol, address, database string) error {
return nil
}
func setupDb(tx *sql.Tx) error {
queries := []string{
// MIGRATION 000
`CREATE TABLE IF NOT EXISTS accounts (uuid BINARY(16) NOT NULL PRIMARY KEY, username VARCHAR(16) UNIQUE NOT NULL, hash BINARY(32) NOT NULL, salt BINARY(16) NOT NULL, registered TIMESTAMP NOT NULL, lastLoggedIn TIMESTAMP DEFAULT NULL, lastActivity TIMESTAMP DEFAULT NULL, banned TINYINT(1) NOT NULL DEFAULT 0, trainerId SMALLINT(5) UNSIGNED DEFAULT 0, secretId SMALLINT(5) UNSIGNED DEFAULT 0)`,
`CREATE INDEX IF NOT EXISTS accountsByActivity ON accounts (lastActivity)`,
`CREATE TABLE IF NOT EXISTS sessions (token BINARY(32) NOT NULL PRIMARY KEY, uuid BINARY(16) NOT NULL, active TINYINT(1) NOT NULL DEFAULT 0, expire TIMESTAMP DEFAULT NULL, CONSTRAINT sessions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
`CREATE INDEX IF NOT EXISTS sessionsByUuid ON sessions (uuid)`,
`CREATE TABLE IF NOT EXISTS accountStats (uuid BINARY(16) NOT NULL PRIMARY KEY, playTime INT(11) NOT NULL DEFAULT 0, battles INT(11) NOT NULL DEFAULT 0, classicSessionsPlayed INT(11) NOT NULL DEFAULT 0, sessionsWon INT(11) NOT NULL DEFAULT 0, highestEndlessWave INT(11) NOT NULL DEFAULT 0, highestLevel INT(11) NOT NULL DEFAULT 0, pokemonSeen INT(11) NOT NULL DEFAULT 0, pokemonDefeated INT(11) NOT NULL DEFAULT 0, pokemonCaught INT(11) NOT NULL DEFAULT 0, pokemonHatched INT(11) NOT NULL DEFAULT 0, eggsPulled INT(11) NOT NULL DEFAULT 0, regularVouchers INT(11) NOT NULL DEFAULT 0, plusVouchers INT(11) NOT NULL DEFAULT 0, premiumVouchers INT(11) NOT NULL DEFAULT 0, goldenVouchers INT(11) NOT NULL DEFAULT 0, CONSTRAINT accountStats_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
`CREATE TABLE IF NOT EXISTS accountCompensations (id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, uuid BINARY(16) NOT NULL, voucherType INT(11) NOT NULL, count INT(11) NOT NULL DEFAULT 1, claimed BIT(1) NOT NULL DEFAULT b'0', CONSTRAINT accountCompensations_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
`CREATE INDEX IF NOT EXISTS accountCompensationsByUuid ON accountCompensations (uuid)`,
`CREATE TABLE IF NOT EXISTS dailyRuns (date DATE NOT NULL PRIMARY KEY, seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL)`,
`CREATE INDEX IF NOT EXISTS dailyRunsByDateAndSeed ON dailyRuns (date, seed)`,
`CREATE TABLE IF NOT EXISTS dailyRunCompletions (uuid BINARY(16) NOT NULL, seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, mode INT(11) NOT NULL DEFAULT 0, score INT(11) NOT NULL DEFAULT 0, timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (uuid, seed), CONSTRAINT dailyRunCompletions_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
`CREATE INDEX IF NOT EXISTS dailyRunCompletionsByUuidAndSeed ON dailyRunCompletions (uuid, seed)`,
`CREATE TABLE IF NOT EXISTS accountDailyRuns (uuid BINARY(16) NOT NULL, date DATE NOT NULL, score INT(11) NOT NULL DEFAULT 0, wave INT(11) NOT NULL DEFAULT 0, timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (uuid, date), CONSTRAINT accountDailyRuns_ibfk_1 FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT accountDailyRuns_ibfk_2 FOREIGN KEY (date) REFERENCES dailyRuns (date) ON DELETE NO ACTION ON UPDATE NO ACTION)`,
`CREATE INDEX IF NOT EXISTS accountDailyRunsByDate ON accountDailyRuns (date)`,
`CREATE TABLE IF NOT EXISTS systemSaveData (uuid BINARY(16) PRIMARY KEY, data LONGBLOB, timestamp TIMESTAMP, FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
`CREATE TABLE IF NOT EXISTS sessionSaveData (uuid BINARY(16), slot TINYINT, data LONGBLOB, timestamp TIMESTAMP, PRIMARY KEY (uuid, slot), FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
// ----------------------------------
// MIGRATION 001
`ALTER TABLE sessions DROP COLUMN IF EXISTS active`,
`CREATE TABLE IF NOT EXISTS activeClientSessions (uuid BINARY(16) NOT NULL PRIMARY KEY, clientSessionId VARCHAR(32) NOT NULL, FOREIGN KEY (uuid) REFERENCES accounts (uuid) ON DELETE CASCADE ON UPDATE CASCADE)`,
}
for _, q := range queries {
_, err := tx.Exec(q)
if err != nil {
return fmt.Errorf("failed to execute query: %w, query: %s", err, q)
}
}
return nil
}

View File

@ -29,7 +29,7 @@ func FetchPlayerCount() (int, error) {
func FetchBattleCount() (int, error) {
var battleCount int
err := handle.QueryRow("SELECT COALESCE(SUM(battles), 0) FROM accountStats").Scan(&battleCount)
err := handle.QueryRow("SELECT COALESCE(SUM(s.battles), 0) FROM accountStats s JOIN accounts a ON a.uuid = s.uuid WHERE a.banned = 0").Scan(&battleCount)
if err != nil {
return 0, err
}
@ -39,7 +39,7 @@ func FetchBattleCount() (int, error) {
func FetchClassicSessionCount() (int, error) {
var classicSessionCount int
err := handle.QueryRow("SELECT COALESCE(SUM(classicSessionsPlayed), 0) FROM accountStats").Scan(&classicSessionCount)
err := handle.QueryRow("SELECT COALESCE(SUM(s.classicSessionsPlayed), 0) FROM accountStats s JOIN accounts a ON a.uuid = s.uuid WHERE a.banned = 0").Scan(&classicSessionCount)
if err != nil {
return 0, err
}

View File

@ -1,17 +1,26 @@
services:
server:
image: ghcr.io/pagefaultgames/pokerogue:latest
command: --debug --dbaddr db:3306 --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb
command: --debug --dbaddr db --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb
image: ghcr.io/pagefaultgames/rogueserver:master
restart: unless-stopped
depends_on:
- db
db:
condition: service_healthy
networks:
- internal
ports:
- "8001:8001"
db:
image: mariadb:11
restart: unless-stopped
healthcheck:
test: [ "CMD", "healthcheck.sh", "--su-mysql", "--connect", "--innodb_initialized" ]
start_period: 10s
start_interval: 10s
interval: 1m
timeout: 5s
retries: 3
environment:
MYSQL_ROOT_PASSWORD: admin
MYSQL_DATABASE: pokeroguedb
@ -19,6 +28,24 @@ services:
MYSQL_PASSWORD: pokerogue
volumes:
- database:/var/lib/mysql
networks:
- internal
# Watchtower is a service that will automatically update your running containers
# when a new image is available. This is useful for keeping your server up-to-date.
# see https://containrrr.dev/watchtower/ for more information.
watchtower:
image: containrrr/watchtower
container_name: watchtower
restart: always
security_opt:
- no-new-privileges:true
environment:
WATCHTOWER_CLEANUP: true
WATCHTOWER_SCHEDULE: "@midnight"
volumes:
- /etc/localtime:/etc/localtime:ro
- /var/run/docker.sock:/var/run/docker.sock
volumes:
database:

View File

@ -65,7 +65,9 @@ func main() {
mux := http.NewServeMux()
// init api
api.Init(mux)
if err := api.Init(mux); err != nil {
log.Fatal(err)
}
// start web server
handler := prodHandler(mux)
@ -94,7 +96,10 @@ func createListener(proto, addr string) (net.Listener, error) {
}
if proto == "unix" {
os.Chmod(addr, 0777)
if err := os.Chmod(addr, 0777); err != nil {
listener.Close()
return nil, err
}
}
return listener, nil