Skip to content

Commit

Permalink
Initial Commit (Poke Gen6)
Browse files Browse the repository at this point in the history
  • Loading branch information
shutterbug2000 committed Oct 4, 2023
0 parents commit c388047
Show file tree
Hide file tree
Showing 33 changed files with 1,786 additions and 0 deletions.
30 changes: 30 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib

# Test binary, built with `go test -c`
*.test

# Output of the go coverage tool, specifically when used with LiteIDE
*.out

# Dependency directories (remove the comment below to include it)
# vendor/

# Go workspace file
go.work
go.work.sum

# custom
.vscode
.env
build
log
*.pem
*.key
661 changes: 661 additions & 0 deletions LICENSE

Large diffs are not rendered by default.

60 changes: 60 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# TODO - Assumes a UNIX-like OS

RED := $(shell tput setaf 1)
BLUE := $(shell tput setaf 4)
CYAN := $(shell tput setaf 14)
ORANGE := $(shell tput setaf 202)
YELLOW := $(shell tput setaf 214)
RESET := $(shell tput sgr0)

ifeq ($(shell which go),)
# TODO - Read contents from .git folder instead?
$(error "$(RED)go command not found. Install go to continue $(BLUE)https://go.dev/doc/install$(RESET)")
endif

ifneq ($(wildcard .git),)
# * .git folder exists, build server build string from repo info
ifeq ($(shell which git),)
# TODO - Read contents from .git folder instead?
$(error "$(RED)git command not found. Install git to continue $(ORANGE)https://git-scm.com/downloads$(RESET)")
endif
$(info "$(CYAN)Building server build string from repository info$(RESET)")
# * Build server build string from repo info
BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
REMOTE_ORIGIN := $(shell git config --get remote.origin.url)

# * Handle multiple origin URL formats
HTTPS_PREFIX_CHECK := $(shell echo $(REMOTE_ORIGIN) | head -c 8)
HTTP_PREFIX_CHECK := $(shell echo $(REMOTE_ORIGIN) | head -c 7)
GIT@_PREFIX_CHECK := $(shell echo $(REMOTE_ORIGIN) | head -c 4)

ifeq ($(HTTPS_PREFIX_CHECK), https://)
REMOTE_PATH := $(shell echo $(REMOTE_ORIGIN) | cut -d/ -f4-)
else ifeq ($(HTTP_PREFIX_CHECK), http://)
REMOTE_PATH := $(shell echo $(REMOTE_ORIGIN) | cut -d/ -f4-)
else ifeq ($(GIT@_PREFIX_CHECK), git@)
REMOTE_PATH := $(shell echo $(REMOTE_ORIGIN) | cut -d: -f2-)
else
REMOTE_PATH := $(shell echo $(REMOTE_ORIGIN) | cut -d/ -f2-)
endif

HASH := $(shell git rev-parse --short HEAD)
SERVER_BUILD := $(BRANCH):$(REMOTE_PATH)@$(HASH)

else
# * .git folder not present, assume downloaded from zip file and just use folder name
$(info "$(CYAN)git repository not found. Building server build string from folder name$(RESET)")
SERVER_BUILD := $(notdir $(CURDIR))
endif

# * Final build string
DATE_TIME := $(shell date --iso=seconds)
BUILD_STRING := $(SERVER_BUILD), $(DATE_TIME)

all:
ifeq ($(wildcard .env),)
$(warning "$(YELLOW).env file not found, environment variables may not be populated correctly$(RESET)")
endif
go get -u
go mod tidy
go build -ldflags "-X 'main.serverBuildString=$(BUILD_STRING)'" -o ./build/$(notdir $(CURDIR))
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Pokemon X/Y/OR/AS (Generation 6) (3DS) replacement server
Includes both the authentication and secure servers

## Compiling

### Setup
Install [Go](https://go.dev/doc/install) and [git](https://git-scm.com/downloads), then clone and enter the repository

```bash
$ git clone https://github.com/PretendoNetwork/pokemon-gen6
$ cd pokemon-gen6
```

### Compiling using `go`
To compile using Go, `go get` the required modules and then `go build` to your desired location. You may also want to tidy the go modules, though this is optional

```bash
$ go get -u
$ go mod tidy
$ go build -o build/pokegen6
```

The server is now built to `build/pokegen6`

When compiling with only Go, the authentication servers build string is not automatically set. This should not cause any issues with gameplay, but it means that the server build will not be visible in any packet dumps or logs a title may produce

To compile the servers with the authentication server build string, add `-ldflags "-X 'main.serverBuildString=BUILD_STRING_HERE'"` to the build command, or use `make` to compile the server

### Compiling using `make`
Compiling using `make` will read the local `.git` directory to create a dynamic authentication server build string, based on your repositories remote origin and current commit. It will also use the current folders name as the executables name

Install `make` onto your system (this varies by OS), and run `make` while inside the repository

```bash
$ make
```

The server is now built to `build/pokemon-gen6` with the authentication server build string already set

## Configuration
All configuration options are handled via environment variables

`.env` files are supported

| Name | Description | Required |
|-----------------------------------------|------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------|
| `PN_POKEGEN6_POSTGRES_URI` | Fully qualified URI to your Postgres server (Example `postgres://username:password@localhost/pokegen6?sslmode=disable`) | Yes |
| `PN_POKEGEN6_KERBEROS_PASSWORD` | Password used as part of the internal server data in Kerberos tickets | No (Default password `password` will be used) |
| `PN_POKEGEN6_AUTHENTICATION_SERVER_PORT` | Port for the authentication server | Yes |
| `PN_POKEGEN6_SECURE_SERVER_HOST` | Host name for the secure server (should point to the same address as the authentication server) | Yes |
| `PN_POKEGEN6_SECURE_SERVER_PORT` | Port for the secure server | Yes |
| `PN_POKEGEN6_ACCOUNT_GRPC_HOST` | Host name for your account server gRPC service | Yes |
| `PN_POKEGEN6_ACCOUNT_GRPC_PORT` | Port for your account server gRPC service | Yes |
| `PN_POKEGEN6_ACCOUNT_GRPC_API_KEY` | API key for your account server gRPC service | No (Assumed to be an open gRPC API) |
25 changes: 25 additions & 0 deletions database/connect_postgres.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package database

import (
"database/sql"
"os"

_ "github.com/lib/pq"

"github.com/PretendoNetwork/pokemon-gen6/globals"
)

var Postgres *sql.DB

func ConnectPostgres() {
var err error

Postgres, err = sql.Open("postgres", os.Getenv("PN_POKEGEN6_POSTGRES_URI"))
if err != nil {
globals.Logger.Critical(err.Error())
}

globals.Logger.Success("Connected to Postgres!")

initPostgres()
}
63 changes: 63 additions & 0 deletions database/get_rankings_by_category_and_ranking_order_param.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package database

import (
"database/sql"

ranking_types "github.com/PretendoNetwork/nex-protocols-go/ranking/types"
"github.com/PretendoNetwork/pokemon-gen6/globals"
"github.com/PretendoNetwork/pokemon-gen6/types"
)

func GetRankingsByCategoryAndRankingOrderParam(category uint32, rankingOrderParam *ranking_types.RankingOrderParam) (error, []*ranking_types.RankingRankData) {
rankings := make([]*ranking_types.RankingRankData, 0, rankingOrderParam.Length)

rows, err := Postgres.Query(`
SELECT
owner_pid,
score,
groups,
param,
common_data
FROM rankings WHERE category=$1 ORDER BY score DESC LIMIT $2 OFFSET $3`,
category,
rankingOrderParam.Length,
rankingOrderParam.Offset,
)
if err != nil {
return err, rankings
}

row := 1
for rows.Next() {
rankingRankData := ranking_types.NewRankingRankData()
rankingRankData.UniqueID = 0
rankingRankData.Order = uint32(row)
rankingRankData.Category = category

// * A custom type is needed because
// * Postgres doesn't support scanning
// * uint8 slices by default
var groups types.PQUInt8Array

err := rows.Scan(
&rankingRankData.PrincipalID,
&rankingRankData.Score,
&groups,
&rankingRankData.Param,
&rankingRankData.CommonData,
)

if err != nil && err != sql.ErrNoRows {
globals.Logger.Critical(err.Error())
}

if err == nil {
rankingRankData.Groups = groups.Value
rankings = append(rankings, rankingRankData)

row += 1
}
}

return nil, rankings
}
12 changes: 12 additions & 0 deletions database/get_total_rankings_by_category.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package database

func GetTotalRankingsByCategory(category uint32) (error, uint32) {
var total uint32

err := Postgres.QueryRow(`SELECT COUNT(*) FROM rankings WHERE category=$1`, category).Scan(&total)
if err != nil {
return err, 0
}

return nil, total
}
26 changes: 26 additions & 0 deletions database/init_postgres.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package database

import "github.com/PretendoNetwork/pokemon-gen6/globals"

func initPostgres() {
var err error

_, err = Postgres.Exec(`CREATE TABLE IF NOT EXISTS rankings (
id bigserial PRIMARY KEY,
owner_pid integer,
category integer,
score integer,
order_by integer,
update_mode integer,
groups integer[],
param bigint,
common_data bytea,
created_at bigint
)`)
if err != nil {
globals.Logger.Critical(err.Error())
return
}

globals.Logger.Success("Postgres tables created")
}
38 changes: 38 additions & 0 deletions database/insert_ranking_by_pid_and_ranking_score_data.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package database

import (
"time"

ranking_types "github.com/PretendoNetwork/nex-protocols-go/ranking/types"
"github.com/lib/pq"
)

func InsertRankingByPIDAndRankingScoreData(pid uint32, rankingScoreData *ranking_types.RankingScoreData) error {
now := time.Now().UnixNano()

_, err := Postgres.Exec(`
INSERT INTO rankings (
owner_pid,
category,
score,
order_by,
update_mode,
groups,
param,
common_data,
created_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
pid,
rankingScoreData.Category,
rankingScoreData.Score,
rankingScoreData.OrderBy,
rankingScoreData.UpdateMode,
pq.Array(rankingScoreData.Groups),
rankingScoreData.Param,
make([]byte, 0),
now,
)

return err
}
17 changes: 17 additions & 0 deletions globals/globals.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package globals

import (
pb "github.com/PretendoNetwork/grpc-go/account"
"github.com/PretendoNetwork/nex-go"
"github.com/PretendoNetwork/plogger-go"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

var Logger *plogger.Logger
var KerberosPassword = "password" // * Default password
var AuthenticationServer *nex.Server
var SecureServer *nex.Server
var GRPCAccountClientConnection *grpc.ClientConn
var GRPCAccountClient pb.AccountClient
var GRPCAccountCommonMetadata metadata.MD
22 changes: 22 additions & 0 deletions globals/password_from_pid.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package globals

import (
"context"

pb "github.com/PretendoNetwork/grpc-go/account"
"github.com/PretendoNetwork/nex-go"
"github.com/PretendoNetwork/nex-protocols-go/globals"
"google.golang.org/grpc/metadata"
)

func PasswordFromPID(pid uint32) (string, uint32) {
ctx := metadata.NewOutgoingContext(context.Background(), GRPCAccountCommonMetadata)

response, err := GRPCAccountClient.GetNEXPassword(ctx, &pb.GetNEXPasswordRequest{Pid: pid})
if err != nil {
globals.Logger.Error(err.Error())
return "", nex.Errors.RendezVous.InvalidUsername
}

return response.Password, 0
}
3 changes: 3 additions & 0 deletions globals/subscription.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package globals

var Timeline map[uint32][]uint8
1 change: 1 addition & 0 deletions globals/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package globals
31 changes: 31 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
module github.com/PretendoNetwork/pokemon-gen6

go 1.19

require (
github.com/PretendoNetwork/grpc-go v1.0.2
github.com/PretendoNetwork/nex-go v1.0.41
github.com/PretendoNetwork/nex-protocols-common-go v1.0.28
github.com/PretendoNetwork/nex-protocols-go v1.0.53
github.com/PretendoNetwork/plogger-go v1.0.4
github.com/joho/godotenv v1.5.1
github.com/lib/pq v1.10.9
google.golang.org/grpc v1.58.2
)

require (
github.com/fatih/color v1.15.0 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/jwalton/go-supportscolor v1.2.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/superwhiskers/crunch/v3 v3.5.7 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/mod v0.12.0 // indirect
golang.org/x/net v0.15.0 // indirect
golang.org/x/sys v0.12.0 // indirect
golang.org/x/term v0.12.0 // indirect
golang.org/x/text v0.13.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231002182017-d307bd883b97 // indirect
google.golang.org/protobuf v1.31.0 // indirect
)
Loading

0 comments on commit c388047

Please sign in to comment.