├── .dockerignore
├── .golangci.yml
├── .gitignore
├── go.mod
├── docker-compose.Development.yml
├── Dockerfile
├── go.sum
├── defs
├── game.go
├── daily.go
└── savedata.go
├── api
├── savedata
│ ├── common.go
│ ├── newclear.go
│ ├── delete.go
│ ├── update.go
│ ├── clear.go
│ └── get.go
├── daily
│ ├── rankingspagecount.go
│ ├── rankings.go
│ └── common.go
├── account
│ ├── logout.go
│ ├── changepw.go
│ ├── common.go
│ ├── info.go
│ ├── register.go
│ └── login.go
├── stats.go
├── common.go
└── endpoints.go
├── .github
└── workflows
│ ├── ghcr.yml
│ └── ci.yml
├── db
├── game.go
├── legacy.go
├── daily.go
├── savedata.go
├── account.go
└── db.go
├── docker-compose.Example.yml
├── README.md
├── rogueserver.go
└── LICENSE
/.dockerignore:
--------------------------------------------------------------------------------
1 | /.github/
2 |
3 | Dockerfile*
4 | docker-compose*.yml
5 |
6 | /.data/
7 | /secret.key
8 |
9 | /rogueserver*
10 | !/rogueserver.go
11 |
--------------------------------------------------------------------------------
/.golangci.yml:
--------------------------------------------------------------------------------
1 | run:
2 | timeout: 10m
3 | severity:
4 | default-severity: error
5 | rules:
6 | - linters:
7 | - unused
8 | severity: info
9 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # no extension on linux, .exe on windows
3 | rogueserver*
4 | !/rogueserver/*
5 | /userdata/*
6 | secret.key
7 |
8 | # local testing
9 | /.data/
10 |
11 | # Jetbrains IDEs
12 | /.idea/
13 | *.iml
14 | *.ipr
15 | *.iws
16 | .vscode/launch.json
17 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/pagefaultgames/rogueserver
2 |
3 | go 1.22
4 |
5 | require (
6 | github.com/go-sql-driver/mysql v1.7.1
7 | github.com/klauspost/compress v1.17.4
8 | github.com/robfig/cron/v3 v3.0.1
9 | golang.org/x/crypto v0.16.0
10 | )
11 |
12 | require golang.org/x/sys v0.15.0 // indirect
13 |
--------------------------------------------------------------------------------
/docker-compose.Development.yml:
--------------------------------------------------------------------------------
1 | services:
2 | db:
3 | image: mariadb:11
4 | container_name: pokerogue-db-local
5 | restart: on-failure
6 | environment:
7 | MYSQL_ROOT_PASSWORD: admin
8 | MYSQL_DATABASE: pokeroguedb
9 | MYSQL_USER: pokerogue
10 | MYSQL_PASSWORD: pokerogue
11 | ports:
12 | - "3306:3306"
13 | volumes:
14 | - ./.data/db:/var/lib/mysql
15 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | ARG GO_VERSION=1.22
2 |
3 | FROM golang:${GO_VERSION} AS builder
4 |
5 | WORKDIR /src
6 |
7 | COPY ./go.mod /src/
8 | COPY ./go.sum /src/
9 |
10 | RUN go mod download && go mod verify
11 |
12 | COPY . /src/
13 |
14 | RUN CGO_ENABLED=0 \
15 | go build -o rogueserver
16 |
17 | RUN chmod +x /src/rogueserver
18 |
19 | # ---------------------------------------------
20 |
21 | FROM scratch
22 |
23 | WORKDIR /app
24 |
25 | COPY --from=builder /src/rogueserver .
26 |
27 | EXPOSE 8001
28 |
29 | ENTRYPOINT ["./rogueserver"]
30 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI=
2 | github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
3 | github.com/klauspost/compress v1.17.4 h1:Ej5ixsIri7BrIjBkRZLTo6ghwrEtHFk7ijlczPW4fZ4=
4 | github.com/klauspost/compress v1.17.4/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM=
5 | github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
6 | github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
7 | golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY=
8 | golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
9 | golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
10 | golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
11 |
--------------------------------------------------------------------------------
/defs/game.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package defs
19 |
20 | type TitleStats struct {
21 | PlayerCount int `json:"playerCount"`
22 | BattleCount int `json:"battleCount"`
23 | }
24 |
--------------------------------------------------------------------------------
/defs/daily.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package defs
19 |
20 | type DailyRanking struct {
21 | Rank int `json:"rank"`
22 | Username string `json:"username"`
23 | Score int `json:"score"`
24 | Wave int `json:"wave"`
25 | }
26 |
--------------------------------------------------------------------------------
/api/savedata/common.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package savedata
19 |
20 | import (
21 | "github.com/pagefaultgames/rogueserver/defs"
22 | )
23 |
24 | func validateSessionCompleted(session defs.SessionSaveData) bool {
25 | switch session.GameMode {
26 | case 0:
27 | return session.BattleType == 2 && session.WaveIndex == 200
28 | case 3:
29 | return session.BattleType == 2 && session.WaveIndex == 50
30 | }
31 |
32 | return false
33 | }
34 |
--------------------------------------------------------------------------------
/api/daily/rankingspagecount.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package daily
19 |
20 | import (
21 | "log"
22 |
23 | "github.com/pagefaultgames/rogueserver/db"
24 | )
25 |
26 | // /daily/rankingpagecount - fetch daily ranking page count
27 | func RankingPageCount(category int) (int, error) {
28 | pageCount, err := db.FetchRankingPageCount(category)
29 | if err != nil {
30 | log.Print("failed to retrieve ranking page count")
31 | }
32 |
33 | return pageCount, nil
34 | }
35 |
--------------------------------------------------------------------------------
/api/daily/rankings.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package daily
19 |
20 | import (
21 | "log"
22 |
23 | "github.com/pagefaultgames/rogueserver/db"
24 | "github.com/pagefaultgames/rogueserver/defs"
25 | )
26 |
27 | // /daily/rankings - fetch daily rankings
28 | func Rankings(category, page int) ([]defs.DailyRanking, error) {
29 | rankings, err := db.FetchRankings(category, page)
30 | if err != nil {
31 | log.Print("failed to retrieve rankings")
32 | }
33 |
34 | return rankings, nil
35 | }
36 |
--------------------------------------------------------------------------------
/api/account/logout.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package account
19 |
20 | import (
21 | "database/sql"
22 | "errors"
23 | "fmt"
24 |
25 | "github.com/pagefaultgames/rogueserver/db"
26 | )
27 |
28 | // /account/logout - log out of account
29 | func Logout(token []byte) error {
30 | err := db.RemoveSessionFromToken(token)
31 | if err != nil {
32 | if errors.Is(err, sql.ErrNoRows) {
33 | return fmt.Errorf("token not found")
34 | }
35 |
36 | return fmt.Errorf("failed to remove account session")
37 | }
38 |
39 | return nil
40 | }
41 |
--------------------------------------------------------------------------------
/.github/workflows/ghcr.yml:
--------------------------------------------------------------------------------
1 | name: Publish to GHCR
2 |
3 | on:
4 | push:
5 |
6 | jobs:
7 | build:
8 | name: Build and publish to GHCR
9 | if: github.repository == 'pagefaultgames/rogueserver'
10 | env:
11 | GO_VERSION: 1.22
12 | runs-on: ubuntu-latest
13 | steps:
14 | - name: Setup Docker BuildX
15 | uses: docker/setup-buildx-action@v3
16 | - name: Log into container registry
17 | uses: docker/login-action@v3
18 | with:
19 | registry: ghcr.io
20 | username: ${{ github.repository_owner }}
21 | password: ${{ github.token }}
22 | - name: Extract Docker metadata
23 | id: meta
24 | uses: docker/metadata-action@v5
25 | with:
26 | images: ghcr.io/${{ github.repository }}
27 | - name: Build Docker image
28 | uses: docker/build-push-action@v5
29 | with:
30 | push: true
31 | tags: ${{ steps.meta.outputs.tags }}
32 | labels: ${{ steps.meta.outputs.labels }}
33 | cache-from: type=gha
34 | cache-to: type=gha,mode=max
35 | build-args: |
36 | GO_VERSION=${{ env.GO_VERSION }}
37 | VERSION=${{ github.ref_name }}-SNAPSHOT
38 | COMMIT_SHA=${{ env.GITHUB_SHA_SHORT }}
39 |
--------------------------------------------------------------------------------
/api/account/changepw.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package account
19 |
20 | import (
21 | "crypto/rand"
22 | "fmt"
23 |
24 | "github.com/pagefaultgames/rogueserver/db"
25 | )
26 |
27 | func ChangePW(uuid []byte, password string) error {
28 | if len(password) < 6 {
29 | return fmt.Errorf("invalid password")
30 | }
31 |
32 | salt := make([]byte, ArgonSaltSize)
33 | _, err := rand.Read(salt)
34 | if err != nil {
35 | return fmt.Errorf(fmt.Sprintf("failed to generate salt: %s", err))
36 | }
37 |
38 | err = db.UpdateAccountPassword(uuid, deriveArgon2IDKey([]byte(password), salt), salt)
39 | if err != nil {
40 | return fmt.Errorf("failed to add account record: %s", err)
41 | }
42 |
43 | return nil
44 | }
45 |
--------------------------------------------------------------------------------
/api/savedata/newclear.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package savedata
19 |
20 | import (
21 | "fmt"
22 |
23 | "github.com/pagefaultgames/rogueserver/db"
24 | "github.com/pagefaultgames/rogueserver/defs"
25 | )
26 |
27 | // /savedata/newclear - return whether a session is a new clear for its seed
28 | func NewClear(uuid []byte, slot int) (bool, error) {
29 | if slot < 0 || slot >= defs.SessionSlotCount {
30 | return false, fmt.Errorf("slot id %d out of range", slot)
31 | }
32 |
33 | session, err := db.ReadSessionSaveData(uuid, slot)
34 | if err != nil {
35 | return false, err
36 | }
37 |
38 | completed, err := db.ReadSeedCompleted(uuid, session.Seed)
39 | if err != nil {
40 | return false, fmt.Errorf("failed to read seed completed: %s", err)
41 | }
42 |
43 | return !completed, nil
44 | }
45 |
--------------------------------------------------------------------------------
/api/savedata/delete.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package savedata
19 |
20 | import (
21 | "fmt"
22 | "github.com/pagefaultgames/rogueserver/db"
23 | "github.com/pagefaultgames/rogueserver/defs"
24 | "log"
25 | )
26 |
27 | // /savedata/delete - delete save data
28 | func Delete(uuid []byte, datatype, slot int) error {
29 | err := db.UpdateAccountLastActivity(uuid)
30 | if err != nil {
31 | log.Print("failed to update account last activity")
32 | }
33 |
34 | switch datatype {
35 | case 0: // System
36 | return db.DeleteSystemSaveData(uuid)
37 | case 1: // Session
38 | if slot < 0 || slot >= defs.SessionSlotCount {
39 | return fmt.Errorf("slot id %d out of range", slot)
40 | }
41 |
42 | return db.DeleteSessionSaveData(uuid, slot)
43 | default:
44 | return fmt.Errorf("invalid data type")
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on:
4 | push:
5 | pull_request:
6 |
7 | jobs:
8 | build:
9 | name: Build (${{ matrix.os_name }})
10 | env:
11 | GO_VERSION: 1.22
12 | GOOS: ${{ matrix.os_name }}
13 | GOARCH: ${{ matrix.arch }}
14 | runs-on: ${{ matrix.os }}
15 | strategy:
16 | fail-fast: false
17 | matrix:
18 | include:
19 | - os: ubuntu-latest
20 | os_name: linux
21 | arch: amd64
22 | - os: windows-latest
23 | os_name: windows
24 | arch: amd64
25 | # TODO macos needs universal binary!
26 | # - os: macos-latest
27 | # os_name: macos
28 | steps:
29 | - uses: actions/checkout@v4
30 | - name: Set up Go ${{ env.GO_VERSION }}
31 | uses: actions/setup-go@v5
32 | with:
33 | go-version: ${{ env.GO_VERSION }}
34 | - name: Install dependencies
35 | run: go mod download
36 | - name: Lint Codebase
37 | continue-on-error: true
38 | uses: golangci/golangci-lint-action@v6
39 | with:
40 | version: latest
41 | args: --config .golangci.yml
42 | - name: Test
43 | run: go test -v
44 | - name: Build
45 | run: go build -v
46 | - name: Upload artifact
47 | uses: actions/upload-artifact@v4
48 | with:
49 | name: rogueserver-${{ matrix.os_name }}-${{ matrix.arch }}-${{ github.sha }}
50 | path: |
51 | rogueserver*
52 | !rogueserver.go
53 |
--------------------------------------------------------------------------------
/api/account/common.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package account
19 |
20 | import (
21 | "regexp"
22 | "runtime"
23 |
24 | "golang.org/x/crypto/argon2"
25 | )
26 |
27 | type GenericAuthResponse struct {
28 | Token string `json:"token"`
29 | }
30 |
31 | const (
32 | ArgonTime = 1
33 | ArgonMemory = 256 * 1024
34 | ArgonThreads = 4
35 | ArgonKeySize = 32
36 | ArgonSaltSize = 16
37 |
38 | UUIDSize = 16
39 | TokenSize = 32
40 | )
41 |
42 | var (
43 | ArgonMaxInstances = runtime.NumCPU()
44 |
45 | isValidUsername = regexp.MustCompile(`^\w{1,16}$`).MatchString
46 | semaphore = make(chan bool, ArgonMaxInstances)
47 | )
48 |
49 | func deriveArgon2IDKey(password, salt []byte) []byte {
50 | semaphore <- true
51 | defer func() { <-semaphore }()
52 |
53 | return argon2.IDKey(password, salt, ArgonTime, ArgonMemory, ArgonThreads, ArgonKeySize)
54 | }
55 |
--------------------------------------------------------------------------------
/db/game.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package db
19 |
20 | func FetchPlayerCount() (int, error) {
21 | var playerCount int
22 | err := handle.QueryRow("SELECT COUNT(*) FROM accounts WHERE lastActivity > DATE_SUB(UTC_TIMESTAMP(), INTERVAL 5 MINUTE)").Scan(&playerCount)
23 | if err != nil {
24 | return 0, err
25 | }
26 |
27 | return playerCount, nil
28 | }
29 |
30 | func FetchBattleCount() (int, error) {
31 | var battleCount int
32 | err := handle.QueryRow("SELECT COALESCE(SUM(battles), 0) FROM accountStats").Scan(&battleCount)
33 | if err != nil {
34 | return 0, err
35 | }
36 |
37 | return battleCount, nil
38 | }
39 |
40 | func FetchClassicSessionCount() (int, error) {
41 | var classicSessionCount int
42 | err := handle.QueryRow("SELECT COALESCE(SUM(classicSessionsPlayed), 0) FROM accountStats").Scan(&classicSessionCount)
43 | if err != nil {
44 | return 0, err
45 | }
46 |
47 | return classicSessionCount, nil
48 | }
49 |
--------------------------------------------------------------------------------
/docker-compose.Example.yml:
--------------------------------------------------------------------------------
1 | services:
2 | server:
3 | command: --debug --dbaddr db --dbuser pokerogue --dbpass pokerogue --dbname pokeroguedb
4 | image: ghcr.io/pagefaultgames/rogueserver:master
5 | restart: unless-stopped
6 | depends_on:
7 | db:
8 | condition: service_healthy
9 | networks:
10 | - internal
11 | ports:
12 | - "8001:8001"
13 |
14 | db:
15 | image: mariadb:11
16 | restart: unless-stopped
17 | healthcheck:
18 | test: [ "CMD", "healthcheck.sh", "--su-mysql", "--connect", "--innodb_initialized" ]
19 | start_period: 10s
20 | start_interval: 10s
21 | interval: 1m
22 | timeout: 5s
23 | retries: 3
24 | environment:
25 | MYSQL_ROOT_PASSWORD: admin
26 | MYSQL_DATABASE: pokeroguedb
27 | MYSQL_USER: pokerogue
28 | MYSQL_PASSWORD: pokerogue
29 | volumes:
30 | - database:/var/lib/mysql
31 | networks:
32 | - internal
33 |
34 | # Watchtower is a service that will automatically update your running containers
35 | # when a new image is available. This is useful for keeping your server up-to-date.
36 | # see https://containrrr.dev/watchtower/ for more information.
37 | watchtower:
38 | image: containrrr/watchtower
39 | container_name: watchtower
40 | restart: always
41 | security_opt:
42 | - no-new-privileges:true
43 | environment:
44 | WATCHTOWER_CLEANUP: true
45 | WATCHTOWER_SCHEDULE: "@midnight"
46 | volumes:
47 | - /etc/localtime:/etc/localtime:ro
48 | - /var/run/docker.sock:/var/run/docker.sock
49 |
50 | volumes:
51 | database:
52 |
53 | networks:
54 | internal:
55 |
--------------------------------------------------------------------------------
/api/account/info.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package account
19 |
20 | import (
21 | "github.com/pagefaultgames/rogueserver/db"
22 | "github.com/pagefaultgames/rogueserver/defs"
23 | )
24 |
25 | type InfoResponse struct {
26 | Username string `json:"username"`
27 | LastSessionSlot int `json:"lastSessionSlot"`
28 | }
29 |
30 | // /account/info - get account info
31 | func Info(username string, uuid []byte) (InfoResponse, error) {
32 | response := InfoResponse{Username: username, LastSessionSlot: -1}
33 |
34 | highest := -1
35 | for i := 0; i < defs.SessionSlotCount; i++ {
36 | data, err := db.ReadSessionSaveData(uuid, i)
37 | if err != nil {
38 | continue
39 | }
40 |
41 | if data.Timestamp > highest {
42 | highest = data.Timestamp
43 | response.LastSessionSlot = i
44 | }
45 | }
46 |
47 | if response.LastSessionSlot < 0 || response.LastSessionSlot >= defs.SessionSlotCount {
48 | response.LastSessionSlot = -1
49 | }
50 |
51 | return response, nil
52 | }
53 |
--------------------------------------------------------------------------------
/api/account/register.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package account
19 |
20 | import (
21 | "crypto/rand"
22 | "fmt"
23 | "github.com/pagefaultgames/rogueserver/db"
24 | )
25 |
26 | // /account/register - register account
27 | func Register(username, password string) error {
28 | if !isValidUsername(username) {
29 | return fmt.Errorf("invalid username")
30 | }
31 |
32 | if len(password) < 6 {
33 | return fmt.Errorf("invalid password")
34 | }
35 |
36 | uuid := make([]byte, UUIDSize)
37 | _, err := rand.Read(uuid)
38 | if err != nil {
39 | return fmt.Errorf("failed to generate uuid: %s", err)
40 | }
41 |
42 | salt := make([]byte, ArgonSaltSize)
43 | _, err = rand.Read(salt)
44 | if err != nil {
45 | return fmt.Errorf(fmt.Sprintf("failed to generate salt: %s", err))
46 | }
47 |
48 | err = db.AddAccountRecord(uuid, username, deriveArgon2IDKey([]byte(password), salt), salt)
49 | if err != nil {
50 | return fmt.Errorf("failed to add account record: %s", err)
51 | }
52 |
53 | return nil
54 | }
55 |
--------------------------------------------------------------------------------
/api/stats.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package api
19 |
20 | import (
21 | "log"
22 | "time"
23 |
24 | "github.com/pagefaultgames/rogueserver/db"
25 | "github.com/robfig/cron/v3"
26 | )
27 |
28 | var (
29 | scheduler = cron.New(cron.WithLocation(time.UTC))
30 | playerCount int
31 | battleCount int
32 | classicSessionCount int
33 | )
34 |
35 | func scheduleStatRefresh() error {
36 | _, err := scheduler.AddFunc("@every 30s", func() {
37 | err := updateStats()
38 | if err != nil {
39 | log.Printf("failed to update stats: %s", err)
40 | }
41 | })
42 | if err != nil {
43 | return err
44 | }
45 |
46 | scheduler.Start()
47 | return nil
48 | }
49 |
50 | func updateStats() error {
51 | var err error
52 | playerCount, err = db.FetchPlayerCount()
53 | if err != nil {
54 | return err
55 | }
56 |
57 | battleCount, err = db.FetchBattleCount()
58 | if err != nil {
59 | return err
60 | }
61 |
62 | classicSessionCount, err = db.FetchClassicSessionCount()
63 | if err != nil {
64 | return err
65 | }
66 |
67 | return nil
68 | }
69 |
--------------------------------------------------------------------------------
/api/account/login.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package account
19 |
20 | import (
21 | "bytes"
22 | "crypto/rand"
23 | "database/sql"
24 | "encoding/base64"
25 | "fmt"
26 |
27 | "github.com/pagefaultgames/rogueserver/db"
28 | )
29 |
30 | type LoginResponse GenericAuthResponse
31 |
32 | // /account/login - log into account
33 | func Login(username, password string) (LoginResponse, error) {
34 | var response LoginResponse
35 |
36 | if !isValidUsername(username) {
37 | return response, fmt.Errorf("invalid username")
38 | }
39 |
40 | if len(password) < 6 {
41 | return response, fmt.Errorf("invalid password")
42 | }
43 |
44 | key, salt, err := db.FetchAccountKeySaltFromUsername(username)
45 | if err != nil {
46 | if err == sql.ErrNoRows {
47 | return response, fmt.Errorf("account doesn't exist")
48 | }
49 |
50 | return response, err
51 | }
52 |
53 | if !bytes.Equal(key, deriveArgon2IDKey([]byte(password), salt)) {
54 | return response, fmt.Errorf("password doesn't match")
55 | }
56 |
57 | token := make([]byte, TokenSize)
58 | _, err = rand.Read(token)
59 | if err != nil {
60 | return response, fmt.Errorf("failed to generate token: %s", err)
61 | }
62 |
63 | err = db.AddAccountSession(username, token)
64 | if err != nil {
65 | return response, fmt.Errorf("failed to add account session")
66 | }
67 |
68 | response.Token = base64.StdEncoding.EncodeToString(token)
69 |
70 | return response, nil
71 | }
72 |
--------------------------------------------------------------------------------
/api/savedata/update.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package savedata
19 |
20 | import (
21 | "fmt"
22 | "log"
23 |
24 | "github.com/pagefaultgames/rogueserver/db"
25 | "github.com/pagefaultgames/rogueserver/defs"
26 | )
27 |
28 | // /savedata/update - update save data
29 | func Update(uuid []byte, slot int, save any) error {
30 | err := db.UpdateAccountLastActivity(uuid)
31 | if err != nil {
32 | log.Print("failed to update account last activity")
33 | }
34 |
35 | switch save := save.(type) {
36 | case defs.SystemSaveData: // System
37 | if save.TrainerId == 0 && save.SecretId == 0 {
38 | return fmt.Errorf("invalid system data")
39 | }
40 |
41 | if save.GameVersion != "1.0.4" {
42 | return fmt.Errorf("client version out of date")
43 | }
44 |
45 | err = db.UpdateAccountStats(uuid, save.GameStats, save.VoucherCounts)
46 | if err != nil {
47 | return fmt.Errorf("failed to update account stats: %s", err)
48 | }
49 |
50 | err = db.DeleteClaimedAccountCompensations(uuid)
51 | if err != nil {
52 | return fmt.Errorf("failed to delete claimed compensations: %s", err)
53 | }
54 |
55 | return db.StoreSystemSaveData(uuid, save)
56 |
57 | case defs.SessionSaveData: // Session
58 | if slot < 0 || slot >= defs.SessionSlotCount {
59 | return fmt.Errorf("slot id %d out of range", slot)
60 | }
61 | return db.StoreSessionSaveData(uuid, save, slot)
62 |
63 | default:
64 | return fmt.Errorf("invalid data type")
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/api/savedata/clear.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package savedata
19 |
20 | import (
21 | "fmt"
22 | "log"
23 |
24 | "github.com/pagefaultgames/rogueserver/db"
25 | "github.com/pagefaultgames/rogueserver/defs"
26 | )
27 |
28 | type ClearResponse struct {
29 | Success bool `json:"success"`
30 | Error string `json:"error"`
31 | }
32 |
33 | // /savedata/clear - mark session save data as cleared and delete
34 | func Clear(uuid []byte, slot int, seed string, save defs.SessionSaveData) (ClearResponse, error) {
35 | var response ClearResponse
36 | err := db.UpdateAccountLastActivity(uuid)
37 | if err != nil {
38 | log.Print("failed to update account last activity")
39 | }
40 |
41 | if slot < 0 || slot >= defs.SessionSlotCount {
42 | return response, fmt.Errorf("slot id %d out of range", slot)
43 | }
44 |
45 | sessionCompleted := validateSessionCompleted(save)
46 |
47 | if save.GameMode == 3 && save.Seed == seed {
48 | waveCompleted := save.WaveIndex
49 | if !sessionCompleted {
50 | waveCompleted--
51 | }
52 |
53 | err = db.AddOrUpdateAccountDailyRun(uuid, save.Score, waveCompleted)
54 | if err != nil {
55 | log.Printf("failed to add or update daily run record: %s", err)
56 | }
57 | }
58 |
59 | if sessionCompleted {
60 | response.Success, err = db.TryAddSeedCompletion(uuid, save.Seed, int(save.GameMode))
61 | if err != nil {
62 | log.Printf("failed to mark seed as completed: %s", err)
63 | }
64 | }
65 |
66 | err = db.DeleteSessionSaveData(uuid, slot)
67 | if err != nil {
68 | log.Printf("failed to delete session save data: %s", err)
69 | }
70 |
71 | return response, nil
72 | }
73 |
--------------------------------------------------------------------------------
/db/legacy.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package db
19 |
20 | import (
21 | "encoding/gob"
22 | "encoding/hex"
23 | "fmt"
24 | "os"
25 | "strconv"
26 |
27 | "github.com/klauspost/compress/zstd"
28 | "github.com/pagefaultgames/rogueserver/defs"
29 | )
30 |
31 | func LegacyReadSystemSaveData(uuid []byte) (defs.SystemSaveData, error) {
32 | var system defs.SystemSaveData
33 |
34 | file, err := os.Open("userdata/" + hex.EncodeToString(uuid) + "/system.pzs")
35 | if err != nil {
36 | return system, fmt.Errorf("failed to open save file for reading: %s", err)
37 | }
38 |
39 | defer file.Close()
40 |
41 | zstdDecoder, err := zstd.NewReader(file)
42 | if err != nil {
43 | return system, fmt.Errorf("failed to create zstd decoder: %s", err)
44 | }
45 |
46 | defer zstdDecoder.Close()
47 |
48 | err = gob.NewDecoder(zstdDecoder).Decode(&system)
49 | if err != nil {
50 | return system, fmt.Errorf("failed to deserialize save: %s", err)
51 | }
52 |
53 | return system, nil
54 | }
55 |
56 | func LegacyReadSessionSaveData(uuid []byte, slotID int) (defs.SessionSaveData, error) {
57 | var session defs.SessionSaveData
58 |
59 | fileName := "session"
60 | if slotID != 0 {
61 | fileName += strconv.Itoa(slotID)
62 | }
63 |
64 | file, err := os.Open(fmt.Sprintf("userdata/%s/%s.pzs", hex.EncodeToString(uuid), fileName))
65 | if err != nil {
66 | return session, fmt.Errorf("failed to open save file for reading: %s", err)
67 | }
68 |
69 | defer file.Close()
70 |
71 | zstdDecoder, err := zstd.NewReader(file)
72 | if err != nil {
73 | return session, fmt.Errorf("failed to create zstd decoder: %s", err)
74 | }
75 |
76 | defer zstdDecoder.Close()
77 |
78 | err = gob.NewDecoder(zstdDecoder).Decode(&session)
79 | if err != nil {
80 | return session, fmt.Errorf("failed to deserialize save: %s", err)
81 | }
82 |
83 | return session, nil
84 | }
85 |
--------------------------------------------------------------------------------
/api/savedata/get.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package savedata
19 |
20 | import (
21 | "fmt"
22 | "strconv"
23 |
24 | "github.com/pagefaultgames/rogueserver/db"
25 | "github.com/pagefaultgames/rogueserver/defs"
26 | )
27 |
28 | // /savedata/get - get save data
29 | func Get(uuid []byte, datatype, slot int) (any, error) {
30 | switch datatype {
31 | case 0: // System
32 | if slot != 0 {
33 | return nil, fmt.Errorf("invalid slot id for system data")
34 | }
35 |
36 | system, err := db.ReadSystemSaveData(uuid)
37 | if err != nil {
38 | return nil, err
39 | }
40 |
41 | // TODO this should be a transaction
42 | compensations, err := db.FetchAndClaimAccountCompensations(uuid)
43 | if err != nil {
44 | return nil, fmt.Errorf("failed to fetch compensations: %s", err)
45 | }
46 |
47 | needsUpdate := false
48 | for compensationType, amount := range compensations {
49 | system.VoucherCounts[strconv.Itoa(compensationType)] += amount
50 | if amount > 0 {
51 | needsUpdate = true
52 | }
53 | }
54 |
55 | if needsUpdate {
56 | err = db.StoreSystemSaveData(uuid, system)
57 | if err != nil {
58 | return nil, fmt.Errorf("failed to update system save data: %s", err)
59 | }
60 | err = db.DeleteClaimedAccountCompensations(uuid)
61 | if err != nil {
62 | return nil, fmt.Errorf("failed to delete claimed compensations: %s", err)
63 | }
64 |
65 | err = db.UpdateAccountStats(uuid, system.GameStats, system.VoucherCounts)
66 | if err != nil {
67 | return nil, fmt.Errorf("failed to update account stats: %s", err)
68 | }
69 | }
70 |
71 | return system, nil
72 | case 1: // Session
73 | if slot < 0 || slot >= defs.SessionSlotCount {
74 | return nil, fmt.Errorf("slot id %d out of range", slot)
75 | }
76 |
77 | session, err := db.ReadSessionSaveData(uuid, slot)
78 | if err != nil {
79 | return nil, err
80 | }
81 |
82 | return session, nil
83 | default:
84 | return nil, fmt.Errorf("invalid data type")
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/api/daily/common.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package daily
19 |
20 | import (
21 | "crypto/md5"
22 | "crypto/rand"
23 | "encoding/base64"
24 | "encoding/binary"
25 | "fmt"
26 | "log"
27 | "os"
28 | "time"
29 |
30 | "github.com/pagefaultgames/rogueserver/db"
31 | "github.com/robfig/cron/v3"
32 | )
33 |
34 | const secondsPerDay = 60 * 60 * 24
35 |
36 | var (
37 | scheduler = cron.New(cron.WithLocation(time.UTC))
38 | secret []byte
39 | )
40 |
41 | func Init() error {
42 | var err error
43 |
44 | secret, err = os.ReadFile("secret.key")
45 | if err != nil {
46 | if !os.IsNotExist(err) {
47 | return fmt.Errorf("failed to read daily seed secret: %s", err)
48 | }
49 |
50 | newSecret := make([]byte, 32)
51 | _, err := rand.Read(newSecret)
52 | if err != nil {
53 | return fmt.Errorf("failed to generate daily seed secret: %s", err)
54 | }
55 |
56 | err = os.WriteFile("secret.key", newSecret, 0400)
57 | if err != nil {
58 | return fmt.Errorf("failed to write daily seed secret: %s", err)
59 | }
60 |
61 | secret = newSecret
62 | }
63 |
64 | seed, err := recordNewDaily()
65 | if err != nil {
66 | log.Print(err)
67 | }
68 |
69 | log.Printf("Daily Run Seed: %s", seed)
70 |
71 | _, err = scheduler.AddFunc("@daily", func() {
72 | time.Sleep(time.Second)
73 |
74 | seed, err = recordNewDaily()
75 | if err != nil {
76 | log.Printf("error while recording new daily: %s", err)
77 | } else {
78 | log.Printf("Daily Run Seed: %s", seed)
79 | }
80 | })
81 | if err != nil {
82 | return err
83 | }
84 |
85 | scheduler.Start()
86 |
87 | return nil
88 | }
89 |
90 | func Seed() string {
91 | return base64.StdEncoding.EncodeToString(deriveSeed(time.Now().UTC()))
92 | }
93 |
94 | func deriveSeed(seedTime time.Time) []byte {
95 | day := make([]byte, 8)
96 | binary.BigEndian.PutUint64(day, uint64(seedTime.Unix()/secondsPerDay))
97 |
98 | hashedSeed := md5.Sum(append(day, secret...))
99 |
100 | return hashedSeed[:]
101 | }
102 |
103 | func recordNewDaily() (string, error) {
104 | return db.TryAddDailyRun(Seed())
105 | }
106 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # rogueserver
2 |
3 | # Hosting in Docker
4 | It is advised that you host this in a docker container as it will be much easier to manage.
5 | There is a sample docker-compose file for setting up a docker container to setup this server.
6 |
7 | # Self Hosting outside of Docker:
8 | ## Required Tools:
9 | - Golang
10 | - Node: **18.3.0**
11 | - npm: [how to install](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)
12 |
13 | ## Installation:
14 | 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
15 |
16 | ### src/utils.ts:224-225 (in pokerogue)
17 | 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)
18 |
19 | # If you are on Windows
20 |
21 | Now that all of the files are configured: start up powershell as administrator:
22 | ```
23 | cd C:\api\server\location\
24 | go build .
25 | .\rogueserver.exe --debug --dbuser yourusername --dbpass yourpassword
26 | ```
27 | The other available flags are located in rogueserver.go:34-43.
28 |
29 | Then in another run this the first time then run `npm run start` from the rogueserver location from then on:
30 | ```
31 | powershell -ep bypass
32 | cd C:\server\location\
33 | npm install
34 | npm run start
35 | ```
36 | 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).
37 |
38 | # If you are on Linux
39 | In whatever shell you prefer, run the following:
40 | ```
41 | cd /api/server/location/
42 | go build .
43 | ./rogueserver --debug --dbuser yourusername --dbpass yourpassword &
44 |
45 | cd /server/location/
46 | npm run start
47 | ```
48 |
49 | 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).
50 | An example to allow incoming connections using UFW:
51 | ```
52 | sudo ufw allow 8000,8001/tcp
53 | ```
54 |
55 | This should allow you to reach the game from other computers on the same network.
56 |
57 | ## Tying to a Domain
58 |
59 | 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.
60 |
61 | I setup caddy and would recommend using it as a reverse proxy.
62 | [caddy installation](https://caddyserver.com/docs/install)
63 | once its installed setup a config file for caddy:
64 |
65 | ```
66 | pokerogue.exampledomain.com {
67 | reverse_proxy localhost:8000
68 | }
69 | pokeapi.exampledomain.com {
70 | reverse_proxy localhost:8001
71 | }
72 | ```
73 | Preferably set up caddy as a service from [here.](https://caddyserver.com/docs/running)
74 |
75 | Once this is good to go, take your API url (https://pokeapi.exampledomain.com) and paste it on
76 | ### src/utils.ts:224-225
77 | in place of the previous 0.0.0.0:8001 address
78 |
79 | Make sure that both 8000 and 8001 are portforwarded on your router.
80 |
81 | 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!
82 |
83 |
84 |
--------------------------------------------------------------------------------
/db/daily.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package db
19 |
20 | import (
21 | "math"
22 |
23 | "github.com/pagefaultgames/rogueserver/defs"
24 | )
25 |
26 | func TryAddDailyRun(seed string) (string, error) {
27 | var actualSeed string
28 | err := handle.QueryRow("INSERT INTO dailyRuns (seed, date) VALUES (?, UTC_DATE()) ON DUPLICATE KEY UPDATE date = date RETURNING seed", seed).Scan(&actualSeed)
29 | if err != nil {
30 | return "", err
31 | }
32 |
33 | return actualSeed, nil
34 | }
35 |
36 | func GetDailyRunSeed() (string, error) {
37 | var seed string
38 | err := handle.QueryRow("SELECT seed FROM dailyRuns WHERE date = UTC_DATE()").Scan(&seed)
39 | if err != nil {
40 | return "", err
41 | }
42 |
43 | return seed, nil
44 |
45 | }
46 |
47 | func AddOrUpdateAccountDailyRun(uuid []byte, score int, wave int) error {
48 | _, err := handle.Exec("INSERT INTO accountDailyRuns (uuid, date, score, wave, timestamp) VALUES (?, UTC_DATE(), ?, ?, UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE score = GREATEST(score, ?), wave = GREATEST(wave, ?), timestamp = IF(score < ?, UTC_TIMESTAMP(), timestamp)", uuid, score, wave, score, wave, score)
49 | if err != nil {
50 | return err
51 | }
52 |
53 | return nil
54 | }
55 |
56 | func FetchRankings(category int, page int) ([]defs.DailyRanking, error) {
57 | var rankings []defs.DailyRanking
58 |
59 | offset := (page - 1) * 10
60 |
61 | var query string
62 | switch category {
63 | case 0:
64 | query = "SELECT RANK() OVER (ORDER BY adr.score DESC, adr.timestamp), a.username, adr.score, adr.wave FROM accountDailyRuns adr JOIN dailyRuns dr ON dr.date = adr.date JOIN accounts a ON adr.uuid = a.uuid WHERE dr.date = UTC_DATE() AND a.banned = 0 LIMIT 10 OFFSET ?"
65 | case 1:
66 | query = "SELECT RANK() OVER (ORDER BY SUM(adr.score) DESC, adr.timestamp), a.username, SUM(adr.score), 0 FROM accountDailyRuns adr JOIN dailyRuns dr ON dr.date = adr.date JOIN accounts a ON adr.uuid = a.uuid WHERE dr.date >= DATE_SUB(DATE(UTC_TIMESTAMP()), INTERVAL DAYOFWEEK(UTC_TIMESTAMP()) - 1 DAY) AND a.banned = 0 GROUP BY a.username ORDER BY 1 LIMIT 10 OFFSET ?"
67 | }
68 |
69 | results, err := handle.Query(query, offset)
70 | if err != nil {
71 | return rankings, err
72 | }
73 |
74 | defer results.Close()
75 |
76 | for results.Next() {
77 | var ranking defs.DailyRanking
78 | err = results.Scan(&ranking.Rank, &ranking.Username, &ranking.Score, &ranking.Wave)
79 | if err != nil {
80 | return rankings, err
81 | }
82 |
83 | rankings = append(rankings, ranking)
84 | }
85 |
86 | return rankings, nil
87 | }
88 |
89 | func FetchRankingPageCount(category int) (int, error) {
90 | var query string
91 | switch category {
92 | case 0:
93 | query = "SELECT COUNT(a.username) FROM accountDailyRuns adr JOIN dailyRuns dr ON dr.date = adr.date JOIN accounts a ON adr.uuid = a.uuid WHERE dr.date = UTC_DATE()"
94 | case 1:
95 | query = "SELECT COUNT(DISTINCT a.username) FROM accountDailyRuns adr JOIN dailyRuns dr ON dr.date = adr.date JOIN accounts a ON adr.uuid = a.uuid WHERE dr.date >= DATE_SUB(DATE(UTC_TIMESTAMP()), INTERVAL DAYOFWEEK(UTC_TIMESTAMP()) - 1 DAY)"
96 | }
97 |
98 | var recordCount int
99 | err := handle.QueryRow(query).Scan(&recordCount)
100 | if err != nil {
101 | return 0, err
102 | }
103 |
104 | return int(math.Ceil(float64(recordCount) / 10)), nil
105 | }
106 |
--------------------------------------------------------------------------------
/rogueserver.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package main
19 |
20 | import (
21 | "encoding/gob"
22 | "flag"
23 | "log"
24 | "net"
25 | "net/http"
26 | "os"
27 |
28 | "github.com/pagefaultgames/rogueserver/api"
29 | "github.com/pagefaultgames/rogueserver/db"
30 | )
31 |
32 | func main() {
33 | // flag stuff
34 | debug := flag.Bool("debug", false, "use debug mode")
35 |
36 | proto := flag.String("proto", "tcp", "protocol for api to use (tcp, unix)")
37 | addr := flag.String("addr", "0.0.0.0:8001", "network address for api to listen on")
38 | tlscert := flag.String("tlscert", "", "tls certificate path")
39 | tlskey := flag.String("tlskey", "", "tls key path")
40 |
41 | dbuser := flag.String("dbuser", "pokerogue", "database username")
42 | dbpass := flag.String("dbpass", "pokerogue", "database password")
43 | dbproto := flag.String("dbproto", "tcp", "protocol for database connection")
44 | dbaddr := flag.String("dbaddr", "localhost", "database address")
45 | dbname := flag.String("dbname", "pokeroguedb", "database name")
46 |
47 | flag.Parse()
48 |
49 | // register gob types
50 | gob.Register([]interface{}{})
51 | gob.Register(map[string]interface{}{})
52 |
53 | // get database connection
54 | err := db.Init(*dbuser, *dbpass, *dbproto, *dbaddr, *dbname)
55 | if err != nil {
56 | log.Fatalf("failed to initialize database: %s", err)
57 | }
58 |
59 | // create listener
60 | listener, err := createListener(*proto, *addr)
61 | if err != nil {
62 | log.Fatalf("failed to create net listener: %s", err)
63 | }
64 |
65 | mux := http.NewServeMux()
66 |
67 | // init api
68 | if err := api.Init(mux); err != nil {
69 | log.Fatal(err)
70 | }
71 |
72 | // start web server
73 | handler := prodHandler(mux)
74 | if *debug {
75 | handler = debugHandler(mux)
76 | }
77 |
78 | if *tlscert == "" {
79 | err = http.Serve(listener, handler)
80 | } else {
81 | err = http.ServeTLS(listener, handler, *tlscert, *tlskey)
82 | }
83 | if err != nil {
84 | log.Fatalf("failed to create http server or server errored: %s", err)
85 | }
86 | }
87 |
88 | func createListener(proto, addr string) (net.Listener, error) {
89 | if proto == "unix" {
90 | os.Remove(addr)
91 | }
92 |
93 | listener, err := net.Listen(proto, addr)
94 | if err != nil {
95 | return nil, err
96 | }
97 |
98 | if proto == "unix" {
99 | if err := os.Chmod(addr, 0777); err != nil {
100 | listener.Close()
101 | return nil, err
102 | }
103 | }
104 |
105 | return listener, nil
106 | }
107 |
108 | func prodHandler(router *http.ServeMux) http.Handler {
109 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
110 | w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
111 | w.Header().Set("Access-Control-Allow-Methods", "OPTIONS, GET, POST")
112 | w.Header().Set("Access-Control-Allow-Origin", "https://pokerogue.net")
113 |
114 | if r.Method == "OPTIONS" {
115 | w.WriteHeader(http.StatusOK)
116 | return
117 | }
118 |
119 | router.ServeHTTP(w, r)
120 | })
121 | }
122 |
123 | func debugHandler(router *http.ServeMux) http.Handler {
124 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
125 | w.Header().Set("Access-Control-Allow-Headers", "*")
126 | w.Header().Set("Access-Control-Allow-Methods", "*")
127 | w.Header().Set("Access-Control-Allow-Origin", "*")
128 |
129 | if r.Method == "OPTIONS" {
130 | w.WriteHeader(http.StatusOK)
131 | return
132 | }
133 |
134 | router.ServeHTTP(w, r)
135 | })
136 | }
137 |
--------------------------------------------------------------------------------
/api/common.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package api
19 |
20 | import (
21 | "encoding/base64"
22 | "encoding/json"
23 | "fmt"
24 | "github.com/pagefaultgames/rogueserver/api/account"
25 | "github.com/pagefaultgames/rogueserver/api/daily"
26 | "github.com/pagefaultgames/rogueserver/db"
27 | "log"
28 | "net/http"
29 | )
30 |
31 | func Init(mux *http.ServeMux) error {
32 | if err := scheduleStatRefresh(); err != nil {
33 | return err
34 | }
35 | if err := daily.Init(); err != nil {
36 | return err
37 | }
38 |
39 | // account
40 | mux.HandleFunc("GET /account/info", handleAccountInfo)
41 | mux.HandleFunc("POST /account/register", handleAccountRegister)
42 | mux.HandleFunc("POST /account/login", handleAccountLogin)
43 | mux.HandleFunc("POST /account/changepw", handleAccountChangePW)
44 | mux.HandleFunc("GET /account/logout", handleAccountLogout)
45 |
46 | // game
47 | mux.HandleFunc("GET /game/titlestats", handleGameTitleStats)
48 | mux.HandleFunc("GET /game/classicsessioncount", handleGameClassicSessionCount)
49 |
50 | // savedata
51 | mux.HandleFunc("GET /savedata/get", legacyHandleGetSaveData)
52 | mux.HandleFunc("POST /savedata/update", legacyHandleSaveData)
53 | mux.HandleFunc("GET /savedata/delete", legacyHandleSaveData) // TODO use deleteSystemSave
54 | mux.HandleFunc("POST /savedata/clear", legacyHandleSaveData) // TODO use clearSessionData
55 | mux.HandleFunc("GET /savedata/newclear", legacyHandleNewClear)
56 |
57 | // new session
58 | mux.HandleFunc("POST /savedata/updateall", handleUpdateAll)
59 | mux.HandleFunc("POST /savedata/system/verify", handleSystemVerify)
60 | mux.HandleFunc("GET /savedata/system", handleGetSystemData)
61 | mux.HandleFunc("GET /savedata/session", handleGetSessionData)
62 |
63 | // daily
64 | mux.HandleFunc("GET /daily/seed", handleDailySeed)
65 | mux.HandleFunc("GET /daily/rankings", handleDailyRankings)
66 | mux.HandleFunc("GET /daily/rankingpagecount", handleDailyRankingPageCount)
67 | return nil
68 | }
69 |
70 | func tokenFromRequest(r *http.Request) ([]byte, error) {
71 | if r.Header.Get("Authorization") == "" {
72 | return nil, fmt.Errorf("missing token")
73 | }
74 |
75 | token, err := base64.StdEncoding.DecodeString(r.Header.Get("Authorization"))
76 | if err != nil {
77 | return nil, fmt.Errorf("failed to decode token: %s", err)
78 | }
79 |
80 | if len(token) != account.TokenSize {
81 | return nil, fmt.Errorf("invalid token length: got %d, expected %d", len(token), account.TokenSize)
82 | }
83 |
84 | return token, nil
85 | }
86 |
87 | func uuidFromRequest(r *http.Request) ([]byte, error) {
88 | _, uuid, err := tokenAndUuidFromRequest(r)
89 | return uuid, err
90 | }
91 |
92 | func tokenAndUuidFromRequest(r *http.Request) ([]byte, []byte, error) {
93 | token, err := tokenFromRequest(r)
94 | if err != nil {
95 | return nil, nil, err
96 | }
97 |
98 | uuid, err := db.FetchUUIDFromToken(token)
99 | if err != nil {
100 | return nil, nil, fmt.Errorf("failed to validate token: %s", err)
101 | }
102 |
103 | return token, uuid, nil
104 | }
105 |
106 | func httpError(w http.ResponseWriter, r *http.Request, err error, code int) {
107 | log.Printf("%s: %s\n", r.URL.Path, err)
108 | http.Error(w, err.Error(), code)
109 | }
110 |
111 | func jsonResponse(w http.ResponseWriter, r *http.Request, data any) {
112 | w.Header().Set("Content-Type", "application/json")
113 | err := json.NewEncoder(w).Encode(data)
114 | if err != nil {
115 | httpError(w, r, fmt.Errorf("failed to encode response json: %s", err), http.StatusInternalServerError)
116 | return
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/db/savedata.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package db
19 |
20 | import (
21 | "bytes"
22 | "encoding/gob"
23 |
24 | "github.com/pagefaultgames/rogueserver/defs"
25 | )
26 |
27 | func TryAddSeedCompletion(uuid []byte, seed string, mode int) (bool, error) {
28 | var count int
29 | err := handle.QueryRow("SELECT COUNT(*) FROM dailyRunCompletions WHERE uuid = ? AND seed = ?", uuid, seed).Scan(&count)
30 | if err != nil {
31 | return false, err
32 | } else if count > 0 {
33 | return false, nil
34 | }
35 |
36 | _, err = handle.Exec("INSERT INTO dailyRunCompletions (uuid, seed, mode, timestamp) VALUES (?, ?, ?, UTC_TIMESTAMP())", uuid, seed, mode)
37 | if err != nil {
38 | return false, err
39 | }
40 |
41 | return true, nil
42 | }
43 |
44 | func ReadSeedCompleted(uuid []byte, seed string) (bool, error) {
45 | var count int
46 | err := handle.QueryRow("SELECT COUNT(*) FROM dailyRunCompletions WHERE uuid = ? AND seed = ?", uuid, seed).Scan(&count)
47 | if err != nil {
48 | return false, err
49 | }
50 |
51 | return count > 0, nil
52 | }
53 |
54 | func ReadSystemSaveData(uuid []byte) (defs.SystemSaveData, error) {
55 | var system defs.SystemSaveData
56 |
57 | var data []byte
58 | err := handle.QueryRow("SELECT data FROM systemSaveData WHERE uuid = ?", uuid).Scan(&data)
59 | if err != nil {
60 | return system, err
61 | }
62 |
63 | err = gob.NewDecoder(bytes.NewReader(data)).Decode(&system)
64 | if err != nil {
65 | return system, err
66 | }
67 |
68 | return system, nil
69 | }
70 |
71 | func StoreSystemSaveData(uuid []byte, data defs.SystemSaveData) error {
72 | var buf bytes.Buffer
73 | err := gob.NewEncoder(&buf).Encode(data)
74 | if err != nil {
75 | return err
76 | }
77 |
78 | _, err = handle.Exec("INSERT INTO systemSaveData (uuid, data, timestamp) VALUES (?, ?, UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE data = ?, timestamp = UTC_TIMESTAMP()", uuid, buf.Bytes(), buf.Bytes())
79 | if err != nil {
80 | return err
81 | }
82 |
83 | return nil
84 | }
85 |
86 | func DeleteSystemSaveData(uuid []byte) error {
87 | _, err := handle.Exec("DELETE FROM systemSaveData WHERE uuid = ?", uuid)
88 | if err != nil {
89 | return err
90 | }
91 |
92 | return nil
93 | }
94 |
95 | func ReadSessionSaveData(uuid []byte, slot int) (defs.SessionSaveData, error) {
96 | var session defs.SessionSaveData
97 |
98 | var data []byte
99 | err := handle.QueryRow("SELECT data FROM sessionSaveData WHERE uuid = ? AND slot = ?", uuid, slot).Scan(&data)
100 | if err != nil {
101 | return session, err
102 | }
103 |
104 | err = gob.NewDecoder(bytes.NewReader(data)).Decode(&session)
105 | if err != nil {
106 | return session, err
107 | }
108 |
109 | return session, nil
110 | }
111 |
112 | func GetLatestSessionSaveDataSlot(uuid []byte) (int, error) {
113 | var slot int
114 | err := handle.QueryRow("SELECT slot FROM sessionSaveData WHERE uuid = ? ORDER BY timestamp DESC, slot ASC LIMIT 1", uuid).Scan(&slot)
115 | if err != nil {
116 | return -1, err
117 | }
118 |
119 | return slot, nil
120 | }
121 |
122 | func StoreSessionSaveData(uuid []byte, data defs.SessionSaveData, slot int) error {
123 | var buf bytes.Buffer
124 | err := gob.NewEncoder(&buf).Encode(data)
125 | if err != nil {
126 | return err
127 | }
128 |
129 | _, err = handle.Exec("INSERT INTO sessionSaveData (uuid, slot, data, timestamp) VALUES (?, ?, ?, UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE data = ?, timestamp = UTC_TIMESTAMP()", uuid, slot, buf.Bytes(), buf.Bytes())
130 | if err != nil {
131 | return err
132 | }
133 |
134 | return nil
135 | }
136 |
137 | func DeleteSessionSaveData(uuid []byte, slot int) error {
138 | _, err := handle.Exec("DELETE FROM sessionSaveData WHERE uuid = ? AND slot = ?", uuid, slot)
139 | if err != nil {
140 | return err
141 | }
142 |
143 | return nil
144 | }
145 |
--------------------------------------------------------------------------------
/defs/savedata.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package defs
19 |
20 | const SessionSlotCount = 5
21 |
22 | type SystemSaveData struct {
23 | TrainerId int `json:"trainerId"`
24 | SecretId int `json:"secretId"`
25 | Gender int `json:"gender"`
26 | DexData DexData `json:"dexData"`
27 | StarterData StarterData `json:"starterData"`
28 | StarterMoveData StarterMoveData `json:"starterMoveData"` // Legacy
29 | StarterEggMoveData StarterEggMoveData `json:"starterEggMoveData"` // Legacy
30 | GameStats GameStats `json:"gameStats"`
31 | Unlocks Unlocks `json:"unlocks"`
32 | AchvUnlocks AchvUnlocks `json:"achvUnlocks"`
33 | VoucherUnlocks VoucherUnlocks `json:"voucherUnlocks"`
34 | VoucherCounts VoucherCounts `json:"voucherCounts"`
35 | Eggs []EggData `json:"eggs"`
36 | GameVersion string `json:"gameVersion"`
37 | Timestamp int `json:"timestamp"`
38 | }
39 |
40 | type DexData map[int]DexEntry
41 |
42 | type DexEntry struct {
43 | SeenAttr interface{} `json:"seenAttr"` // integer or string
44 | CaughtAttr interface{} `json:"caughtAttr"` // integer or string
45 | NatureAttr int `json:"natureAttr"`
46 | SeenCount int `json:"seenCount"`
47 | CaughtCount int `json:"caughtCount"`
48 | HatchedCount int `json:"hatchedCount"`
49 | Ivs []int `json:"ivs"`
50 | }
51 |
52 | type StarterData map[int]StarterEntry
53 |
54 | type StarterEntry struct {
55 | Moveset interface{} `json:"moveset"`
56 | EggMoves int `json:"eggMoves"`
57 | CandyCount int `json:"candyCount"`
58 | Friendship int `json:"friendship"`
59 | AbilityAttr int `json:"abilityAttr"`
60 | PassiveAttr int `json:"passiveAttr"`
61 | ValueReduction int `json:"valueReduction"`
62 | ClassicWinCount int `json:"classicWinCount"`
63 | }
64 |
65 | type StarterMoveData map[int]interface{}
66 |
67 | type StarterEggMoveData map[int]int
68 |
69 | type GameStats interface{}
70 |
71 | type Unlocks map[int]bool
72 |
73 | type AchvUnlocks map[string]int
74 |
75 | type VoucherUnlocks map[string]int
76 |
77 | type VoucherCounts map[string]int
78 |
79 | type EggData struct {
80 | Id int `json:"id"`
81 | GachaType GachaType `json:"gachaType"`
82 | HatchWaves int `json:"hatchWaves"`
83 | Timestamp int `json:"timestamp"`
84 | }
85 |
86 | type GachaType int
87 |
88 | type SessionSaveData struct {
89 | Seed string `json:"seed"`
90 | PlayTime int `json:"playTime"`
91 | GameMode GameMode `json:"gameMode"`
92 | Party []PokemonData `json:"party"`
93 | EnemyParty []PokemonData `json:"enemyParty"`
94 | Modifiers []PersistentModifierData `json:"modifiers"`
95 | EnemyModifiers []PersistentModifierData `json:"enemyModifiers"`
96 | Arena ArenaData `json:"arena"`
97 | PokeballCounts PokeballCounts `json:"pokeballCounts"`
98 | Money int `json:"money"`
99 | Score int `json:"score"`
100 | VictoryCount int `json:"victoryCount"`
101 | FaintCount int `json:"faintCount"`
102 | ReviveCount int `json:"reviveCount"`
103 | WaveIndex int `json:"waveIndex"`
104 | BattleType BattleType `json:"battleType"`
105 | Trainer TrainerData `json:"trainer"`
106 | GameVersion string `json:"gameVersion"`
107 | Timestamp int `json:"timestamp"`
108 | }
109 |
110 | type GameMode int
111 |
112 | type PokemonData interface{}
113 |
114 | type PersistentModifierData interface{}
115 |
116 | type ArenaData interface{}
117 |
118 | type PokeballCounts map[string]int
119 |
120 | type BattleType int
121 |
122 | type TrainerData interface{}
123 |
124 | type SessionHistoryData struct {
125 | Seed string `json:"seed"`
126 | PlayTime int `json:"playTime"`
127 | Result SessionHistoryResult `json:"sessionHistoryResult"`
128 | GameMode GameMode `json:"gameMode"`
129 | Party []PokemonData `json:"party"`
130 | Modifiers []PersistentModifierData `json:"modifiers"`
131 | Money int `json:"money"`
132 | Score int `json:"score"`
133 | WaveIndex int `json:"waveIndex"`
134 | BattleType BattleType `json:"battleType"`
135 | GameVersion string `json:"gameVersion"`
136 | Timestamp int `json:"timestamp"`
137 | }
138 |
139 | type SessionHistoryResult int
140 |
--------------------------------------------------------------------------------
/db/account.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package db
19 |
20 | import (
21 | "database/sql"
22 | "errors"
23 | "fmt"
24 | "slices"
25 |
26 | _ "github.com/go-sql-driver/mysql"
27 | "github.com/pagefaultgames/rogueserver/defs"
28 | )
29 |
30 | func AddAccountRecord(uuid []byte, username string, key, salt []byte) error {
31 | _, err := handle.Exec("INSERT INTO accounts (uuid, username, hash, salt, registered) VALUES (?, ?, ?, ?, UTC_TIMESTAMP())", uuid, username, key, salt)
32 | if err != nil {
33 | return err
34 | }
35 |
36 | return nil
37 | }
38 |
39 | func AddAccountSession(username string, token []byte) error {
40 | _, err := handle.Exec("INSERT INTO sessions (uuid, token, expire) SELECT a.uuid, ?, DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 WEEK) FROM accounts a WHERE a.username = ?", token, username)
41 | if err != nil {
42 | return err
43 | }
44 |
45 | _, err = handle.Exec("UPDATE accounts SET lastLoggedIn = UTC_TIMESTAMP() WHERE username = ?", username)
46 | if err != nil {
47 | return err
48 | }
49 |
50 | return nil
51 | }
52 |
53 | func UpdateAccountPassword(uuid, key, salt []byte) error {
54 | _, err := handle.Exec("UPDATE accounts SET (hash, salt) VALUES (?, ?) WHERE uuid = ?", key, salt, uuid)
55 | if err != nil {
56 | return err
57 | }
58 |
59 | return nil
60 | }
61 |
62 | func UpdateAccountLastActivity(uuid []byte) error {
63 | _, err := handle.Exec("UPDATE accounts SET lastActivity = UTC_TIMESTAMP() WHERE uuid = ?", uuid)
64 | if err != nil {
65 | return err
66 | }
67 |
68 | return nil
69 | }
70 |
71 | func UpdateAccountStats(uuid []byte, stats defs.GameStats, voucherCounts map[string]int) error {
72 | var columns = []string{"playTime", "battles", "classicSessionsPlayed", "sessionsWon", "highestEndlessWave", "highestLevel", "pokemonSeen", "pokemonDefeated", "pokemonCaught", "pokemonHatched", "eggsPulled", "regularVouchers", "plusVouchers", "premiumVouchers", "goldenVouchers"}
73 |
74 | var statCols []string
75 | var statValues []interface{}
76 |
77 | m, ok := stats.(map[string]interface{})
78 | if !ok {
79 | return fmt.Errorf("expected map[string]interface{}, got %T", stats)
80 | }
81 |
82 | for k, v := range m {
83 | value, ok := v.(float64)
84 | if !ok {
85 | return fmt.Errorf("expected float64, got %T", v)
86 | }
87 |
88 | if slices.Contains(columns, k) {
89 | statCols = append(statCols, k)
90 | statValues = append(statValues, value)
91 | }
92 | }
93 |
94 | for k, v := range voucherCounts {
95 | var column string
96 | switch k {
97 | case "0":
98 | column = "regularVouchers"
99 | case "1":
100 | column = "plusVouchers"
101 | case "2":
102 | column = "premiumVouchers"
103 | case "3":
104 | column = "goldenVouchers"
105 | default:
106 | continue
107 | }
108 | statCols = append(statCols, column)
109 | statValues = append(statValues, v)
110 | }
111 |
112 | var statArgs []interface{}
113 | statArgs = append(statArgs, uuid)
114 | for range 2 {
115 | statArgs = append(statArgs, statValues...)
116 | }
117 |
118 | query := "INSERT INTO accountStats (uuid"
119 |
120 | for _, col := range statCols {
121 | query += ", " + col
122 | }
123 |
124 | query += ") VALUES (?"
125 |
126 | for range len(statCols) {
127 | query += ", ?"
128 | }
129 |
130 | query += ") ON DUPLICATE KEY UPDATE "
131 |
132 | for i, col := range statCols {
133 | if i > 0 {
134 | query += ", "
135 | }
136 |
137 | query += col + " = ?"
138 | }
139 |
140 | _, err := handle.Exec(query, statArgs...)
141 | if err != nil {
142 | return err
143 | }
144 |
145 | return nil
146 | }
147 |
148 | func FetchAndClaimAccountCompensations(uuid []byte) (map[int]int, error) {
149 | var compensations = make(map[int]int)
150 |
151 | results, err := handle.Query("SELECT voucherType, count FROM accountCompensations WHERE uuid = ?", uuid)
152 | if err != nil {
153 | return nil, err
154 | }
155 |
156 | defer results.Close()
157 |
158 | for results.Next() {
159 | var voucherType int
160 | var count int
161 | err := results.Scan(&voucherType, &count)
162 | if err != nil {
163 | return compensations, err
164 | }
165 | compensations[voucherType] = count
166 | }
167 |
168 | _, err = handle.Exec("UPDATE accountCompensations SET claimed = 1 WHERE uuid = ?", uuid)
169 | if err != nil {
170 | return compensations, err
171 | }
172 |
173 | return compensations, nil
174 | }
175 |
176 | func DeleteClaimedAccountCompensations(uuid []byte) error {
177 | _, err := handle.Exec("DELETE FROM accountCompensations WHERE uuid = ? AND claimed = 1", uuid)
178 | if err != nil {
179 | return err
180 | }
181 |
182 | return nil
183 | }
184 |
185 | func FetchAccountKeySaltFromUsername(username string) ([]byte, []byte, error) {
186 | var key, salt []byte
187 | err := handle.QueryRow("SELECT hash, salt FROM accounts WHERE username = ?", username).Scan(&key, &salt)
188 | if err != nil {
189 | return nil, nil, err
190 | }
191 |
192 | return key, salt, nil
193 | }
194 |
195 | func FetchTrainerIds(uuid []byte) (trainerId, secretId int, err error) {
196 | err = handle.QueryRow("SELECT trainerId, secretId FROM accounts WHERE uuid = ?", uuid).Scan(&trainerId, &secretId)
197 | if err != nil {
198 | return 0, 0, err
199 | }
200 |
201 | return trainerId, secretId, nil
202 | }
203 |
204 | func UpdateTrainerIds(trainerId, secretId int, uuid []byte) error {
205 | _, err := handle.Exec("UPDATE accounts SET trainerId = ?, secretId = ? WHERE uuid = ?", trainerId, secretId, uuid)
206 | if err != nil {
207 | return err
208 | }
209 |
210 | return nil
211 | }
212 |
213 | func IsActiveSession(uuid []byte, clientSessionId string) (bool, error) {
214 | var storedId string
215 | err := handle.QueryRow("SELECT clientSessionId FROM activeClientSessions WHERE uuid = ?", uuid).Scan(&storedId)
216 | if err != nil {
217 | if errors.Is(err, sql.ErrNoRows) {
218 | err = UpdateActiveSession(uuid, clientSessionId)
219 | if err != nil {
220 | return false, err
221 | }
222 | return true, nil
223 | }
224 | return false, err
225 | }
226 |
227 | return storedId == "" || storedId == clientSessionId, nil
228 | }
229 |
230 | func UpdateActiveSession(uuid []byte, clientSessionId string) error {
231 | _, err := handle.Exec("REPLACE INTO activeClientSessions VALUES (?, ?)", uuid, clientSessionId)
232 | if err != nil {
233 | return err
234 | }
235 |
236 | return nil
237 | }
238 |
239 | func FetchUUIDFromToken(token []byte) ([]byte, error) {
240 | var uuid []byte
241 | err := handle.QueryRow("SELECT uuid FROM sessions WHERE token = ?", token).Scan(&uuid)
242 | if err != nil {
243 | return nil, err
244 | }
245 |
246 | return uuid, nil
247 | }
248 |
249 | func RemoveSessionFromToken(token []byte) error {
250 | _, err := handle.Exec("DELETE FROM sessions WHERE token = ?", token)
251 | if err != nil {
252 | return err
253 | }
254 |
255 | return nil
256 | }
257 |
258 | func FetchUsernameFromUUID(uuid []byte) (string, error) {
259 | var username string
260 | err := handle.QueryRow("SELECT username FROM accounts WHERE uuid = ?", uuid).Scan(&username)
261 | if err != nil {
262 | return "", err
263 | }
264 |
265 | return username, nil
266 | }
267 |
--------------------------------------------------------------------------------
/db/db.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package db
19 |
20 | import (
21 | "database/sql"
22 | "encoding/hex"
23 | "fmt"
24 | "log"
25 | "os"
26 | "time"
27 |
28 | _ "github.com/go-sql-driver/mysql"
29 | )
30 |
31 | var handle *sql.DB
32 |
33 | func Init(username, password, protocol, address, database string) error {
34 | var err error
35 |
36 | handle, err = sql.Open("mysql", username+":"+password+"@"+protocol+"("+address+")/"+database)
37 | if err != nil {
38 | return fmt.Errorf("failed to open database connection: %s", err)
39 | }
40 |
41 | conns := 1024
42 | if protocol != "unix" {
43 | conns = 256
44 | }
45 |
46 | handle.SetMaxOpenConns(conns)
47 | handle.SetMaxIdleConns(conns / 4)
48 |
49 | handle.SetConnMaxIdleTime(time.Second * 10)
50 |
51 | tx, err := handle.Begin()
52 | if err != nil {
53 | log.Fatal(err)
54 | }
55 |
56 | err = setupDb(tx)
57 | if err != nil {
58 | _ = tx.Rollback()
59 | log.Fatal(err)
60 | }
61 |
62 | err = tx.Commit()
63 | if err != nil {
64 | log.Fatal(err)
65 | }
66 |
67 | // TODO temp code
68 | _, err = os.Stat("userdata")
69 | if err != nil {
70 | if !os.IsNotExist(err) { // not found, do not migrate
71 | log.Fatalf("failed to stat userdata directory: %s", err)
72 | }
73 |
74 | return nil
75 | }
76 |
77 | entries, err := os.ReadDir("userdata")
78 | if err != nil {
79 | log.Fatal(err)
80 | }
81 |
82 | for _, entry := range entries {
83 | if !entry.IsDir() {
84 | continue
85 | }
86 |
87 | uuidString := entry.Name()
88 | uuid, err := hex.DecodeString(uuidString)
89 | if err != nil {
90 | log.Printf("failed to decode uuid: %s", err)
91 | continue
92 | }
93 |
94 | var count int
95 | err = handle.QueryRow("SELECT COUNT(*) FROM systemSaveData WHERE uuid = ?", uuid).Scan(&count)
96 | if err != nil || count != 0 {
97 | continue
98 | }
99 |
100 | // store new system data
101 | systemData, err := LegacyReadSystemSaveData(uuid)
102 | if err != nil {
103 | log.Printf("failed to read system save data for %v: %s", uuidString, err)
104 | continue
105 | }
106 |
107 | err = StoreSystemSaveData(uuid, systemData)
108 | if err != nil {
109 | log.Fatalf("failed to store system save data for %v: %s\n", uuidString, err)
110 | }
111 |
112 | // delete old system data
113 | err = os.Remove("userdata/" + uuidString + "/system.pzs")
114 | if err != nil {
115 | log.Fatalf("failed to remove legacy system save data for %v: %s", uuidString, err)
116 | }
117 |
118 | for i := 0; i < 5; i++ {
119 | sessionData, err := LegacyReadSessionSaveData(uuid, i)
120 | if err != nil {
121 | log.Printf("failed to read session save data %v for %v: %s", i, uuidString, err)
122 | continue
123 | }
124 |
125 | // store new session data
126 | err = StoreSessionSaveData(uuid, sessionData, i)
127 | if err != nil {
128 | log.Fatalf("failed to store session save data for %v: %s\n", uuidString, err)
129 | }
130 |
131 | // delete old session data
132 | filename := "session"
133 | if i != 0 {
134 | filename += fmt.Sprintf("%d", i)
135 | }
136 | err = os.Remove(fmt.Sprintf("userdata/%s/%s.pzs", uuidString, filename))
137 | if err != nil {
138 | log.Fatalf("failed to remove legacy session save data %v for %v: %s", i, uuidString, err)
139 | }
140 | }
141 | }
142 |
143 | return nil
144 | }
145 |
146 | func setupDb(tx *sql.Tx) error {
147 | queries := []string{
148 | // MIGRATION 000
149 |
150 | `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)`,
151 | `CREATE INDEX IF NOT EXISTS accountsByActivity ON accounts (lastActivity)`,
152 |
153 | `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)`,
154 | `CREATE INDEX IF NOT EXISTS sessionsByUuid ON sessions (uuid)`,
155 |
156 | `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)`,
157 |
158 | `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)`,
159 | `CREATE INDEX IF NOT EXISTS accountCompensationsByUuid ON accountCompensations (uuid)`,
160 |
161 | `CREATE TABLE IF NOT EXISTS dailyRuns (date DATE NOT NULL PRIMARY KEY, seed CHAR(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL)`,
162 | `CREATE INDEX IF NOT EXISTS dailyRunsByDateAndSeed ON dailyRuns (date, seed)`,
163 |
164 | `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)`,
165 | `CREATE INDEX IF NOT EXISTS dailyRunCompletionsByUuidAndSeed ON dailyRunCompletions (uuid, seed)`,
166 |
167 | `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)`,
168 | `CREATE INDEX IF NOT EXISTS accountDailyRunsByDate ON accountDailyRuns (date)`,
169 |
170 | `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)`,
171 |
172 | `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)`,
173 |
174 | // ----------------------------------
175 | // MIGRATION 001
176 |
177 | `ALTER TABLE sessions DROP COLUMN IF EXISTS active`,
178 | `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)`,
179 | }
180 |
181 | for _, q := range queries {
182 | _, err := tx.Exec(q)
183 | if err != nil {
184 | return fmt.Errorf("failed to execute query: %w, query: %s", err, q)
185 | }
186 | }
187 | return nil
188 | }
189 |
--------------------------------------------------------------------------------
/api/endpoints.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (C) 2024 Pagefault Games
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU Affero General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU Affero General Public License for more details.
13 |
14 | You should have received a copy of the GNU Affero General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | package api
19 |
20 | import (
21 | "database/sql"
22 | "encoding/json"
23 | "errors"
24 | "fmt"
25 | "net/http"
26 | "strconv"
27 |
28 | "github.com/pagefaultgames/rogueserver/api/account"
29 | "github.com/pagefaultgames/rogueserver/api/daily"
30 | "github.com/pagefaultgames/rogueserver/api/savedata"
31 | "github.com/pagefaultgames/rogueserver/db"
32 | "github.com/pagefaultgames/rogueserver/defs"
33 | )
34 |
35 | /*
36 | The caller of endpoint handler functions are responsible for extracting the necessary data from the request.
37 | Handler functions are responsible for checking the validity of this data and returning a result or error.
38 | Handlers should not return serialized JSON, instead return the struct itself.
39 | */
40 |
41 | // account
42 |
43 | func handleAccountInfo(w http.ResponseWriter, r *http.Request) {
44 | uuid, err := uuidFromRequest(r)
45 | if err != nil {
46 | httpError(w, r, err, http.StatusBadRequest)
47 | return
48 | }
49 |
50 | username, err := db.FetchUsernameFromUUID(uuid)
51 | if err != nil {
52 | httpError(w, r, err, http.StatusInternalServerError)
53 | return
54 | }
55 |
56 | response, err := account.Info(username, uuid)
57 | if err != nil {
58 | httpError(w, r, err, http.StatusInternalServerError)
59 | return
60 | }
61 |
62 | jsonResponse(w, r, response)
63 | }
64 |
65 | func handleAccountRegister(w http.ResponseWriter, r *http.Request) {
66 | err := r.ParseForm()
67 | if err != nil {
68 | httpError(w, r, fmt.Errorf("failed to parse request form: %s", err), http.StatusBadRequest)
69 | return
70 | }
71 |
72 | err = account.Register(r.Form.Get("username"), r.Form.Get("password"))
73 | if err != nil {
74 | httpError(w, r, err, http.StatusInternalServerError)
75 | return
76 | }
77 |
78 | w.WriteHeader(http.StatusOK)
79 | }
80 |
81 | func handleAccountLogin(w http.ResponseWriter, r *http.Request) {
82 | err := r.ParseForm()
83 | if err != nil {
84 | httpError(w, r, fmt.Errorf("failed to parse request form: %s", err), http.StatusBadRequest)
85 | return
86 | }
87 |
88 | response, err := account.Login(r.Form.Get("username"), r.Form.Get("password"))
89 | if err != nil {
90 | httpError(w, r, err, http.StatusInternalServerError)
91 | return
92 | }
93 |
94 | jsonResponse(w, r, response)
95 | }
96 |
97 | func handleAccountChangePW(w http.ResponseWriter, r *http.Request) {
98 | err := r.ParseForm()
99 | if err != nil {
100 | httpError(w, r, fmt.Errorf("failed to parse request form: %s", err), http.StatusBadRequest)
101 | return
102 | }
103 |
104 | uuid, err := uuidFromRequest(r)
105 | if err != nil {
106 | httpError(w, r, err, http.StatusBadRequest)
107 | return
108 | }
109 |
110 | err = account.ChangePW(uuid, r.Form.Get("password"))
111 | if err != nil {
112 | httpError(w, r, err, http.StatusInternalServerError)
113 | return
114 | }
115 |
116 | w.WriteHeader(http.StatusOK)
117 | }
118 |
119 | func handleAccountLogout(w http.ResponseWriter, r *http.Request) {
120 | token, err := tokenFromRequest(r)
121 | if err != nil {
122 | httpError(w, r, err, http.StatusBadRequest)
123 | return
124 | }
125 |
126 | err = account.Logout(token)
127 | if err != nil {
128 | httpError(w, r, err, http.StatusInternalServerError)
129 | return
130 | }
131 |
132 | w.WriteHeader(http.StatusOK)
133 | }
134 |
135 | // game
136 | func handleGameTitleStats(w http.ResponseWriter, r *http.Request) {
137 | stats := defs.TitleStats{
138 | PlayerCount: playerCount,
139 | BattleCount: battleCount,
140 | }
141 |
142 | jsonResponse(w, r, stats)
143 | }
144 |
145 | func handleGameClassicSessionCount(w http.ResponseWriter, r *http.Request) {
146 | _, _ = w.Write([]byte(strconv.Itoa(classicSessionCount)))
147 | }
148 |
149 | func handleGetSessionData(w http.ResponseWriter, r *http.Request) {
150 | uuid, err := uuidFromRequest(r)
151 | if err != nil {
152 | httpError(w, r, err, http.StatusBadRequest)
153 | return
154 | }
155 |
156 | var slot int
157 | if r.URL.Query().Has("slot") {
158 | slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
159 | if err != nil {
160 | httpError(w, r, err, http.StatusBadRequest)
161 | return
162 | }
163 | }
164 |
165 | var clientSessionId string
166 | if r.URL.Query().Has("clientSessionId") {
167 | clientSessionId = r.URL.Query().Get("clientSessionId")
168 | } else {
169 | httpError(w, r, fmt.Errorf("missing clientSessionId"), http.StatusBadRequest)
170 | }
171 |
172 | err = db.UpdateActiveSession(uuid, clientSessionId)
173 | if err != nil {
174 | httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
175 | return
176 | }
177 |
178 | var save any
179 | save, err = savedata.Get(uuid, 1, slot)
180 | if errors.Is(err, sql.ErrNoRows) {
181 | http.Error(w, err.Error(), http.StatusNotFound)
182 | return
183 | }
184 |
185 | if err != nil {
186 | httpError(w, r, err, http.StatusInternalServerError)
187 | return
188 | }
189 |
190 | jsonResponse(w, r, save)
191 | }
192 |
193 | const legacyClientSessionId = "LEGACY_CLIENT"
194 |
195 | func legacyHandleGetSaveData(w http.ResponseWriter, r *http.Request) {
196 | uuid, err := uuidFromRequest(r)
197 | if err != nil {
198 | httpError(w, r, err, http.StatusBadRequest)
199 | return
200 | }
201 |
202 | datatype := -1
203 | if r.URL.Query().Has("datatype") {
204 | datatype, err = strconv.Atoi(r.URL.Query().Get("datatype"))
205 | if err != nil {
206 | httpError(w, r, err, http.StatusBadRequest)
207 | return
208 | }
209 | }
210 |
211 | var slot int
212 | if r.URL.Query().Has("slot") {
213 | slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
214 | if err != nil {
215 | httpError(w, r, err, http.StatusBadRequest)
216 | return
217 | }
218 | }
219 |
220 | var save any
221 | if datatype == 0 {
222 | err = db.UpdateActiveSession(uuid, legacyClientSessionId) // we dont have a client id
223 | if err != nil {
224 | httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
225 | return
226 | }
227 | }
228 |
229 | save, err = savedata.Get(uuid, datatype, slot)
230 | if errors.Is(err, sql.ErrNoRows) {
231 | http.Error(w, err.Error(), http.StatusNotFound)
232 | return
233 | }
234 |
235 | if err != nil {
236 | httpError(w, r, err, http.StatusInternalServerError)
237 | return
238 | }
239 |
240 | jsonResponse(w, r, save)
241 | }
242 |
243 | // FIXME UNFINISHED!!!
244 | func clearSessionData(w http.ResponseWriter, r *http.Request) {
245 | uuid, err := uuidFromRequest(r)
246 | if err != nil {
247 | httpError(w, r, err, http.StatusBadRequest)
248 | return
249 | }
250 |
251 | var slot int
252 | if r.URL.Query().Has("slot") {
253 | slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
254 | if err != nil {
255 | httpError(w, r, err, http.StatusBadRequest)
256 | return
257 | }
258 | }
259 |
260 | var save any
261 | var session defs.SessionSaveData
262 | err = json.NewDecoder(r.Body).Decode(&session)
263 | if err != nil {
264 | httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
265 | return
266 | }
267 |
268 | save = session
269 |
270 | var active bool
271 | active, err = db.IsActiveSession(uuid, legacyClientSessionId) //TODO unfinished, read token from query
272 | if err != nil {
273 | httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
274 | return
275 | }
276 |
277 | var trainerId, secretId int
278 | if r.URL.Query().Has("trainerId") && r.URL.Query().Has("secretId") {
279 | trainerId, err = strconv.Atoi(r.URL.Query().Get("trainerId"))
280 | if err != nil {
281 | httpError(w, r, err, http.StatusBadRequest)
282 | return
283 | }
284 |
285 | secretId, err = strconv.Atoi(r.URL.Query().Get("secretId"))
286 | if err != nil {
287 | httpError(w, r, err, http.StatusBadRequest)
288 | return
289 | }
290 | }
291 |
292 | storedTrainerId, storedSecretId, err := db.FetchTrainerIds(uuid)
293 | if err != nil {
294 | httpError(w, r, err, http.StatusInternalServerError)
295 | return
296 | }
297 |
298 | if storedTrainerId > 0 || storedSecretId > 0 {
299 | if trainerId != storedTrainerId || secretId != storedSecretId {
300 | httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
301 | return
302 | }
303 | } else {
304 | err = db.UpdateTrainerIds(trainerId, secretId, uuid)
305 | if err != nil {
306 | httpError(w, r, fmt.Errorf("unable to update trainer ID: %s", err), http.StatusInternalServerError)
307 | return
308 | }
309 | }
310 |
311 | if !active {
312 | save = savedata.ClearResponse{Error: "session out of date: not active"}
313 | }
314 |
315 | var seed string
316 | seed, err = db.GetDailyRunSeed()
317 | if err != nil {
318 | httpError(w, r, err, http.StatusInternalServerError)
319 | return
320 | }
321 |
322 | response, err := savedata.Clear(uuid, slot, seed, save.(defs.SessionSaveData))
323 | if err != nil {
324 | httpError(w, r, err, http.StatusInternalServerError)
325 | return
326 | }
327 |
328 | jsonResponse(w, r, response)
329 | }
330 |
331 | // FIXME UNFINISHED!!!
332 | func deleteSystemSave(w http.ResponseWriter, r *http.Request) {
333 | uuid, err := uuidFromRequest(r)
334 | if err != nil {
335 | httpError(w, r, err, http.StatusBadRequest)
336 | return
337 | }
338 |
339 | datatype := 0
340 | if r.URL.Query().Has("datatype") {
341 | datatype, err = strconv.Atoi(r.URL.Query().Get("datatype"))
342 | if err != nil {
343 | httpError(w, r, err, http.StatusBadRequest)
344 | return
345 | }
346 | }
347 |
348 | var slot int
349 | if r.URL.Query().Has("slot") {
350 | slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
351 | if err != nil {
352 | httpError(w, r, err, http.StatusBadRequest)
353 | return
354 | }
355 | }
356 |
357 | var active bool
358 | active, err = db.IsActiveSession(uuid, legacyClientSessionId) //TODO unfinished, read token from query
359 | if err != nil {
360 | httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusInternalServerError)
361 | return
362 | }
363 |
364 | if !active {
365 | httpError(w, r, fmt.Errorf("session out of date: not active"), http.StatusBadRequest)
366 | return
367 | }
368 |
369 | var trainerId, secretId int
370 |
371 | if r.URL.Query().Has("trainerId") && r.URL.Query().Has("secretId") {
372 | trainerId, err = strconv.Atoi(r.URL.Query().Get("trainerId"))
373 | if err != nil {
374 | httpError(w, r, err, http.StatusBadRequest)
375 | return
376 | }
377 |
378 | secretId, err = strconv.Atoi(r.URL.Query().Get("secretId"))
379 | if err != nil {
380 | httpError(w, r, err, http.StatusBadRequest)
381 | return
382 | }
383 | }
384 |
385 | storedTrainerId, storedSecretId, err := db.FetchTrainerIds(uuid)
386 | if err != nil {
387 | httpError(w, r, err, http.StatusInternalServerError)
388 | return
389 | }
390 |
391 | if storedTrainerId > 0 || storedSecretId > 0 {
392 | if trainerId != storedTrainerId || secretId != storedSecretId {
393 | httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
394 | return
395 | }
396 | } else {
397 | if err := db.UpdateTrainerIds(trainerId, secretId, uuid); err != nil {
398 | httpError(w, r, err, http.StatusInternalServerError)
399 | return
400 | }
401 | }
402 |
403 | err = savedata.Delete(uuid, datatype, slot)
404 | if err != nil {
405 | httpError(w, r, err, http.StatusInternalServerError)
406 | return
407 | }
408 |
409 | w.WriteHeader(http.StatusOK)
410 | }
411 |
412 | func legacyHandleSaveData(w http.ResponseWriter, r *http.Request) {
413 | uuid, err := uuidFromRequest(r)
414 | if err != nil {
415 | httpError(w, r, err, http.StatusBadRequest)
416 | return
417 | }
418 |
419 | datatype := -1
420 | if r.URL.Query().Has("datatype") {
421 | datatype, err = strconv.Atoi(r.URL.Query().Get("datatype"))
422 | if err != nil {
423 | httpError(w, r, err, http.StatusBadRequest)
424 | return
425 | }
426 | }
427 |
428 | var slot int
429 | if r.URL.Query().Has("slot") {
430 | slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
431 | if err != nil {
432 | httpError(w, r, err, http.StatusBadRequest)
433 | return
434 | }
435 | }
436 |
437 | var clientSessionId string
438 | if r.URL.Query().Has("clientSessionId") {
439 | clientSessionId = r.URL.Query().Get("clientSessionId")
440 | }
441 | if clientSessionId == "" {
442 | clientSessionId = legacyClientSessionId
443 | }
444 |
445 | var save any
446 | // /savedata/get and /savedata/delete specify datatype, but don't expect data in body
447 | if r.URL.Path != "/savedata/get" && r.URL.Path != "/savedata/delete" {
448 | if datatype == 0 {
449 | var system defs.SystemSaveData
450 | err = json.NewDecoder(r.Body).Decode(&system)
451 | if err != nil {
452 | httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
453 | return
454 | }
455 |
456 | save = system
457 | // /savedata/clear doesn't specify datatype, it is assumed to be 1 (session)
458 | } else if datatype == 1 || r.URL.Path == "/savedata/clear" {
459 | var session defs.SessionSaveData
460 | err = json.NewDecoder(r.Body).Decode(&session)
461 | if err != nil {
462 | httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
463 | return
464 | }
465 |
466 | save = session
467 | }
468 | }
469 |
470 | var active bool
471 | if r.URL.Path == "/savedata/get" {
472 | if datatype == 0 {
473 | err = db.UpdateActiveSession(uuid, clientSessionId)
474 | if err != nil {
475 | httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
476 | return
477 | }
478 | }
479 | } else {
480 | active, err = db.IsActiveSession(uuid, clientSessionId)
481 | if err != nil {
482 | httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
483 | return
484 | }
485 |
486 | // TODO: make this not suck
487 | if !active && r.URL.Path != "/savedata/clear" {
488 | httpError(w, r, fmt.Errorf("session out of date: not active"), http.StatusBadRequest)
489 | return
490 | }
491 |
492 | var trainerId, secretId int
493 |
494 | if r.URL.Path != "/savedata/update" || datatype == 1 {
495 | if r.URL.Query().Has("trainerId") && r.URL.Query().Has("secretId") {
496 | trainerId, err = strconv.Atoi(r.URL.Query().Get("trainerId"))
497 | if err != nil {
498 | httpError(w, r, err, http.StatusBadRequest)
499 | return
500 | }
501 |
502 | secretId, err = strconv.Atoi(r.URL.Query().Get("secretId"))
503 | if err != nil {
504 | httpError(w, r, err, http.StatusBadRequest)
505 | return
506 | }
507 | }
508 | } else {
509 | trainerId = save.(defs.SystemSaveData).TrainerId
510 | secretId = save.(defs.SystemSaveData).SecretId
511 | }
512 |
513 | storedTrainerId, storedSecretId, err := db.FetchTrainerIds(uuid)
514 | if err != nil {
515 | httpError(w, r, err, http.StatusInternalServerError)
516 | return
517 | }
518 |
519 | if storedTrainerId > 0 || storedSecretId > 0 {
520 | if trainerId != storedTrainerId || secretId != storedSecretId {
521 | httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
522 | return
523 | }
524 | } else {
525 | if err := db.UpdateTrainerIds(trainerId, secretId, uuid); err != nil {
526 | httpError(w, r, err, http.StatusInternalServerError)
527 | return
528 | }
529 | }
530 | }
531 |
532 | switch r.URL.Path {
533 | case "/savedata/get":
534 | save, err = savedata.Get(uuid, datatype, slot)
535 | if err == sql.ErrNoRows {
536 | http.Error(w, err.Error(), http.StatusNotFound)
537 | return
538 | }
539 | case "/savedata/update":
540 | err = savedata.Update(uuid, slot, save)
541 | case "/savedata/delete":
542 | err = savedata.Delete(uuid, datatype, slot)
543 | case "/savedata/clear":
544 | if !active {
545 | // TODO: make this not suck
546 | save = savedata.ClearResponse{Error: "session out of date: not active"}
547 | break
548 | }
549 |
550 | var seed string
551 | seed, err = db.GetDailyRunSeed()
552 | if err != nil {
553 | httpError(w, r, err, http.StatusInternalServerError)
554 | return
555 | }
556 |
557 | // doesn't return a save, but it works
558 | save, err = savedata.Clear(uuid, slot, seed, save.(defs.SessionSaveData))
559 | }
560 | if err != nil {
561 | httpError(w, r, err, http.StatusInternalServerError)
562 | return
563 | }
564 |
565 | if save == nil || r.URL.Path == "/savedata/update" {
566 | w.WriteHeader(http.StatusOK)
567 | return
568 | }
569 |
570 | jsonResponse(w, r, save)
571 | }
572 |
573 | type CombinedSaveData struct {
574 | System defs.SystemSaveData `json:"system"`
575 | Session defs.SessionSaveData `json:"session"`
576 | SessionSlotId int `json:"sessionSlotId"`
577 | ClientSessionId string `json:"clientSessionId"`
578 | }
579 |
580 | // TODO wrap this in a transaction
581 | func handleUpdateAll(w http.ResponseWriter, r *http.Request) {
582 | uuid, err := uuidFromRequest(r)
583 | if err != nil {
584 | httpError(w, r, err, http.StatusBadRequest)
585 | return
586 | }
587 |
588 | var data CombinedSaveData
589 | err = json.NewDecoder(r.Body).Decode(&data)
590 | if err != nil {
591 | httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
592 | return
593 | }
594 | if data.ClientSessionId == "" {
595 | data.ClientSessionId = legacyClientSessionId
596 | }
597 |
598 | var active bool
599 | active, err = db.IsActiveSession(uuid, data.ClientSessionId)
600 | if err != nil {
601 | httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
602 | return
603 | }
604 |
605 | if !active {
606 | httpError(w, r, fmt.Errorf("session out of date: not active"), http.StatusBadRequest)
607 | return
608 | }
609 |
610 | trainerId := data.System.TrainerId
611 | secretId := data.System.SecretId
612 |
613 | storedTrainerId, storedSecretId, err := db.FetchTrainerIds(uuid)
614 | if err != nil {
615 | httpError(w, r, err, http.StatusInternalServerError)
616 | return
617 | }
618 |
619 | if storedTrainerId > 0 || storedSecretId > 0 {
620 | if trainerId != storedTrainerId || secretId != storedSecretId {
621 | httpError(w, r, fmt.Errorf("session out of date: stored trainer or secret ID does not match"), http.StatusBadRequest)
622 | return
623 | }
624 | } else {
625 | if err = db.UpdateTrainerIds(trainerId, secretId, uuid); err != nil {
626 | httpError(w, r, err, http.StatusInternalServerError)
627 | return
628 | }
629 | }
630 |
631 | err = savedata.Update(uuid, data.SessionSlotId, data.Session)
632 | if err != nil {
633 | httpError(w, r, err, http.StatusInternalServerError)
634 | return
635 | }
636 | err = savedata.Update(uuid, 0, data.System)
637 | if err != nil {
638 | httpError(w, r, err, http.StatusInternalServerError)
639 | return
640 | }
641 | w.WriteHeader(http.StatusOK)
642 | }
643 |
644 | type SystemVerifyResponse struct {
645 | Valid bool `json:"valid"`
646 | SystemData *defs.SystemSaveData `json:"systemData"`
647 | }
648 |
649 | type SystemVerifyRequest struct {
650 | ClientSessionId string `json:"clientSessionId"`
651 | }
652 |
653 | func handleSystemVerify(w http.ResponseWriter, r *http.Request) {
654 | uuid, err := uuidFromRequest(r)
655 | if err != nil {
656 | httpError(w, r, err, http.StatusBadRequest)
657 | return
658 | }
659 |
660 | var input SystemVerifyRequest
661 | err = json.NewDecoder(r.Body).Decode(&input)
662 | if err != nil {
663 | httpError(w, r, fmt.Errorf("failed to decode request body: %s", err), http.StatusBadRequest)
664 | return
665 | }
666 |
667 | var active bool
668 | active, err = db.IsActiveSession(uuid, input.ClientSessionId)
669 | if err != nil {
670 | httpError(w, r, fmt.Errorf("failed to check active session: %s", err), http.StatusBadRequest)
671 | return
672 | }
673 |
674 | response := SystemVerifyResponse{
675 | Valid: active,
676 | }
677 |
678 | // not valid, send server state
679 | if !active {
680 | err = db.UpdateActiveSession(uuid, input.ClientSessionId)
681 | if err != nil {
682 | httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
683 | return
684 | }
685 |
686 | var storedSaveData defs.SystemSaveData
687 | storedSaveData, err = db.ReadSystemSaveData(uuid)
688 | if err != nil {
689 | httpError(w, r, fmt.Errorf("failed to read session save data: %s", err), http.StatusInternalServerError)
690 | return
691 | }
692 |
693 | response.SystemData = &storedSaveData
694 | }
695 |
696 | jsonResponse(w, r, response)
697 | }
698 |
699 | func handleGetSystemData(w http.ResponseWriter, r *http.Request) {
700 | uuid, err := uuidFromRequest(r)
701 | if err != nil {
702 | httpError(w, r, err, http.StatusBadRequest)
703 | return
704 | }
705 |
706 | var clientSessionId string
707 | if r.URL.Query().Has("clientSessionId") {
708 | clientSessionId = r.URL.Query().Get("clientSessionId")
709 | } else {
710 | httpError(w, r, fmt.Errorf("missing clientSessionId"), http.StatusBadRequest)
711 | }
712 |
713 | err = db.UpdateActiveSession(uuid, clientSessionId)
714 | if err != nil {
715 | httpError(w, r, fmt.Errorf("failed to update active session: %s", err), http.StatusBadRequest)
716 | return
717 | }
718 |
719 | var save any //TODO this is always system save data
720 | save, err = savedata.Get(uuid, 0, 0)
721 | if err != nil {
722 | if errors.Is(err, sql.ErrNoRows) {
723 | http.Error(w, err.Error(), http.StatusNotFound)
724 | } else {
725 | httpError(w, r, err, http.StatusInternalServerError)
726 | }
727 |
728 | return
729 | }
730 | //TODO apply vouchers
731 |
732 | jsonResponse(w, r, save)
733 | }
734 |
735 | func legacyHandleNewClear(w http.ResponseWriter, r *http.Request) {
736 | uuid, err := uuidFromRequest(r)
737 | if err != nil {
738 | httpError(w, r, err, http.StatusBadRequest)
739 | return
740 | }
741 |
742 | var slot int
743 | if r.URL.Query().Has("slot") {
744 | slot, err = strconv.Atoi(r.URL.Query().Get("slot"))
745 | if err != nil {
746 | httpError(w, r, err, http.StatusBadRequest)
747 | return
748 | }
749 | }
750 |
751 | newClear, err := savedata.NewClear(uuid, slot)
752 | if err != nil {
753 | httpError(w, r, fmt.Errorf("failed to read new clear: %s", err), http.StatusInternalServerError)
754 | return
755 | }
756 |
757 | jsonResponse(w, r, newClear)
758 | }
759 |
760 | // daily
761 | func handleDailySeed(w http.ResponseWriter, r *http.Request) {
762 | seed, err := db.GetDailyRunSeed()
763 | if err != nil {
764 | httpError(w, r, err, http.StatusInternalServerError)
765 | return
766 | }
767 |
768 | _, err = w.Write([]byte(seed))
769 | if err != nil {
770 | httpError(w, r, fmt.Errorf("failed to write seed: %s", err), http.StatusInternalServerError)
771 | }
772 | }
773 |
774 | func handleDailyRankings(w http.ResponseWriter, r *http.Request) {
775 | var err error
776 |
777 | var category int
778 | if r.URL.Query().Has("category") {
779 | category, err = strconv.Atoi(r.URL.Query().Get("category"))
780 | if err != nil {
781 | httpError(w, r, fmt.Errorf("failed to convert category: %s", err), http.StatusBadRequest)
782 | return
783 | }
784 | }
785 |
786 | page := 1
787 | if r.URL.Query().Has("page") {
788 | page, err = strconv.Atoi(r.URL.Query().Get("page"))
789 | if err != nil {
790 | httpError(w, r, fmt.Errorf("failed to convert page: %s", err), http.StatusBadRequest)
791 | return
792 | }
793 | }
794 |
795 | rankings, err := daily.Rankings(category, page)
796 | if err != nil {
797 | httpError(w, r, err, http.StatusInternalServerError)
798 | return
799 | }
800 |
801 | jsonResponse(w, r, rankings)
802 | }
803 |
804 | func handleDailyRankingPageCount(w http.ResponseWriter, r *http.Request) {
805 | var category int
806 | if r.URL.Query().Has("category") {
807 | var err error
808 | category, err = strconv.Atoi(r.URL.Query().Get("category"))
809 | if err != nil {
810 | httpError(w, r, fmt.Errorf("failed to convert category: %s", err), http.StatusBadRequest)
811 | return
812 | }
813 | }
814 |
815 | count, err := daily.RankingPageCount(category)
816 | if err != nil {
817 | httpError(w, r, err, http.StatusInternalServerError)
818 | }
819 |
820 | _, _ = w.Write([]byte(strconv.Itoa(count)))
821 | }
822 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------