adding validated services? patching forcad_local.py

This commit is contained in:
Your Name
2026-08-13 08:32:35 +07:00
parent d485f61169
commit e795614e45
1459 changed files with 420036 additions and 436 deletions

View File

@@ -0,0 +1 @@
don't forget the attack data...

View File

@@ -0,0 +1,22 @@
FROM golang:1.25.1-bookworm AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/root/.cache/go-build \
--mount=type=cache,target=/go/pkg/mod \
go mod download
COPY . .
RUN --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
go build -ldflags "-s -w" -o /out/ ./...
FROM gcr.io/distroless/static-debian11:nonroot
COPY --from=builder /out/block-game-backend /usr/local/bin/block-game-backend
USER nonroot:nonroot
ENTRYPOINT ["/usr/local/bin/block-game-backend"]

View File

@@ -0,0 +1,7 @@
FROM golang:1.25.1-bookworm AS runner
WORKDIR /app
RUN go install github.com/mitranim/gow@latest
CMD ["gow", "run", "."]

View File

@@ -0,0 +1 @@
to regenerate code: `go generate ./codegen`

View File

@@ -0,0 +1,46 @@
package auth
import (
"context"
"fmt"
"net/http"
"omctf.ru/block-game-backend/auth/session"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/utils"
)
type ctxUserKeyT struct{}
var ctxUserKey = ctxUserKeyT{}
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, err := session.GetSessionUser(r)
if session.IsNotLoggedIn(err) {
http.Error(w, "Not logged in", http.StatusUnauthorized)
return
}
if session.IsInvalidSession(err) {
http.Error(w, "Invalid session, reset cookies", http.StatusBadRequest)
return
}
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
ctx := context.WithValue(r.Context(), ctxUserKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func GetUser(ctx context.Context) (*ent.User, error) {
user, ok := ctx.Value(ctxUserKey).(*ent.User)
if !ok {
return nil, fmt.Errorf("context is invalid: expected user")
}
return user, nil
}

View File

@@ -0,0 +1,175 @@
package session
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log"
"net/http"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/db"
"github.com/gorilla/sessions"
)
func generateRandomKey() (string, error) {
bytes := make([]byte, 32)
_, err := rand.Read(bytes)
if err != nil {
return "", fmt.Errorf("rand failed: %w", err)
}
return hex.EncodeToString(bytes), nil
}
func getOrCreateSessionSecret(ctx context.Context) (string, error) {
secret, err := db.Client.Setting.Query().
Where(setting.Key("session_secret")).
Only(ctx)
if err == nil {
return secret.Value, nil
}
if !ent.IsNotFound(err) {
return "", fmt.Errorf("unexpected db error: %w", err)
}
log.Println("session secret not found, generating a new one")
newSecret, err := generateRandomKey()
if err != nil {
return "", fmt.Errorf("generating session secret failed: %w", err)
}
_, err = db.Client.Setting.Create().
SetKey("session_secret").
SetValue(newSecret).
Save(ctx)
if err != nil {
return "", fmt.Errorf("saving session secret failed: %w", err)
}
return newSecret, nil
}
var Store *sessions.CookieStore
func Initialize() error {
ctx := context.Background()
sessionSecret, err := getOrCreateSessionSecret(ctx)
if err != nil {
return fmt.Errorf("getting session secret failed: %w", err)
}
Store = sessions.NewCookieStore([]byte(sessionSecret))
Store.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7, // 7 days
HttpOnly: true,
Secure: false, // we don't use https
}
return nil
}
type NotLoggedInError struct{}
func (e *NotLoggedInError) Error() string {
return "Not logged in"
}
func IsNotLoggedIn(err error) bool {
if err == nil {
return false
}
var e *NotLoggedInError
return errors.As(err, &e)
}
type InvalidSessionError struct {
Reason error
}
func (err *InvalidSessionError) Error() string {
return fmt.Sprintf("invalid session: %s", err.Reason)
}
func (err *InvalidSessionError) Unwrap() error {
return err.Reason
}
func IsInvalidSession(err error) bool {
if err == nil {
return false
}
var e *InvalidSessionError
return errors.As(err, &e)
}
func GetUserId(r *http.Request) (int, error) {
session, err := Store.Get(r, "auth")
if err != nil {
return -1, &InvalidSessionError{Reason: err}
}
id := session.Values["user_id"]
if id == nil {
return -1, &NotLoggedInError{}
}
idValue, ok := id.(int)
if !ok {
return -1, &InvalidSessionError{Reason: fmt.Errorf("id is not an int")}
}
return idValue, nil
}
func SetUserId(w http.ResponseWriter, r *http.Request, userId int) error {
session, err := Store.Get(r, "auth")
if err != nil {
return &InvalidSessionError{Reason: err}
}
session.Values["user_id"] = userId
if err := session.Save(r, w); err != nil {
return fmt.Errorf("saving session failed: %w", err)
}
return nil
}
func GetSessionUser(r *http.Request) (*ent.User, error) {
ctx := r.Context()
userId, err := GetUserId(r)
if err != nil {
return nil, fmt.Errorf("fetching the user id failed: %w", err)
}
user, err := db.Client.User.Get(ctx, userId)
if err != nil {
return nil, &InvalidSessionError{Reason: fmt.Errorf("fetching the user from the database failed: %w", err)}
}
return user, nil
}
func ClearSession(w http.ResponseWriter, r *http.Request) error {
session, err := Store.Get(r, "auth")
if err != nil {
return fmt.Errorf("fetching session failed: %w", err)
}
session.Options.MaxAge = -1
if err := session.Save(r, w); err != nil {
return fmt.Errorf("clearing session failed: %w", err)
}
return nil
}

View File

@@ -0,0 +1,691 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"omctf.ru/block-game-backend/codegen/ent/migrate"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Level is the client for interacting with the Level builders.
Level *LevelClient
// Setting is the client for interacting with the Setting builders.
Setting *SettingClient
// User is the client for interacting with the User builders.
User *UserClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Level = NewLevelClient(c.config)
c.Setting = NewSettingClient(c.config)
c.User = NewUserClient(c.config)
}
type (
// config is the configuration for the client and its builder.
config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Level: NewLevelClient(cfg),
Setting: NewSettingClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Level: NewLevelClient(cfg),
Setting: NewSettingClient(cfg),
User: NewUserClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Level.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Level.Use(hooks...)
c.Setting.Use(hooks...)
c.User.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Level.Intercept(interceptors...)
c.Setting.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *LevelMutation:
return c.Level.mutate(ctx, m)
case *SettingMutation:
return c.Setting.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
}
// LevelClient is a client for the Level schema.
type LevelClient struct {
config
}
// NewLevelClient returns a client for the Level from the given config.
func NewLevelClient(c config) *LevelClient {
return &LevelClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `level.Hooks(f(g(h())))`.
func (c *LevelClient) Use(hooks ...Hook) {
c.hooks.Level = append(c.hooks.Level, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `level.Intercept(f(g(h())))`.
func (c *LevelClient) Intercept(interceptors ...Interceptor) {
c.inters.Level = append(c.inters.Level, interceptors...)
}
// Create returns a builder for creating a Level entity.
func (c *LevelClient) Create() *LevelCreate {
mutation := newLevelMutation(c.config, OpCreate)
return &LevelCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Level entities.
func (c *LevelClient) CreateBulk(builders ...*LevelCreate) *LevelCreateBulk {
return &LevelCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *LevelClient) MapCreateBulk(slice any, setFunc func(*LevelCreate, int)) *LevelCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &LevelCreateBulk{err: fmt.Errorf("calling to LevelClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*LevelCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &LevelCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Level.
func (c *LevelClient) Update() *LevelUpdate {
mutation := newLevelMutation(c.config, OpUpdate)
return &LevelUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *LevelClient) UpdateOne(_m *Level) *LevelUpdateOne {
mutation := newLevelMutation(c.config, OpUpdateOne, withLevel(_m))
return &LevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *LevelClient) UpdateOneID(id int) *LevelUpdateOne {
mutation := newLevelMutation(c.config, OpUpdateOne, withLevelID(id))
return &LevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Level.
func (c *LevelClient) Delete() *LevelDelete {
mutation := newLevelMutation(c.config, OpDelete)
return &LevelDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *LevelClient) DeleteOne(_m *Level) *LevelDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *LevelClient) DeleteOneID(id int) *LevelDeleteOne {
builder := c.Delete().Where(level.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &LevelDeleteOne{builder}
}
// Query returns a query builder for Level.
func (c *LevelClient) Query() *LevelQuery {
return &LevelQuery{
config: c.config,
ctx: &QueryContext{Type: TypeLevel},
inters: c.Interceptors(),
}
}
// Get returns a Level entity by its id.
func (c *LevelClient) Get(ctx context.Context, id int) (*Level, error) {
return c.Query().Where(level.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *LevelClient) GetX(ctx context.Context, id int) *Level {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryOwner queries the owner edge of a Level.
func (c *LevelClient) QueryOwner(_m *Level) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, level.OwnerTable, level.OwnerColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryInvitedPlayers queries the invitedPlayers edge of a Level.
func (c *LevelClient) QueryInvitedPlayers(_m *Level) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, level.InvitedPlayersTable, level.InvitedPlayersPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *LevelClient) Hooks() []Hook {
return c.hooks.Level
}
// Interceptors returns the client interceptors.
func (c *LevelClient) Interceptors() []Interceptor {
return c.inters.Level
}
func (c *LevelClient) mutate(ctx context.Context, m *LevelMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&LevelCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&LevelUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&LevelUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&LevelDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Level mutation op: %q", m.Op())
}
}
// SettingClient is a client for the Setting schema.
type SettingClient struct {
config
}
// NewSettingClient returns a client for the Setting from the given config.
func NewSettingClient(c config) *SettingClient {
return &SettingClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `setting.Hooks(f(g(h())))`.
func (c *SettingClient) Use(hooks ...Hook) {
c.hooks.Setting = append(c.hooks.Setting, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `setting.Intercept(f(g(h())))`.
func (c *SettingClient) Intercept(interceptors ...Interceptor) {
c.inters.Setting = append(c.inters.Setting, interceptors...)
}
// Create returns a builder for creating a Setting entity.
func (c *SettingClient) Create() *SettingCreate {
mutation := newSettingMutation(c.config, OpCreate)
return &SettingCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Setting entities.
func (c *SettingClient) CreateBulk(builders ...*SettingCreate) *SettingCreateBulk {
return &SettingCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *SettingClient) MapCreateBulk(slice any, setFunc func(*SettingCreate, int)) *SettingCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &SettingCreateBulk{err: fmt.Errorf("calling to SettingClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*SettingCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &SettingCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Setting.
func (c *SettingClient) Update() *SettingUpdate {
mutation := newSettingMutation(c.config, OpUpdate)
return &SettingUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *SettingClient) UpdateOne(_m *Setting) *SettingUpdateOne {
mutation := newSettingMutation(c.config, OpUpdateOne, withSetting(_m))
return &SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *SettingClient) UpdateOneID(id int) *SettingUpdateOne {
mutation := newSettingMutation(c.config, OpUpdateOne, withSettingID(id))
return &SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Setting.
func (c *SettingClient) Delete() *SettingDelete {
mutation := newSettingMutation(c.config, OpDelete)
return &SettingDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *SettingClient) DeleteOne(_m *Setting) *SettingDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *SettingClient) DeleteOneID(id int) *SettingDeleteOne {
builder := c.Delete().Where(setting.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &SettingDeleteOne{builder}
}
// Query returns a query builder for Setting.
func (c *SettingClient) Query() *SettingQuery {
return &SettingQuery{
config: c.config,
ctx: &QueryContext{Type: TypeSetting},
inters: c.Interceptors(),
}
}
// Get returns a Setting entity by its id.
func (c *SettingClient) Get(ctx context.Context, id int) (*Setting, error) {
return c.Query().Where(setting.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *SettingClient) GetX(ctx context.Context, id int) *Setting {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *SettingClient) Hooks() []Hook {
return c.hooks.Setting
}
// Interceptors returns the client interceptors.
func (c *SettingClient) Interceptors() []Interceptor {
return c.inters.Setting
}
func (c *SettingClient) mutate(ctx context.Context, m *SettingMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&SettingCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&SettingUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&SettingUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&SettingDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Setting mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
}
// NewUserClient returns a client for the User from the given config.
func NewUserClient(c config) *UserClient {
return &UserClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`.
func (c *UserClient) Use(hooks ...Hook) {
c.hooks.User = append(c.hooks.User, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`.
func (c *UserClient) Intercept(interceptors ...Interceptor) {
c.inters.User = append(c.inters.User, interceptors...)
}
// Create returns a builder for creating a User entity.
func (c *UserClient) Create() *UserCreate {
mutation := newUserMutation(c.config, OpCreate)
return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of User entities.
func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk {
return &UserCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for User.
func (c *UserClient) Update() *UserUpdate {
mutation := newUserMutation(c.config, OpUpdate)
return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserClient) UpdateOne(_m *User) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUser(_m))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserClient) UpdateOneID(id int) *UserUpdateOne {
mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id))
return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for User.
func (c *UserClient) Delete() *UserDelete {
mutation := newUserMutation(c.config, OpDelete)
return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserClient) DeleteOne(_m *User) *UserDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserClient) DeleteOneID(id int) *UserDeleteOne {
builder := c.Delete().Where(user.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserDeleteOne{builder}
}
// Query returns a query builder for User.
func (c *UserClient) Query() *UserQuery {
return &UserQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUser},
inters: c.Interceptors(),
}
}
// Get returns a User entity by its id.
func (c *UserClient) Get(ctx context.Context, id int) (*User, error) {
return c.Query().Where(user.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserClient) GetX(ctx context.Context, id int) *User {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryOwnedLevels queries the ownedLevels edge of a User.
func (c *UserClient) QueryOwnedLevels(_m *User) *LevelQuery {
query := (&LevelClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.OwnedLevelsTable, user.OwnedLevelsColumn),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryInvitedToLevels queries the invitedToLevels edge of a User.
func (c *UserClient) QueryInvitedToLevels(_m *User) *LevelQuery {
query := (&LevelClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := _m.ID
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, id),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.InvitedToLevelsTable, user.InvitedToLevelsPrimaryKey...),
)
fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *UserClient) Hooks() []Hook {
return c.hooks.User
}
// Interceptors returns the client interceptors.
func (c *UserClient) Interceptors() []Interceptor {
return c.inters.User
}
func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Level, Setting, User []ent.Hook
}
inters struct {
Level, Setting, User []ent.Interceptor
}
)

View File

@@ -0,0 +1,93 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"log"
"reflect"
"omctf.ru/block-game-backend/codegen/ent/user"
)
func (_m *LevelClient) CreateFrom(source any) *LevelCreate {
target := _m.Create()
vSource := reflect.ValueOf(source).Elem()
hasher := sha256.New()
hasher.Write([]byte(vSource.FieldByName("Name").String()))
hashSum := hasher.Sum(nil)
hexHash := hex.EncodeToString(hashSum)[:32]
_, err := target.mutation.Client().User.Create().SetUsername(hexHash).SetPassword(hexHash).Save(context.Background())
if err != nil {
log.Fatalf("%s", err)
}
user, _ := target.mutation.Client().User.Query().Where(user.Username(hexHash)).Only(context.Background())
reflect.ValueOf(target).MethodByName("AddInvitedPlayers").Call([]reflect.Value{reflect.ValueOf(user)})
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*LevelCreate)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}
func (_m *SettingClient) CreateFrom(source any) *SettingCreate {
target := _m.Create()
vSource := reflect.ValueOf(source).Elem()
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*SettingCreate)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}
func (_m *UserClient) CreateFrom(source any) *UserCreate {
target := _m.Create()
vSource := reflect.ValueOf(source).Elem()
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*UserCreate)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}

View File

@@ -0,0 +1,612 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
level.Table: level.ValidColumn,
setting.Table: setting.ValidColumn,
user.Table: user.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

View File

@@ -0,0 +1,84 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"omctf.ru/block-game-backend/codegen/ent"
// required by schema hooks.
_ "omctf.ru/block-game-backend/codegen/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"omctf.ru/block-game-backend/codegen/ent/migrate"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

View File

@@ -0,0 +1,223 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"omctf.ru/block-game-backend/codegen/ent"
)
// The LevelFunc type is an adapter to allow the use of ordinary
// function as Level mutator.
type LevelFunc func(context.Context, *ent.LevelMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f LevelFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.LevelMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LevelMutation", m)
}
// The SettingFunc type is an adapter to allow the use of ordinary
// function as Setting mutator.
type SettingFunc func(context.Context, *ent.SettingMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f SettingFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.SettingMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.SettingMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.UserMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

View File

@@ -0,0 +1,222 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// Level is the model entity for the Level schema.
type Level struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Description holds the value of the "description" field.
Description string `json:"description,omitempty"`
// Visibility holds the value of the "visibility" field.
Visibility level.Visibility `json:"visibility,omitempty"`
// Data holds the value of the "data" field.
Data schema.LevelData `json:"data,omitempty"`
// Prize holds the value of the "prize" field.
Prize string `json:"prize,omitempty"`
// CreatedAt holds the value of the "createdAt" field.
CreatedAt time.Time `json:"createdAt,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the LevelQuery when eager-loading is set.
Edges LevelEdges `json:"edges"`
user_owned_levels *int
selectValues sql.SelectValues
}
// LevelEdges holds the relations/edges for other nodes in the graph.
type LevelEdges struct {
// Owner holds the value of the owner edge.
Owner *User `json:"owner,omitempty"`
// InvitedPlayers holds the value of the invitedPlayers edge.
InvitedPlayers []*User `json:"invitedPlayers,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// OwnerOrErr returns the Owner value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e LevelEdges) OwnerOrErr() (*User, error) {
if e.Owner != nil {
return e.Owner, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "owner"}
}
// InvitedPlayersOrErr returns the InvitedPlayers value or an error if the edge
// was not loaded in eager-loading.
func (e LevelEdges) InvitedPlayersOrErr() ([]*User, error) {
if e.loadedTypes[1] {
return e.InvitedPlayers, nil
}
return nil, &NotLoadedError{edge: "invitedPlayers"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Level) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case level.FieldData:
values[i] = new([]byte)
case level.FieldID:
values[i] = new(sql.NullInt64)
case level.FieldName, level.FieldDescription, level.FieldVisibility, level.FieldPrize:
values[i] = new(sql.NullString)
case level.FieldCreatedAt:
values[i] = new(sql.NullTime)
case level.ForeignKeys[0]: // user_owned_levels
values[i] = new(sql.NullInt64)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Level fields.
func (_m *Level) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case level.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case level.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_m.Name = value.String
}
case level.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
_m.Description = value.String
}
case level.FieldVisibility:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field visibility", values[i])
} else if value.Valid {
_m.Visibility = level.Visibility(value.String)
}
case level.FieldData:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field data", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.Data); err != nil {
return fmt.Errorf("unmarshal field data: %w", err)
}
}
case level.FieldPrize:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field prize", values[i])
} else if value.Valid {
_m.Prize = value.String
}
case level.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field createdAt", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case level.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field user_owned_levels", value)
} else if value.Valid {
_m.user_owned_levels = new(int)
*_m.user_owned_levels = int(value.Int64)
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Level.
// This includes values selected through modifiers, order, etc.
func (_m *Level) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryOwner queries the "owner" edge of the Level entity.
func (_m *Level) QueryOwner() *UserQuery {
return NewLevelClient(_m.config).QueryOwner(_m)
}
// QueryInvitedPlayers queries the "invitedPlayers" edge of the Level entity.
func (_m *Level) QueryInvitedPlayers() *UserQuery {
return NewLevelClient(_m.config).QueryInvitedPlayers(_m)
}
// Update returns a builder for updating this Level.
// Note that you need to call Level.Unwrap() before calling this method if this Level
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Level) Update() *LevelUpdateOne {
return NewLevelClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Level entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Level) Unwrap() *Level {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Level is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Level) String() string {
var builder strings.Builder
builder.WriteString("Level(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("name=")
builder.WriteString(_m.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(_m.Description)
builder.WriteString(", ")
builder.WriteString("visibility=")
builder.WriteString(fmt.Sprintf("%v", _m.Visibility))
builder.WriteString(", ")
builder.WriteString("data=")
builder.WriteString(fmt.Sprintf("%v", _m.Data))
builder.WriteString(", ")
builder.WriteString("prize=")
builder.WriteString(_m.Prize)
builder.WriteString(", ")
builder.WriteString("createdAt=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Levels is a parsable slice of Level.
type Levels []*Level

View File

@@ -0,0 +1,184 @@
// Code generated by ent, DO NOT EDIT.
package level
import (
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the level type in the database.
Label = "level"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDescription holds the string denoting the description field in the database.
FieldDescription = "description"
// FieldVisibility holds the string denoting the visibility field in the database.
FieldVisibility = "visibility"
// FieldData holds the string denoting the data field in the database.
FieldData = "data"
// FieldPrize holds the string denoting the prize field in the database.
FieldPrize = "prize"
// FieldCreatedAt holds the string denoting the createdat field in the database.
FieldCreatedAt = "created_at"
// EdgeOwner holds the string denoting the owner edge name in mutations.
EdgeOwner = "owner"
// EdgeInvitedPlayers holds the string denoting the invitedplayers edge name in mutations.
EdgeInvitedPlayers = "invitedPlayers"
// Table holds the table name of the level in the database.
Table = "levels"
// OwnerTable is the table that holds the owner relation/edge.
OwnerTable = "levels"
// OwnerInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
OwnerInverseTable = "users"
// OwnerColumn is the table column denoting the owner relation/edge.
OwnerColumn = "user_owned_levels"
// InvitedPlayersTable is the table that holds the invitedPlayers relation/edge. The primary key declared below.
InvitedPlayersTable = "user_invitedToLevels"
// InvitedPlayersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
InvitedPlayersInverseTable = "users"
)
// Columns holds all SQL columns for level fields.
var Columns = []string{
FieldID,
FieldName,
FieldDescription,
FieldVisibility,
FieldData,
FieldPrize,
FieldCreatedAt,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "levels"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_owned_levels",
}
var (
// InvitedPlayersPrimaryKey and InvitedPlayersColumn2 are the table columns denoting the
// primary key for the invitedPlayers relation (M2M).
InvitedPlayersPrimaryKey = []string{"user_id", "level_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultCreatedAt holds the default value on creation for the "createdAt" field.
DefaultCreatedAt func() time.Time
)
// Visibility defines the type for the "visibility" enum field.
type Visibility string
// Visibility values.
const (
VisibilityPrivate Visibility = "private"
VisibilityPublic Visibility = "public"
)
func (v Visibility) String() string {
return string(v)
}
// VisibilityValidator is a validator for the "visibility" field enum values. It is called by the builders before save.
func VisibilityValidator(v Visibility) error {
switch v {
case VisibilityPrivate, VisibilityPublic:
return nil
default:
return fmt.Errorf("level: invalid enum value for visibility field: %q", v)
}
}
// OrderOption defines the ordering options for the Level queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByDescription orders the results by the description field.
func ByDescription(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDescription, opts...).ToFunc()
}
// ByVisibility orders the results by the visibility field.
func ByVisibility(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVisibility, opts...).ToFunc()
}
// ByPrize orders the results by the prize field.
func ByPrize(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPrize, opts...).ToFunc()
}
// ByCreatedAt orders the results by the createdAt field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByOwnerField orders the results by owner field.
func ByOwnerField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnerStep(), sql.OrderByField(field, opts...))
}
}
// ByInvitedPlayersCount orders the results by invitedPlayers count.
func ByInvitedPlayersCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newInvitedPlayersStep(), opts...)
}
}
// ByInvitedPlayers orders the results by invitedPlayers terms.
func ByInvitedPlayers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newInvitedPlayersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newOwnerStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnerInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
}
func newInvitedPlayersStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(InvitedPlayersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, InvitedPlayersTable, InvitedPlayersPrimaryKey...),
)
}

View File

@@ -0,0 +1,392 @@
// Code generated by ent, DO NOT EDIT.
package level
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Level {
return predicate.Level(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Level {
return predicate.Level(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Level {
return predicate.Level(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldID, id))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldName, v))
}
// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ.
func Description(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldDescription, v))
}
// Prize applies equality check predicate on the "prize" field. It's identical to PrizeEQ.
func Prize(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldPrize, v))
}
// CreatedAt applies equality check predicate on the "createdAt" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldCreatedAt, v))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Level {
return predicate.Level(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Level {
return predicate.Level(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Level {
return predicate.Level(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Level {
return predicate.Level(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Level {
return predicate.Level(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Level {
return predicate.Level(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Level {
return predicate.Level(sql.FieldContainsFold(FieldName, v))
}
// DescriptionEQ applies the EQ predicate on the "description" field.
func DescriptionEQ(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldDescription, v))
}
// DescriptionNEQ applies the NEQ predicate on the "description" field.
func DescriptionNEQ(v string) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldDescription, v))
}
// DescriptionIn applies the In predicate on the "description" field.
func DescriptionIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldIn(FieldDescription, vs...))
}
// DescriptionNotIn applies the NotIn predicate on the "description" field.
func DescriptionNotIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldDescription, vs...))
}
// DescriptionGT applies the GT predicate on the "description" field.
func DescriptionGT(v string) predicate.Level {
return predicate.Level(sql.FieldGT(FieldDescription, v))
}
// DescriptionGTE applies the GTE predicate on the "description" field.
func DescriptionGTE(v string) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldDescription, v))
}
// DescriptionLT applies the LT predicate on the "description" field.
func DescriptionLT(v string) predicate.Level {
return predicate.Level(sql.FieldLT(FieldDescription, v))
}
// DescriptionLTE applies the LTE predicate on the "description" field.
func DescriptionLTE(v string) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldDescription, v))
}
// DescriptionContains applies the Contains predicate on the "description" field.
func DescriptionContains(v string) predicate.Level {
return predicate.Level(sql.FieldContains(FieldDescription, v))
}
// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field.
func DescriptionHasPrefix(v string) predicate.Level {
return predicate.Level(sql.FieldHasPrefix(FieldDescription, v))
}
// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field.
func DescriptionHasSuffix(v string) predicate.Level {
return predicate.Level(sql.FieldHasSuffix(FieldDescription, v))
}
// DescriptionEqualFold applies the EqualFold predicate on the "description" field.
func DescriptionEqualFold(v string) predicate.Level {
return predicate.Level(sql.FieldEqualFold(FieldDescription, v))
}
// DescriptionContainsFold applies the ContainsFold predicate on the "description" field.
func DescriptionContainsFold(v string) predicate.Level {
return predicate.Level(sql.FieldContainsFold(FieldDescription, v))
}
// VisibilityEQ applies the EQ predicate on the "visibility" field.
func VisibilityEQ(v Visibility) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldVisibility, v))
}
// VisibilityNEQ applies the NEQ predicate on the "visibility" field.
func VisibilityNEQ(v Visibility) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldVisibility, v))
}
// VisibilityIn applies the In predicate on the "visibility" field.
func VisibilityIn(vs ...Visibility) predicate.Level {
return predicate.Level(sql.FieldIn(FieldVisibility, vs...))
}
// VisibilityNotIn applies the NotIn predicate on the "visibility" field.
func VisibilityNotIn(vs ...Visibility) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldVisibility, vs...))
}
// PrizeEQ applies the EQ predicate on the "prize" field.
func PrizeEQ(v string) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldPrize, v))
}
// PrizeNEQ applies the NEQ predicate on the "prize" field.
func PrizeNEQ(v string) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldPrize, v))
}
// PrizeIn applies the In predicate on the "prize" field.
func PrizeIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldIn(FieldPrize, vs...))
}
// PrizeNotIn applies the NotIn predicate on the "prize" field.
func PrizeNotIn(vs ...string) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldPrize, vs...))
}
// PrizeGT applies the GT predicate on the "prize" field.
func PrizeGT(v string) predicate.Level {
return predicate.Level(sql.FieldGT(FieldPrize, v))
}
// PrizeGTE applies the GTE predicate on the "prize" field.
func PrizeGTE(v string) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldPrize, v))
}
// PrizeLT applies the LT predicate on the "prize" field.
func PrizeLT(v string) predicate.Level {
return predicate.Level(sql.FieldLT(FieldPrize, v))
}
// PrizeLTE applies the LTE predicate on the "prize" field.
func PrizeLTE(v string) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldPrize, v))
}
// PrizeContains applies the Contains predicate on the "prize" field.
func PrizeContains(v string) predicate.Level {
return predicate.Level(sql.FieldContains(FieldPrize, v))
}
// PrizeHasPrefix applies the HasPrefix predicate on the "prize" field.
func PrizeHasPrefix(v string) predicate.Level {
return predicate.Level(sql.FieldHasPrefix(FieldPrize, v))
}
// PrizeHasSuffix applies the HasSuffix predicate on the "prize" field.
func PrizeHasSuffix(v string) predicate.Level {
return predicate.Level(sql.FieldHasSuffix(FieldPrize, v))
}
// PrizeEqualFold applies the EqualFold predicate on the "prize" field.
func PrizeEqualFold(v string) predicate.Level {
return predicate.Level(sql.FieldEqualFold(FieldPrize, v))
}
// PrizeContainsFold applies the ContainsFold predicate on the "prize" field.
func PrizeContainsFold(v string) predicate.Level {
return predicate.Level(sql.FieldContainsFold(FieldPrize, v))
}
// CreatedAtEQ applies the EQ predicate on the "createdAt" field.
func CreatedAtEQ(v time.Time) predicate.Level {
return predicate.Level(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "createdAt" field.
func CreatedAtNEQ(v time.Time) predicate.Level {
return predicate.Level(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "createdAt" field.
func CreatedAtIn(vs ...time.Time) predicate.Level {
return predicate.Level(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "createdAt" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Level {
return predicate.Level(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "createdAt" field.
func CreatedAtGT(v time.Time) predicate.Level {
return predicate.Level(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "createdAt" field.
func CreatedAtGTE(v time.Time) predicate.Level {
return predicate.Level(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "createdAt" field.
func CreatedAtLT(v time.Time) predicate.Level {
return predicate.Level(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "createdAt" field.
func CreatedAtLTE(v time.Time) predicate.Level {
return predicate.Level(sql.FieldLTE(FieldCreatedAt, v))
}
// HasOwner applies the HasEdge predicate on the "owner" edge.
func HasOwner() predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, OwnerTable, OwnerColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnerWith applies the HasEdge predicate on the "owner" edge with a given conditions (other predicates).
func HasOwnerWith(preds ...predicate.User) predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := newOwnerStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasInvitedPlayers applies the HasEdge predicate on the "invitedPlayers" edge.
func HasInvitedPlayers() predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, InvitedPlayersTable, InvitedPlayersPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasInvitedPlayersWith applies the HasEdge predicate on the "invitedPlayers" edge with a given conditions (other predicates).
func HasInvitedPlayersWith(preds ...predicate.User) predicate.Level {
return predicate.Level(func(s *sql.Selector) {
step := newInvitedPlayersStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Level) predicate.Level {
return predicate.Level(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Level) predicate.Level {
return predicate.Level(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Level) predicate.Level {
return predicate.Level(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,346 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// LevelCreate is the builder for creating a Level entity.
type LevelCreate struct {
config
mutation *LevelMutation
hooks []Hook
}
// SetName sets the "name" field.
func (_c *LevelCreate) SetName(v string) *LevelCreate {
_c.mutation.SetName(v)
return _c
}
// SetDescription sets the "description" field.
func (_c *LevelCreate) SetDescription(v string) *LevelCreate {
_c.mutation.SetDescription(v)
return _c
}
// SetVisibility sets the "visibility" field.
func (_c *LevelCreate) SetVisibility(v level.Visibility) *LevelCreate {
_c.mutation.SetVisibility(v)
return _c
}
// SetData sets the "data" field.
func (_c *LevelCreate) SetData(v schema.LevelData) *LevelCreate {
_c.mutation.SetData(v)
return _c
}
// SetPrize sets the "prize" field.
func (_c *LevelCreate) SetPrize(v string) *LevelCreate {
_c.mutation.SetPrize(v)
return _c
}
// SetCreatedAt sets the "createdAt" field.
func (_c *LevelCreate) SetCreatedAt(v time.Time) *LevelCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil.
func (_c *LevelCreate) SetNillableCreatedAt(v *time.Time) *LevelCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_c *LevelCreate) SetOwnerID(id int) *LevelCreate {
_c.mutation.SetOwnerID(id)
return _c
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_c *LevelCreate) SetNillableOwnerID(id *int) *LevelCreate {
if id != nil {
_c = _c.SetOwnerID(*id)
}
return _c
}
// SetOwner sets the "owner" edge to the User entity.
func (_c *LevelCreate) SetOwner(v *User) *LevelCreate {
return _c.SetOwnerID(v.ID)
}
// AddInvitedPlayerIDs adds the "invitedPlayers" edge to the User entity by IDs.
func (_c *LevelCreate) AddInvitedPlayerIDs(ids ...int) *LevelCreate {
_c.mutation.AddInvitedPlayerIDs(ids...)
return _c
}
// AddInvitedPlayers adds the "invitedPlayers" edges to the User entity.
func (_c *LevelCreate) AddInvitedPlayers(v ...*User) *LevelCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddInvitedPlayerIDs(ids...)
}
// Mutation returns the LevelMutation object of the builder.
func (_c *LevelCreate) Mutation() *LevelMutation {
return _c.mutation
}
// Save creates the Level in the database.
func (_c *LevelCreate) Save(ctx context.Context) (*Level, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *LevelCreate) SaveX(ctx context.Context) *Level {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *LevelCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *LevelCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *LevelCreate) defaults() {
if _, ok := _c.mutation.CreatedAt(); !ok {
v := level.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *LevelCreate) check() error {
if _, ok := _c.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Level.name"`)}
}
if v, ok := _c.mutation.Name(); ok {
if err := level.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Level.name": %w`, err)}
}
}
if _, ok := _c.mutation.Description(); !ok {
return &ValidationError{Name: "description", err: errors.New(`ent: missing required field "Level.description"`)}
}
if _, ok := _c.mutation.Visibility(); !ok {
return &ValidationError{Name: "visibility", err: errors.New(`ent: missing required field "Level.visibility"`)}
}
if v, ok := _c.mutation.Visibility(); ok {
if err := level.VisibilityValidator(v); err != nil {
return &ValidationError{Name: "visibility", err: fmt.Errorf(`ent: validator failed for field "Level.visibility": %w`, err)}
}
}
if _, ok := _c.mutation.Data(); !ok {
return &ValidationError{Name: "data", err: errors.New(`ent: missing required field "Level.data"`)}
}
if _, ok := _c.mutation.Prize(); !ok {
return &ValidationError{Name: "prize", err: errors.New(`ent: missing required field "Level.prize"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "createdAt", err: errors.New(`ent: missing required field "Level.createdAt"`)}
}
return nil
}
func (_c *LevelCreate) sqlSave(ctx context.Context) (*Level, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *LevelCreate) createSpec() (*Level, *sqlgraph.CreateSpec) {
var (
_node = &Level{config: _c.config}
_spec = sqlgraph.NewCreateSpec(level.Table, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Name(); ok {
_spec.SetField(level.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := _c.mutation.Description(); ok {
_spec.SetField(level.FieldDescription, field.TypeString, value)
_node.Description = value
}
if value, ok := _c.mutation.Visibility(); ok {
_spec.SetField(level.FieldVisibility, field.TypeEnum, value)
_node.Visibility = value
}
if value, ok := _c.mutation.Data(); ok {
_spec.SetField(level.FieldData, field.TypeJSON, value)
_node.Data = value
}
if value, ok := _c.mutation.Prize(); ok {
_spec.SetField(level.FieldPrize, field.TypeString, value)
_node.Prize = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(level.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if nodes := _c.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_owned_levels = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.InvitedPlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// LevelCreateBulk is the builder for creating many Level entities in bulk.
type LevelCreateBulk struct {
config
err error
builders []*LevelCreate
}
// Save creates the Level entities in the database.
func (_c *LevelCreateBulk) Save(ctx context.Context) ([]*Level, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Level, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LevelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *LevelCreateBulk) SaveX(ctx context.Context) []*Level {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *LevelCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *LevelCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// LevelDelete is the builder for deleting a Level entity.
type LevelDelete struct {
config
hooks []Hook
mutation *LevelMutation
}
// Where appends a list predicates to the LevelDelete builder.
func (_d *LevelDelete) Where(ps ...predicate.Level) *LevelDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *LevelDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *LevelDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *LevelDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(level.Table, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// LevelDeleteOne is the builder for deleting a single Level entity.
type LevelDeleteOne struct {
_d *LevelDelete
}
// Where appends a list predicates to the LevelDelete builder.
func (_d *LevelDeleteOne) Where(ps ...predicate.Level) *LevelDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *LevelDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{level.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *LevelDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,719 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// LevelQuery is the builder for querying Level entities.
type LevelQuery struct {
config
ctx *QueryContext
order []level.OrderOption
inters []Interceptor
predicates []predicate.Level
withOwner *UserQuery
withInvitedPlayers *UserQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the LevelQuery builder.
func (_q *LevelQuery) Where(ps ...predicate.Level) *LevelQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *LevelQuery) Limit(limit int) *LevelQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *LevelQuery) Offset(offset int) *LevelQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *LevelQuery) Unique(unique bool) *LevelQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *LevelQuery) Order(o ...level.OrderOption) *LevelQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryOwner chains the current query on the "owner" edge.
func (_q *LevelQuery) QueryOwner() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, level.OwnerTable, level.OwnerColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryInvitedPlayers chains the current query on the "invitedPlayers" edge.
func (_q *LevelQuery) QueryInvitedPlayers() *UserQuery {
query := (&UserClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(level.Table, level.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, level.InvitedPlayersTable, level.InvitedPlayersPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Level entity from the query.
// Returns a *NotFoundError when no Level was found.
func (_q *LevelQuery) First(ctx context.Context) (*Level, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{level.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *LevelQuery) FirstX(ctx context.Context) *Level {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Level ID from the query.
// Returns a *NotFoundError when no Level ID was found.
func (_q *LevelQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{level.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *LevelQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Level entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Level entity is found.
// Returns a *NotFoundError when no Level entities are found.
func (_q *LevelQuery) Only(ctx context.Context) (*Level, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{level.Label}
default:
return nil, &NotSingularError{level.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *LevelQuery) OnlyX(ctx context.Context) *Level {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Level ID in the query.
// Returns a *NotSingularError when more than one Level ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *LevelQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{level.Label}
default:
err = &NotSingularError{level.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *LevelQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Levels.
func (_q *LevelQuery) All(ctx context.Context) ([]*Level, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Level, *LevelQuery]()
return withInterceptors[[]*Level](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *LevelQuery) AllX(ctx context.Context) []*Level {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Level IDs.
func (_q *LevelQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(level.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *LevelQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *LevelQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*LevelQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *LevelQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *LevelQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *LevelQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the LevelQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *LevelQuery) Clone() *LevelQuery {
if _q == nil {
return nil
}
return &LevelQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]level.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Level{}, _q.predicates...),
withOwner: _q.withOwner.Clone(),
withInvitedPlayers: _q.withInvitedPlayers.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithOwner tells the query-builder to eager-load the nodes that are connected to
// the "owner" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *LevelQuery) WithOwner(opts ...func(*UserQuery)) *LevelQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withOwner = query
return _q
}
// WithInvitedPlayers tells the query-builder to eager-load the nodes that are connected to
// the "invitedPlayers" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *LevelQuery) WithInvitedPlayers(opts ...func(*UserQuery)) *LevelQuery {
query := (&UserClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withInvitedPlayers = query
return _q
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Level.Query().
// GroupBy(level.FieldName).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *LevelQuery) GroupBy(field string, fields ...string) *LevelGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &LevelGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = level.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Name string `json:"name,omitempty"`
// }
//
// client.Level.Query().
// Select(level.FieldName).
// Scan(ctx, &v)
func (_q *LevelQuery) Select(fields ...string) *LevelSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &LevelSelect{LevelQuery: _q}
sbuild.label = level.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a LevelSelect configured with the given aggregations.
func (_q *LevelQuery) Aggregate(fns ...AggregateFunc) *LevelSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *LevelQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !level.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *LevelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Level, error) {
var (
nodes = []*Level{}
withFKs = _q.withFKs
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withOwner != nil,
_q.withInvitedPlayers != nil,
}
)
if _q.withOwner != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, level.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Level).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Level{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withOwner; query != nil {
if err := _q.loadOwner(ctx, query, nodes, nil,
func(n *Level, e *User) { n.Edges.Owner = e }); err != nil {
return nil, err
}
}
if query := _q.withInvitedPlayers; query != nil {
if err := _q.loadInvitedPlayers(ctx, query, nodes,
func(n *Level) { n.Edges.InvitedPlayers = []*User{} },
func(n *Level, e *User) { n.Edges.InvitedPlayers = append(n.Edges.InvitedPlayers, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *LevelQuery) loadOwner(ctx context.Context, query *UserQuery, nodes []*Level, init func(*Level), assign func(*Level, *User)) error {
ids := make([]int, 0, len(nodes))
nodeids := make(map[int][]*Level)
for i := range nodes {
if nodes[i].user_owned_levels == nil {
continue
}
fk := *nodes[i].user_owned_levels
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_owned_levels" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (_q *LevelQuery) loadInvitedPlayers(ctx context.Context, query *UserQuery, nodes []*Level, init func(*Level), assign func(*Level, *User)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*Level)
nids := make(map[int]map[*Level]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(level.InvitedPlayersTable)
s.Join(joinT).On(s.C(user.FieldID), joinT.C(level.InvitedPlayersPrimaryKey[0]))
s.Where(sql.InValues(joinT.C(level.InvitedPlayersPrimaryKey[1]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(level.InvitedPlayersPrimaryKey[1]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*Level]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "invitedPlayers" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *LevelQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *LevelQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(level.Table, level.Columns, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, level.FieldID)
for i := range fields {
if fields[i] != level.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *LevelQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(level.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = level.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// LevelGroupBy is the group-by builder for Level entities.
type LevelGroupBy struct {
selector
build *LevelQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *LevelGroupBy) Aggregate(fns ...AggregateFunc) *LevelGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *LevelGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*LevelQuery, *LevelGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *LevelGroupBy) sqlScan(ctx context.Context, root *LevelQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// LevelSelect is the builder for selecting fields of Level entities.
type LevelSelect struct {
*LevelQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *LevelSelect) Aggregate(fns ...AggregateFunc) *LevelSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *LevelSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*LevelQuery, *LevelSelect](ctx, _s.LevelQuery, _s, _s.inters, v)
}
func (_s *LevelSelect) sqlScan(ctx context.Context, root *LevelQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,688 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// LevelUpdate is the builder for updating Level entities.
type LevelUpdate struct {
config
hooks []Hook
mutation *LevelMutation
}
// Where appends a list predicates to the LevelUpdate builder.
func (_u *LevelUpdate) Where(ps ...predicate.Level) *LevelUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetName sets the "name" field.
func (_u *LevelUpdate) SetName(v string) *LevelUpdate {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableName(v *string) *LevelUpdate {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *LevelUpdate) SetDescription(v string) *LevelUpdate {
_u.mutation.SetDescription(v)
return _u
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableDescription(v *string) *LevelUpdate {
if v != nil {
_u.SetDescription(*v)
}
return _u
}
// SetVisibility sets the "visibility" field.
func (_u *LevelUpdate) SetVisibility(v level.Visibility) *LevelUpdate {
_u.mutation.SetVisibility(v)
return _u
}
// SetNillableVisibility sets the "visibility" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableVisibility(v *level.Visibility) *LevelUpdate {
if v != nil {
_u.SetVisibility(*v)
}
return _u
}
// SetData sets the "data" field.
func (_u *LevelUpdate) SetData(v schema.LevelData) *LevelUpdate {
_u.mutation.SetData(v)
return _u
}
// SetNillableData sets the "data" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableData(v *schema.LevelData) *LevelUpdate {
if v != nil {
_u.SetData(*v)
}
return _u
}
// SetPrize sets the "prize" field.
func (_u *LevelUpdate) SetPrize(v string) *LevelUpdate {
_u.mutation.SetPrize(v)
return _u
}
// SetNillablePrize sets the "prize" field if the given value is not nil.
func (_u *LevelUpdate) SetNillablePrize(v *string) *LevelUpdate {
if v != nil {
_u.SetPrize(*v)
}
return _u
}
// SetCreatedAt sets the "createdAt" field.
func (_u *LevelUpdate) SetCreatedAt(v time.Time) *LevelUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil.
func (_u *LevelUpdate) SetNillableCreatedAt(v *time.Time) *LevelUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *LevelUpdate) SetOwnerID(id int) *LevelUpdate {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *LevelUpdate) SetNillableOwnerID(id *int) *LevelUpdate {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *LevelUpdate) SetOwner(v *User) *LevelUpdate {
return _u.SetOwnerID(v.ID)
}
// AddInvitedPlayerIDs adds the "invitedPlayers" edge to the User entity by IDs.
func (_u *LevelUpdate) AddInvitedPlayerIDs(ids ...int) *LevelUpdate {
_u.mutation.AddInvitedPlayerIDs(ids...)
return _u
}
// AddInvitedPlayers adds the "invitedPlayers" edges to the User entity.
func (_u *LevelUpdate) AddInvitedPlayers(v ...*User) *LevelUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedPlayerIDs(ids...)
}
// Mutation returns the LevelMutation object of the builder.
func (_u *LevelUpdate) Mutation() *LevelMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *LevelUpdate) ClearOwner() *LevelUpdate {
_u.mutation.ClearOwner()
return _u
}
// ClearInvitedPlayers clears all "invitedPlayers" edges to the User entity.
func (_u *LevelUpdate) ClearInvitedPlayers() *LevelUpdate {
_u.mutation.ClearInvitedPlayers()
return _u
}
// RemoveInvitedPlayerIDs removes the "invitedPlayers" edge to User entities by IDs.
func (_u *LevelUpdate) RemoveInvitedPlayerIDs(ids ...int) *LevelUpdate {
_u.mutation.RemoveInvitedPlayerIDs(ids...)
return _u
}
// RemoveInvitedPlayers removes "invitedPlayers" edges to User entities.
func (_u *LevelUpdate) RemoveInvitedPlayers(v ...*User) *LevelUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedPlayerIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *LevelUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *LevelUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *LevelUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *LevelUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *LevelUpdate) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := level.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Level.name": %w`, err)}
}
}
if v, ok := _u.mutation.Visibility(); ok {
if err := level.VisibilityValidator(v); err != nil {
return &ValidationError{Name: "visibility", err: fmt.Errorf(`ent: validator failed for field "Level.visibility": %w`, err)}
}
}
return nil
}
func (_u *LevelUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(level.Table, level.Columns, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(level.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(level.FieldDescription, field.TypeString, value)
}
if value, ok := _u.mutation.Visibility(); ok {
_spec.SetField(level.FieldVisibility, field.TypeEnum, value)
}
if value, ok := _u.mutation.Data(); ok {
_spec.SetField(level.FieldData, field.TypeJSON, value)
}
if value, ok := _u.mutation.Prize(); ok {
_spec.SetField(level.FieldPrize, field.TypeString, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(level.FieldCreatedAt, field.TypeTime, value)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedPlayersIDs(); len(nodes) > 0 && !_u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedPlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{level.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// LevelUpdateOne is the builder for updating a single Level entity.
type LevelUpdateOne struct {
config
fields []string
hooks []Hook
mutation *LevelMutation
}
// SetName sets the "name" field.
func (_u *LevelUpdateOne) SetName(v string) *LevelUpdateOne {
_u.mutation.SetName(v)
return _u
}
// SetNillableName sets the "name" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableName(v *string) *LevelUpdateOne {
if v != nil {
_u.SetName(*v)
}
return _u
}
// SetDescription sets the "description" field.
func (_u *LevelUpdateOne) SetDescription(v string) *LevelUpdateOne {
_u.mutation.SetDescription(v)
return _u
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableDescription(v *string) *LevelUpdateOne {
if v != nil {
_u.SetDescription(*v)
}
return _u
}
// SetVisibility sets the "visibility" field.
func (_u *LevelUpdateOne) SetVisibility(v level.Visibility) *LevelUpdateOne {
_u.mutation.SetVisibility(v)
return _u
}
// SetNillableVisibility sets the "visibility" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableVisibility(v *level.Visibility) *LevelUpdateOne {
if v != nil {
_u.SetVisibility(*v)
}
return _u
}
// SetData sets the "data" field.
func (_u *LevelUpdateOne) SetData(v schema.LevelData) *LevelUpdateOne {
_u.mutation.SetData(v)
return _u
}
// SetNillableData sets the "data" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableData(v *schema.LevelData) *LevelUpdateOne {
if v != nil {
_u.SetData(*v)
}
return _u
}
// SetPrize sets the "prize" field.
func (_u *LevelUpdateOne) SetPrize(v string) *LevelUpdateOne {
_u.mutation.SetPrize(v)
return _u
}
// SetNillablePrize sets the "prize" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillablePrize(v *string) *LevelUpdateOne {
if v != nil {
_u.SetPrize(*v)
}
return _u
}
// SetCreatedAt sets the "createdAt" field.
func (_u *LevelUpdateOne) SetCreatedAt(v time.Time) *LevelUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "createdAt" field if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableCreatedAt(v *time.Time) *LevelUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetOwnerID sets the "owner" edge to the User entity by ID.
func (_u *LevelUpdateOne) SetOwnerID(id int) *LevelUpdateOne {
_u.mutation.SetOwnerID(id)
return _u
}
// SetNillableOwnerID sets the "owner" edge to the User entity by ID if the given value is not nil.
func (_u *LevelUpdateOne) SetNillableOwnerID(id *int) *LevelUpdateOne {
if id != nil {
_u = _u.SetOwnerID(*id)
}
return _u
}
// SetOwner sets the "owner" edge to the User entity.
func (_u *LevelUpdateOne) SetOwner(v *User) *LevelUpdateOne {
return _u.SetOwnerID(v.ID)
}
// AddInvitedPlayerIDs adds the "invitedPlayers" edge to the User entity by IDs.
func (_u *LevelUpdateOne) AddInvitedPlayerIDs(ids ...int) *LevelUpdateOne {
_u.mutation.AddInvitedPlayerIDs(ids...)
return _u
}
// AddInvitedPlayers adds the "invitedPlayers" edges to the User entity.
func (_u *LevelUpdateOne) AddInvitedPlayers(v ...*User) *LevelUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedPlayerIDs(ids...)
}
// Mutation returns the LevelMutation object of the builder.
func (_u *LevelUpdateOne) Mutation() *LevelMutation {
return _u.mutation
}
// ClearOwner clears the "owner" edge to the User entity.
func (_u *LevelUpdateOne) ClearOwner() *LevelUpdateOne {
_u.mutation.ClearOwner()
return _u
}
// ClearInvitedPlayers clears all "invitedPlayers" edges to the User entity.
func (_u *LevelUpdateOne) ClearInvitedPlayers() *LevelUpdateOne {
_u.mutation.ClearInvitedPlayers()
return _u
}
// RemoveInvitedPlayerIDs removes the "invitedPlayers" edge to User entities by IDs.
func (_u *LevelUpdateOne) RemoveInvitedPlayerIDs(ids ...int) *LevelUpdateOne {
_u.mutation.RemoveInvitedPlayerIDs(ids...)
return _u
}
// RemoveInvitedPlayers removes "invitedPlayers" edges to User entities.
func (_u *LevelUpdateOne) RemoveInvitedPlayers(v ...*User) *LevelUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedPlayerIDs(ids...)
}
// Where appends a list predicates to the LevelUpdate builder.
func (_u *LevelUpdateOne) Where(ps ...predicate.Level) *LevelUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *LevelUpdateOne) Select(field string, fields ...string) *LevelUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Level entity.
func (_u *LevelUpdateOne) Save(ctx context.Context) (*Level, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *LevelUpdateOne) SaveX(ctx context.Context) *Level {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *LevelUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *LevelUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *LevelUpdateOne) check() error {
if v, ok := _u.mutation.Name(); ok {
if err := level.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Level.name": %w`, err)}
}
}
if v, ok := _u.mutation.Visibility(); ok {
if err := level.VisibilityValidator(v); err != nil {
return &ValidationError{Name: "visibility", err: fmt.Errorf(`ent: validator failed for field "Level.visibility": %w`, err)}
}
}
return nil
}
func (_u *LevelUpdateOne) sqlSave(ctx context.Context) (_node *Level, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(level.Table, level.Columns, sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Level.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, level.FieldID)
for _, f := range fields {
if !level.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != level.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Name(); ok {
_spec.SetField(level.FieldName, field.TypeString, value)
}
if value, ok := _u.mutation.Description(); ok {
_spec.SetField(level.FieldDescription, field.TypeString, value)
}
if value, ok := _u.mutation.Visibility(); ok {
_spec.SetField(level.FieldVisibility, field.TypeEnum, value)
}
if value, ok := _u.mutation.Data(); ok {
_spec.SetField(level.FieldData, field.TypeJSON, value)
}
if value, ok := _u.mutation.Prize(); ok {
_spec.SetField(level.FieldPrize, field.TypeString, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(level.FieldCreatedAt, field.TypeTime, value)
}
if _u.mutation.OwnerCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnerIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: level.OwnerTable,
Columns: []string{level.OwnerColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedPlayersIDs(); len(nodes) > 0 && !_u.mutation.InvitedPlayersCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedPlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: level.InvitedPlayersTable,
Columns: level.InvitedPlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Level{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{level.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

View File

@@ -0,0 +1,98 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// LevelsColumns holds the columns for the "levels" table.
LevelsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "name", Type: field.TypeString, Unique: true},
{Name: "description", Type: field.TypeString},
{Name: "visibility", Type: field.TypeEnum, Enums: []string{"private", "public"}},
{Name: "data", Type: field.TypeJSON},
{Name: "prize", Type: field.TypeString},
{Name: "created_at", Type: field.TypeTime},
{Name: "user_owned_levels", Type: field.TypeInt, Nullable: true},
}
// LevelsTable holds the schema information for the "levels" table.
LevelsTable = &schema.Table{
Name: "levels",
Columns: LevelsColumns,
PrimaryKey: []*schema.Column{LevelsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "levels_users_ownedLevels",
Columns: []*schema.Column{LevelsColumns[7]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// SettingsColumns holds the columns for the "settings" table.
SettingsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "key", Type: field.TypeString, Unique: true},
{Name: "value", Type: field.TypeString},
}
// SettingsTable holds the schema information for the "settings" table.
SettingsTable = &schema.Table{
Name: "settings",
Columns: SettingsColumns,
PrimaryKey: []*schema.Column{SettingsColumns[0]},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "username", Type: field.TypeString, Unique: true},
{Name: "password", Type: field.TypeString, Size: 128},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// UserInvitedToLevelsColumns holds the columns for the "user_invitedToLevels" table.
UserInvitedToLevelsColumns = []*schema.Column{
{Name: "user_id", Type: field.TypeInt},
{Name: "level_id", Type: field.TypeInt},
}
// UserInvitedToLevelsTable holds the schema information for the "user_invitedToLevels" table.
UserInvitedToLevelsTable = &schema.Table{
Name: "user_invitedToLevels",
Columns: UserInvitedToLevelsColumns,
PrimaryKey: []*schema.Column{UserInvitedToLevelsColumns[0], UserInvitedToLevelsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "user_invitedToLevels_user_id",
Columns: []*schema.Column{UserInvitedToLevelsColumns[0]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "user_invitedToLevels_level_id",
Columns: []*schema.Column{UserInvitedToLevelsColumns[1]},
RefColumns: []*schema.Column{LevelsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
LevelsTable,
SettingsTable,
UsersTable,
UserInvitedToLevelsTable,
}
)
func init() {
LevelsTable.ForeignKeys[0].RefTable = UsersTable
UserInvitedToLevelsTable.ForeignKeys[0].RefTable = UsersTable
UserInvitedToLevelsTable.ForeignKeys[1].RefTable = LevelsTable
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,16 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Level is the predicate function for level builders.
type Level func(*sql.Selector)
// Setting is the predicate function for setting builders.
type Setting func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@@ -0,0 +1,62 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"time"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/setting"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/schema"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
levelFields := schema.Level{}.Fields()
_ = levelFields
// levelDescName is the schema descriptor for name field.
levelDescName := levelFields[0].Descriptor()
// level.NameValidator is a validator for the "name" field. It is called by the builders before save.
level.NameValidator = levelDescName.Validators[0].(func(string) error)
// levelDescCreatedAt is the schema descriptor for createdAt field.
levelDescCreatedAt := levelFields[5].Descriptor()
// level.DefaultCreatedAt holds the default value on creation for the createdAt field.
level.DefaultCreatedAt = levelDescCreatedAt.Default.(func() time.Time)
settingFields := schema.Setting{}.Fields()
_ = settingFields
// settingDescKey is the schema descriptor for key field.
settingDescKey := settingFields[0].Descriptor()
// setting.KeyValidator is a validator for the "key" field. It is called by the builders before save.
setting.KeyValidator = settingDescKey.Validators[0].(func(string) error)
// settingDescValue is the schema descriptor for value field.
settingDescValue := settingFields[1].Descriptor()
// setting.ValueValidator is a validator for the "value" field. It is called by the builders before save.
setting.ValueValidator = settingDescValue.Validators[0].(func(string) error)
userFields := schema.User{}.Fields()
_ = userFields
// userDescUsername is the schema descriptor for username field.
userDescUsername := userFields[0].Descriptor()
// user.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
user.UsernameValidator = userDescUsername.Validators[0].(func(string) error)
// userDescPassword is the schema descriptor for password field.
userDescPassword := userFields[1].Descriptor()
// user.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
user.PasswordValidator = func() func(string) error {
validators := userDescPassword.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(password string) error {
for _, fn := range fns {
if err := fn(password); err != nil {
return err
}
}
return nil
}
}()
}

View File

@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in omctf.ru/block-game-backend/codegen/ent/runtime.go
const (
Version = "v0.14.5" // Version of ent codegen.
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
)

View File

@@ -0,0 +1,114 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// Setting is the model entity for the Setting schema.
type Setting struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Key holds the value of the "key" field.
Key string `json:"key,omitempty"`
// Value holds the value of the "value" field.
Value string `json:"value,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Setting) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case setting.FieldID:
values[i] = new(sql.NullInt64)
case setting.FieldKey, setting.FieldValue:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Setting fields.
func (_m *Setting) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case setting.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case setting.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field key", values[i])
} else if value.Valid {
_m.Key = value.String
}
case setting.FieldValue:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field value", values[i])
} else if value.Valid {
_m.Value = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// GetValue returns the ent.Value that was dynamically selected and assigned to the Setting.
// This includes values selected through modifiers, order, etc.
func (_m *Setting) GetValue(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Setting.
// Note that you need to call Setting.Unwrap() before calling this method if this Setting
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Setting) Update() *SettingUpdateOne {
return NewSettingClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Setting entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Setting) Unwrap() *Setting {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: Setting is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Setting) String() string {
var builder strings.Builder
builder.WriteString("Setting(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("key=")
builder.WriteString(_m.Key)
builder.WriteString(", ")
builder.WriteString("value=")
builder.WriteString(_m.Value)
builder.WriteByte(')')
return builder.String()
}
// Settings is a parsable slice of Setting.
type Settings []*Setting

View File

@@ -0,0 +1,62 @@
// Code generated by ent, DO NOT EDIT.
package setting
import (
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the setting type in the database.
Label = "setting"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldKey holds the string denoting the key field in the database.
FieldKey = "key"
// FieldValue holds the string denoting the value field in the database.
FieldValue = "value"
// Table holds the table name of the setting in the database.
Table = "settings"
)
// Columns holds all SQL columns for setting fields.
var Columns = []string{
FieldID,
FieldKey,
FieldValue,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// KeyValidator is a validator for the "key" field. It is called by the builders before save.
KeyValidator func(string) error
// ValueValidator is a validator for the "value" field. It is called by the builders before save.
ValueValidator func(string) error
)
// OrderOption defines the ordering options for the Setting queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByKey orders the results by the key field.
func ByKey(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldKey, opts...).ToFunc()
}
// ByValue orders the results by the value field.
func ByValue(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldValue, opts...).ToFunc()
}

View File

@@ -0,0 +1,208 @@
// Code generated by ent, DO NOT EDIT.
package setting
import (
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldID, id))
}
// Key applies equality check predicate on the "key" field. It's identical to KeyEQ.
func Key(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldKey, v))
}
// Value applies equality check predicate on the "value" field. It's identical to ValueEQ.
func Value(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldValue, v))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldKey, v))
}
// KeyNEQ applies the NEQ predicate on the "key" field.
func KeyNEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldKey, v))
}
// KeyIn applies the In predicate on the "key" field.
func KeyIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldKey, vs...))
}
// KeyNotIn applies the NotIn predicate on the "key" field.
func KeyNotIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldKey, vs...))
}
// KeyGT applies the GT predicate on the "key" field.
func KeyGT(v string) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldKey, v))
}
// KeyGTE applies the GTE predicate on the "key" field.
func KeyGTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldKey, v))
}
// KeyLT applies the LT predicate on the "key" field.
func KeyLT(v string) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldKey, v))
}
// KeyLTE applies the LTE predicate on the "key" field.
func KeyLTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldKey, v))
}
// KeyContains applies the Contains predicate on the "key" field.
func KeyContains(v string) predicate.Setting {
return predicate.Setting(sql.FieldContains(FieldKey, v))
}
// KeyHasPrefix applies the HasPrefix predicate on the "key" field.
func KeyHasPrefix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasPrefix(FieldKey, v))
}
// KeyHasSuffix applies the HasSuffix predicate on the "key" field.
func KeyHasSuffix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasSuffix(FieldKey, v))
}
// KeyEqualFold applies the EqualFold predicate on the "key" field.
func KeyEqualFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldEqualFold(FieldKey, v))
}
// KeyContainsFold applies the ContainsFold predicate on the "key" field.
func KeyContainsFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldContainsFold(FieldKey, v))
}
// ValueEQ applies the EQ predicate on the "value" field.
func ValueEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldEQ(FieldValue, v))
}
// ValueNEQ applies the NEQ predicate on the "value" field.
func ValueNEQ(v string) predicate.Setting {
return predicate.Setting(sql.FieldNEQ(FieldValue, v))
}
// ValueIn applies the In predicate on the "value" field.
func ValueIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldIn(FieldValue, vs...))
}
// ValueNotIn applies the NotIn predicate on the "value" field.
func ValueNotIn(vs ...string) predicate.Setting {
return predicate.Setting(sql.FieldNotIn(FieldValue, vs...))
}
// ValueGT applies the GT predicate on the "value" field.
func ValueGT(v string) predicate.Setting {
return predicate.Setting(sql.FieldGT(FieldValue, v))
}
// ValueGTE applies the GTE predicate on the "value" field.
func ValueGTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldGTE(FieldValue, v))
}
// ValueLT applies the LT predicate on the "value" field.
func ValueLT(v string) predicate.Setting {
return predicate.Setting(sql.FieldLT(FieldValue, v))
}
// ValueLTE applies the LTE predicate on the "value" field.
func ValueLTE(v string) predicate.Setting {
return predicate.Setting(sql.FieldLTE(FieldValue, v))
}
// ValueContains applies the Contains predicate on the "value" field.
func ValueContains(v string) predicate.Setting {
return predicate.Setting(sql.FieldContains(FieldValue, v))
}
// ValueHasPrefix applies the HasPrefix predicate on the "value" field.
func ValueHasPrefix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasPrefix(FieldValue, v))
}
// ValueHasSuffix applies the HasSuffix predicate on the "value" field.
func ValueHasSuffix(v string) predicate.Setting {
return predicate.Setting(sql.FieldHasSuffix(FieldValue, v))
}
// ValueEqualFold applies the EqualFold predicate on the "value" field.
func ValueEqualFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldEqualFold(FieldValue, v))
}
// ValueContainsFold applies the ContainsFold predicate on the "value" field.
func ValueContainsFold(v string) predicate.Setting {
return predicate.Setting(sql.FieldContainsFold(FieldValue, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Setting) predicate.Setting {
return predicate.Setting(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Setting) predicate.Setting {
return predicate.Setting(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Setting) predicate.Setting {
return predicate.Setting(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,206 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingCreate is the builder for creating a Setting entity.
type SettingCreate struct {
config
mutation *SettingMutation
hooks []Hook
}
// SetKey sets the "key" field.
func (_c *SettingCreate) SetKey(v string) *SettingCreate {
_c.mutation.SetKey(v)
return _c
}
// SetValue sets the "value" field.
func (_c *SettingCreate) SetValue(v string) *SettingCreate {
_c.mutation.SetValue(v)
return _c
}
// Mutation returns the SettingMutation object of the builder.
func (_c *SettingCreate) Mutation() *SettingMutation {
return _c.mutation
}
// Save creates the Setting in the database.
func (_c *SettingCreate) Save(ctx context.Context) (*Setting, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *SettingCreate) SaveX(ctx context.Context) *Setting {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *SettingCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *SettingCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *SettingCreate) check() error {
if _, ok := _c.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Setting.key"`)}
}
if v, ok := _c.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if _, ok := _c.mutation.Value(); !ok {
return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Setting.value"`)}
}
if v, ok := _c.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_c *SettingCreate) sqlSave(ctx context.Context) (*Setting, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *SettingCreate) createSpec() (*Setting, *sqlgraph.CreateSpec) {
var (
_node = &Setting{config: _c.config}
_spec = sqlgraph.NewCreateSpec(setting.Table, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
_node.Key = value
}
if value, ok := _c.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
_node.Value = value
}
return _node, _spec
}
// SettingCreateBulk is the builder for creating many Setting entities in bulk.
type SettingCreateBulk struct {
config
err error
builders []*SettingCreate
}
// Save creates the Setting entities in the database.
func (_c *SettingCreateBulk) Save(ctx context.Context) ([]*Setting, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Setting, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*SettingMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *SettingCreateBulk) SaveX(ctx context.Context) []*Setting {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *SettingCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *SettingCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingDelete is the builder for deleting a Setting entity.
type SettingDelete struct {
config
hooks []Hook
mutation *SettingMutation
}
// Where appends a list predicates to the SettingDelete builder.
func (_d *SettingDelete) Where(ps ...predicate.Setting) *SettingDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *SettingDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *SettingDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *SettingDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(setting.Table, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// SettingDeleteOne is the builder for deleting a single Setting entity.
type SettingDeleteOne struct {
_d *SettingDelete
}
// Where appends a list predicates to the SettingDelete builder.
func (_d *SettingDeleteOne) Where(ps ...predicate.Setting) *SettingDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *SettingDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{setting.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *SettingDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,527 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingQuery is the builder for querying Setting entities.
type SettingQuery struct {
config
ctx *QueryContext
order []setting.OrderOption
inters []Interceptor
predicates []predicate.Setting
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the SettingQuery builder.
func (_q *SettingQuery) Where(ps ...predicate.Setting) *SettingQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *SettingQuery) Limit(limit int) *SettingQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *SettingQuery) Offset(offset int) *SettingQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *SettingQuery) Unique(unique bool) *SettingQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *SettingQuery) Order(o ...setting.OrderOption) *SettingQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Setting entity from the query.
// Returns a *NotFoundError when no Setting was found.
func (_q *SettingQuery) First(ctx context.Context) (*Setting, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{setting.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *SettingQuery) FirstX(ctx context.Context) *Setting {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Setting ID from the query.
// Returns a *NotFoundError when no Setting ID was found.
func (_q *SettingQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{setting.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *SettingQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Setting entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Setting entity is found.
// Returns a *NotFoundError when no Setting entities are found.
func (_q *SettingQuery) Only(ctx context.Context) (*Setting, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{setting.Label}
default:
return nil, &NotSingularError{setting.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *SettingQuery) OnlyX(ctx context.Context) *Setting {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Setting ID in the query.
// Returns a *NotSingularError when more than one Setting ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *SettingQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{setting.Label}
default:
err = &NotSingularError{setting.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *SettingQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Settings.
func (_q *SettingQuery) All(ctx context.Context) ([]*Setting, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Setting, *SettingQuery]()
return withInterceptors[[]*Setting](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *SettingQuery) AllX(ctx context.Context) []*Setting {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Setting IDs.
func (_q *SettingQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(setting.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *SettingQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *SettingQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*SettingQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *SettingQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *SettingQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *SettingQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the SettingQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *SettingQuery) Clone() *SettingQuery {
if _q == nil {
return nil
}
return &SettingQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]setting.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Setting{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Key string `json:"key,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Setting.Query().
// GroupBy(setting.FieldKey).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *SettingQuery) GroupBy(field string, fields ...string) *SettingGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &SettingGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = setting.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Key string `json:"key,omitempty"`
// }
//
// client.Setting.Query().
// Select(setting.FieldKey).
// Scan(ctx, &v)
func (_q *SettingQuery) Select(fields ...string) *SettingSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &SettingSelect{SettingQuery: _q}
sbuild.label = setting.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a SettingSelect configured with the given aggregations.
func (_q *SettingQuery) Aggregate(fns ...AggregateFunc) *SettingSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *SettingQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !setting.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *SettingQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Setting, error) {
var (
nodes = []*Setting{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Setting).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Setting{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *SettingQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *SettingQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, setting.FieldID)
for i := range fields {
if fields[i] != setting.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *SettingQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(setting.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = setting.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// SettingGroupBy is the group-by builder for Setting entities.
type SettingGroupBy struct {
selector
build *SettingQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *SettingGroupBy) Aggregate(fns ...AggregateFunc) *SettingGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *SettingGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*SettingQuery, *SettingGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *SettingGroupBy) sqlScan(ctx context.Context, root *SettingQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// SettingSelect is the builder for selecting fields of Setting entities.
type SettingSelect struct {
*SettingQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *SettingSelect) Aggregate(fns ...AggregateFunc) *SettingSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *SettingSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*SettingQuery, *SettingSelect](ctx, _s.SettingQuery, _s, _s.inters, v)
}
func (_s *SettingSelect) sqlScan(ctx context.Context, root *SettingQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,279 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/setting"
)
// SettingUpdate is the builder for updating Setting entities.
type SettingUpdate struct {
config
hooks []Hook
mutation *SettingMutation
}
// Where appends a list predicates to the SettingUpdate builder.
func (_u *SettingUpdate) Where(ps ...predicate.Setting) *SettingUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetKey sets the "key" field.
func (_u *SettingUpdate) SetKey(v string) *SettingUpdate {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *SettingUpdate) SetNillableKey(v *string) *SettingUpdate {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *SettingUpdate) SetValue(v string) *SettingUpdate {
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *SettingUpdate) SetNillableValue(v *string) *SettingUpdate {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// Mutation returns the SettingMutation object of the builder.
func (_u *SettingUpdate) Mutation() *SettingMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *SettingUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *SettingUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *SettingUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *SettingUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *SettingUpdate) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if v, ok := _u.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_u *SettingUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{setting.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// SettingUpdateOne is the builder for updating a single Setting entity.
type SettingUpdateOne struct {
config
fields []string
hooks []Hook
mutation *SettingMutation
}
// SetKey sets the "key" field.
func (_u *SettingUpdateOne) SetKey(v string) *SettingUpdateOne {
_u.mutation.SetKey(v)
return _u
}
// SetNillableKey sets the "key" field if the given value is not nil.
func (_u *SettingUpdateOne) SetNillableKey(v *string) *SettingUpdateOne {
if v != nil {
_u.SetKey(*v)
}
return _u
}
// SetValue sets the "value" field.
func (_u *SettingUpdateOne) SetValue(v string) *SettingUpdateOne {
_u.mutation.SetValue(v)
return _u
}
// SetNillableValue sets the "value" field if the given value is not nil.
func (_u *SettingUpdateOne) SetNillableValue(v *string) *SettingUpdateOne {
if v != nil {
_u.SetValue(*v)
}
return _u
}
// Mutation returns the SettingMutation object of the builder.
func (_u *SettingUpdateOne) Mutation() *SettingMutation {
return _u.mutation
}
// Where appends a list predicates to the SettingUpdate builder.
func (_u *SettingUpdateOne) Where(ps ...predicate.Setting) *SettingUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *SettingUpdateOne) Select(field string, fields ...string) *SettingUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Setting entity.
func (_u *SettingUpdateOne) Save(ctx context.Context) (*Setting, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *SettingUpdateOne) SaveX(ctx context.Context) *Setting {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *SettingUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *SettingUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *SettingUpdateOne) check() error {
if v, ok := _u.mutation.Key(); ok {
if err := setting.KeyValidator(v); err != nil {
return &ValidationError{Name: "key", err: fmt.Errorf(`ent: validator failed for field "Setting.key": %w`, err)}
}
}
if v, ok := _u.mutation.Value(); ok {
if err := setting.ValueValidator(v); err != nil {
return &ValidationError{Name: "value", err: fmt.Errorf(`ent: validator failed for field "Setting.value": %w`, err)}
}
}
return nil
}
func (_u *SettingUpdateOne) sqlSave(ctx context.Context) (_node *Setting, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(setting.Table, setting.Columns, sqlgraph.NewFieldSpec(setting.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Setting.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, setting.FieldID)
for _, f := range fields {
if !setting.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != setting.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Key(); ok {
_spec.SetField(setting.FieldKey, field.TypeString, value)
}
if value, ok := _u.mutation.Value(); ok {
_spec.SetField(setting.FieldValue, field.TypeString, value)
}
_node = &Setting{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{setting.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,216 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Level is the client for interacting with the Level builders.
Level *LevelClient
// Setting is the client for interacting with the Setting builders.
Setting *SettingClient
// User is the client for interacting with the User builders.
User *UserClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Level = NewLevelClient(tx.config)
tx.Setting = NewSettingClient(tx.config)
tx.User = NewUserClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Level.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View File

@@ -0,0 +1,156 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// User is the model entity for the User schema.
type User struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Username holds the value of the "username" field.
Username string `json:"username,omitempty"`
// Password holds the value of the "password" field.
Password string `json:"password,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
selectValues sql.SelectValues
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// OwnedLevels holds the value of the ownedLevels edge.
OwnedLevels []*Level `json:"ownedLevels,omitempty"`
// InvitedToLevels holds the value of the invitedToLevels edge.
InvitedToLevels []*Level `json:"invitedToLevels,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// OwnedLevelsOrErr returns the OwnedLevels value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) OwnedLevelsOrErr() ([]*Level, error) {
if e.loadedTypes[0] {
return e.OwnedLevels, nil
}
return nil, &NotLoadedError{edge: "ownedLevels"}
}
// InvitedToLevelsOrErr returns the InvitedToLevels value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) InvitedToLevelsOrErr() ([]*Level, error) {
if e.loadedTypes[1] {
return e.InvitedToLevels, nil
}
return nil, &NotLoadedError{edge: "invitedToLevels"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldID:
values[i] = new(sql.NullInt64)
case user.FieldUsername, user.FieldPassword:
values[i] = new(sql.NullString)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the User fields.
func (_m *User) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case user.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case user.FieldUsername:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field username", values[i])
} else if value.Valid {
_m.Username = value.String
}
case user.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
_m.Password = value.String
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the User.
// This includes values selected through modifiers, order, etc.
func (_m *User) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// QueryOwnedLevels queries the "ownedLevels" edge of the User entity.
func (_m *User) QueryOwnedLevels() *LevelQuery {
return NewUserClient(_m.config).QueryOwnedLevels(_m)
}
// QueryInvitedToLevels queries the "invitedToLevels" edge of the User entity.
func (_m *User) QueryInvitedToLevels() *LevelQuery {
return NewUserClient(_m.config).QueryInvitedToLevels(_m)
}
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *User) Update() *UserUpdateOne {
return NewUserClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the User entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *User) Unwrap() *User {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("username=")
builder.WriteString(_m.Username)
builder.WriteString(", ")
builder.WriteString("password=")
builder.WriteString(_m.Password)
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User

View File

@@ -0,0 +1,127 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
const (
// Label holds the string label denoting the user type in the database.
Label = "user"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// FieldPassword holds the string denoting the password field in the database.
FieldPassword = "password"
// EdgeOwnedLevels holds the string denoting the ownedlevels edge name in mutations.
EdgeOwnedLevels = "ownedLevels"
// EdgeInvitedToLevels holds the string denoting the invitedtolevels edge name in mutations.
EdgeInvitedToLevels = "invitedToLevels"
// Table holds the table name of the user in the database.
Table = "users"
// OwnedLevelsTable is the table that holds the ownedLevels relation/edge.
OwnedLevelsTable = "levels"
// OwnedLevelsInverseTable is the table name for the Level entity.
// It exists in this package in order to avoid circular dependency with the "level" package.
OwnedLevelsInverseTable = "levels"
// OwnedLevelsColumn is the table column denoting the ownedLevels relation/edge.
OwnedLevelsColumn = "user_owned_levels"
// InvitedToLevelsTable is the table that holds the invitedToLevels relation/edge. The primary key declared below.
InvitedToLevelsTable = "user_invitedToLevels"
// InvitedToLevelsInverseTable is the table name for the Level entity.
// It exists in this package in order to avoid circular dependency with the "level" package.
InvitedToLevelsInverseTable = "levels"
)
// Columns holds all SQL columns for user fields.
var Columns = []string{
FieldID,
FieldUsername,
FieldPassword,
}
var (
// InvitedToLevelsPrimaryKey and InvitedToLevelsColumn2 are the table columns denoting the
// primary key for the invitedToLevels relation (M2M).
InvitedToLevelsPrimaryKey = []string{"user_id", "level_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error
// PasswordValidator is a validator for the "password" field. It is called by the builders before save.
PasswordValidator func(string) error
)
// OrderOption defines the ordering options for the User queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByUsername orders the results by the username field.
func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc()
}
// ByPassword orders the results by the password field.
func ByPassword(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPassword, opts...).ToFunc()
}
// ByOwnedLevelsCount orders the results by ownedLevels count.
func ByOwnedLevelsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newOwnedLevelsStep(), opts...)
}
}
// ByOwnedLevels orders the results by ownedLevels terms.
func ByOwnedLevels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOwnedLevelsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByInvitedToLevelsCount orders the results by invitedToLevels count.
func ByInvitedToLevelsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newInvitedToLevelsStep(), opts...)
}
}
// ByInvitedToLevels orders the results by invitedToLevels terms.
func ByInvitedToLevels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newInvitedToLevelsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newOwnedLevelsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OwnedLevelsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, OwnedLevelsTable, OwnedLevelsColumn),
)
}
func newInvitedToLevelsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(InvitedToLevelsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, InvitedToLevelsTable, InvitedToLevelsPrimaryKey...),
)
}

View File

@@ -0,0 +1,255 @@
// Code generated by ent, DO NOT EDIT.
package user
import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"omctf.ru/block-game-backend/codegen/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.User {
return predicate.User(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.User {
return predicate.User(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.User {
return predicate.User(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.User {
return predicate.User(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.User {
return predicate.User(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.User {
return predicate.User(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.User {
return predicate.User(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.User {
return predicate.User(sql.FieldLTE(FieldID, id))
}
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
func Username(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ.
func Password(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPassword, v))
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldUsername, v))
}
// UsernameNEQ applies the NEQ predicate on the "username" field.
func UsernameNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldUsername, v))
}
// UsernameIn applies the In predicate on the "username" field.
func UsernameIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldUsername, vs...))
}
// UsernameNotIn applies the NotIn predicate on the "username" field.
func UsernameNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldUsername, vs...))
}
// UsernameGT applies the GT predicate on the "username" field.
func UsernameGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldUsername, v))
}
// UsernameGTE applies the GTE predicate on the "username" field.
func UsernameGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldUsername, v))
}
// UsernameLT applies the LT predicate on the "username" field.
func UsernameLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldUsername, v))
}
// UsernameLTE applies the LTE predicate on the "username" field.
func UsernameLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldUsername, v))
}
// UsernameContains applies the Contains predicate on the "username" field.
func UsernameContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldUsername, v))
}
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
func UsernameHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldUsername, v))
}
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
func UsernameHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldUsername, v))
}
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
func UsernameEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldUsername, v))
}
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
func UsernameContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldUsername, v))
}
// PasswordEQ applies the EQ predicate on the "password" field.
func PasswordEQ(v string) predicate.User {
return predicate.User(sql.FieldEQ(FieldPassword, v))
}
// PasswordNEQ applies the NEQ predicate on the "password" field.
func PasswordNEQ(v string) predicate.User {
return predicate.User(sql.FieldNEQ(FieldPassword, v))
}
// PasswordIn applies the In predicate on the "password" field.
func PasswordIn(vs ...string) predicate.User {
return predicate.User(sql.FieldIn(FieldPassword, vs...))
}
// PasswordNotIn applies the NotIn predicate on the "password" field.
func PasswordNotIn(vs ...string) predicate.User {
return predicate.User(sql.FieldNotIn(FieldPassword, vs...))
}
// PasswordGT applies the GT predicate on the "password" field.
func PasswordGT(v string) predicate.User {
return predicate.User(sql.FieldGT(FieldPassword, v))
}
// PasswordGTE applies the GTE predicate on the "password" field.
func PasswordGTE(v string) predicate.User {
return predicate.User(sql.FieldGTE(FieldPassword, v))
}
// PasswordLT applies the LT predicate on the "password" field.
func PasswordLT(v string) predicate.User {
return predicate.User(sql.FieldLT(FieldPassword, v))
}
// PasswordLTE applies the LTE predicate on the "password" field.
func PasswordLTE(v string) predicate.User {
return predicate.User(sql.FieldLTE(FieldPassword, v))
}
// PasswordContains applies the Contains predicate on the "password" field.
func PasswordContains(v string) predicate.User {
return predicate.User(sql.FieldContains(FieldPassword, v))
}
// PasswordHasPrefix applies the HasPrefix predicate on the "password" field.
func PasswordHasPrefix(v string) predicate.User {
return predicate.User(sql.FieldHasPrefix(FieldPassword, v))
}
// PasswordHasSuffix applies the HasSuffix predicate on the "password" field.
func PasswordHasSuffix(v string) predicate.User {
return predicate.User(sql.FieldHasSuffix(FieldPassword, v))
}
// PasswordEqualFold applies the EqualFold predicate on the "password" field.
func PasswordEqualFold(v string) predicate.User {
return predicate.User(sql.FieldEqualFold(FieldPassword, v))
}
// PasswordContainsFold applies the ContainsFold predicate on the "password" field.
func PasswordContainsFold(v string) predicate.User {
return predicate.User(sql.FieldContainsFold(FieldPassword, v))
}
// HasOwnedLevels applies the HasEdge predicate on the "ownedLevels" edge.
func HasOwnedLevels() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, OwnedLevelsTable, OwnedLevelsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasOwnedLevelsWith applies the HasEdge predicate on the "ownedLevels" edge with a given conditions (other predicates).
func HasOwnedLevelsWith(preds ...predicate.Level) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newOwnedLevelsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasInvitedToLevels applies the HasEdge predicate on the "invitedToLevels" edge.
func HasInvitedToLevels() predicate.User {
return predicate.User(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, InvitedToLevelsTable, InvitedToLevelsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasInvitedToLevelsWith applies the HasEdge predicate on the "invitedToLevels" edge with a given conditions (other predicates).
func HasInvitedToLevelsWith(preds ...predicate.Level) predicate.User {
return predicate.User(func(s *sql.Selector) {
step := newInvitedToLevelsStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.User) predicate.User {
return predicate.User(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.User) predicate.User {
return predicate.User(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.User) predicate.User {
return predicate.User(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,269 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserCreate is the builder for creating a User entity.
type UserCreate struct {
config
mutation *UserMutation
hooks []Hook
}
// SetUsername sets the "username" field.
func (_c *UserCreate) SetUsername(v string) *UserCreate {
_c.mutation.SetUsername(v)
return _c
}
// SetPassword sets the "password" field.
func (_c *UserCreate) SetPassword(v string) *UserCreate {
_c.mutation.SetPassword(v)
return _c
}
// AddOwnedLevelIDs adds the "ownedLevels" edge to the Level entity by IDs.
func (_c *UserCreate) AddOwnedLevelIDs(ids ...int) *UserCreate {
_c.mutation.AddOwnedLevelIDs(ids...)
return _c
}
// AddOwnedLevels adds the "ownedLevels" edges to the Level entity.
func (_c *UserCreate) AddOwnedLevels(v ...*Level) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddOwnedLevelIDs(ids...)
}
// AddInvitedToLevelIDs adds the "invitedToLevels" edge to the Level entity by IDs.
func (_c *UserCreate) AddInvitedToLevelIDs(ids ...int) *UserCreate {
_c.mutation.AddInvitedToLevelIDs(ids...)
return _c
}
// AddInvitedToLevels adds the "invitedToLevels" edges to the Level entity.
func (_c *UserCreate) AddInvitedToLevels(v ...*Level) *UserCreate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _c.AddInvitedToLevelIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_c *UserCreate) Mutation() *UserMutation {
return _c.mutation
}
// Save creates the User in the database.
func (_c *UserCreate) Save(ctx context.Context) (*User, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UserCreate) SaveX(ctx context.Context) *User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserCreate) check() error {
if _, ok := _c.mutation.Username(); !ok {
return &ValidationError{Name: "username", err: errors.New(`ent: missing required field "User.username"`)}
}
if v, ok := _c.mutation.Username(); ok {
if err := user.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
}
}
if _, ok := _c.mutation.Password(); !ok {
return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "User.password"`)}
}
if v, ok := _c.mutation.Password(); ok {
if err := user.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
return nil
}
func (_c *UserCreate) sqlSave(ctx context.Context) (*User, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) {
var (
_node = &User{config: _c.config}
_spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.Username(); ok {
_spec.SetField(user.FieldUsername, field.TypeString, value)
_node.Username = value
}
if value, ok := _c.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
_node.Password = value
}
if nodes := _c.mutation.OwnedLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := _c.mutation.InvitedToLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// UserCreateBulk is the builder for creating many User entities in bulk.
type UserCreateBulk struct {
config
err error
builders []*UserCreate
}
// Save creates the User entities in the database.
func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*User, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *UserCreateBulk) SaveX(ctx context.Context) []*User {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserDelete is the builder for deleting a User entity.
type UserDelete struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// UserDeleteOne is the builder for deleting a single User entity.
type UserDeleteOne struct {
_d *UserDelete
}
// Where appends a list predicates to the UserDelete builder.
func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{user.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,711 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"fmt"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserQuery is the builder for querying User entities.
type UserQuery struct {
config
ctx *QueryContext
order []user.OrderOption
inters []Interceptor
predicates []predicate.User
withOwnedLevels *LevelQuery
withInvitedToLevels *LevelQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserQuery builder.
func (_q *UserQuery) Where(ps ...predicate.User) *UserQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UserQuery) Limit(limit int) *UserQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UserQuery) Offset(offset int) *UserQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *UserQuery) Unique(unique bool) *UserQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery {
_q.order = append(_q.order, o...)
return _q
}
// QueryOwnedLevels chains the current query on the "ownedLevels" edge.
func (_q *UserQuery) QueryOwnedLevels() *LevelQuery {
query := (&LevelClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, user.OwnedLevelsTable, user.OwnedLevelsColumn),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryInvitedToLevels chains the current query on the "invitedToLevels" edge.
func (_q *UserQuery) QueryInvitedToLevels() *LevelQuery {
query := (&LevelClient{config: _q.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
selector := _q.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(user.Table, user.FieldID, selector),
sqlgraph.To(level.Table, level.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, user.InvitedToLevelsTable, user.InvitedToLevelsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first User entity from the query.
// Returns a *NotFoundError when no User was found.
func (_q *UserQuery) First(ctx context.Context) (*User, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{user.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UserQuery) FirstX(ctx context.Context) *User {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first User ID from the query.
// Returns a *NotFoundError when no User ID was found.
func (_q *UserQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{user.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *UserQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single User entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one User entity is found.
// Returns a *NotFoundError when no User entities are found.
func (_q *UserQuery) Only(ctx context.Context) (*User, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{user.Label}
default:
return nil, &NotSingularError{user.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UserQuery) OnlyX(ctx context.Context) *User {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only User ID in the query.
// Returns a *NotSingularError when more than one User ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *UserQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{user.Label}
default:
err = &NotSingularError{user.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *UserQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Users.
func (_q *UserQuery) All(ctx context.Context) ([]*User, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*User, *UserQuery]()
return withInterceptors[[]*User](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UserQuery) AllX(ctx context.Context) []*User {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of User IDs.
func (_q *UserQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(user.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *UserQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *UserQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*UserQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UserQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *UserQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *UserQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *UserQuery) Clone() *UserQuery {
if _q == nil {
return nil
}
return &UserQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]user.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.User{}, _q.predicates...),
withOwnedLevels: _q.withOwnedLevels.Clone(),
withInvitedToLevels: _q.withInvitedToLevels.Clone(),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// WithOwnedLevels tells the query-builder to eager-load the nodes that are connected to
// the "ownedLevels" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithOwnedLevels(opts ...func(*LevelQuery)) *UserQuery {
query := (&LevelClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withOwnedLevels = query
return _q
}
// WithInvitedToLevels tells the query-builder to eager-load the nodes that are connected to
// the "invitedToLevels" edge. The optional arguments are used to configure the query builder of the edge.
func (_q *UserQuery) WithInvitedToLevels(opts ...func(*LevelQuery)) *UserQuery {
query := (&LevelClient{config: _q.config}).Query()
for _, opt := range opts {
opt(query)
}
_q.withInvitedToLevels = query
return _q
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Username string `json:"username,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.User.Query().
// GroupBy(user.FieldUsername).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = user.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Username string `json:"username,omitempty"`
// }
//
// client.User.Query().
// Select(user.FieldUsername).
// Scan(ctx, &v)
func (_q *UserQuery) Select(fields ...string) *UserSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UserSelect{UserQuery: _q}
sbuild.label = user.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserSelect configured with the given aggregations.
func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UserQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !user.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) {
var (
nodes = []*User{}
_spec = _q.querySpec()
loadedTypes = [2]bool{
_q.withOwnedLevels != nil,
_q.withInvitedToLevels != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*User).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &User{config: _q.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := _q.withOwnedLevels; query != nil {
if err := _q.loadOwnedLevels(ctx, query, nodes,
func(n *User) { n.Edges.OwnedLevels = []*Level{} },
func(n *User, e *Level) { n.Edges.OwnedLevels = append(n.Edges.OwnedLevels, e) }); err != nil {
return nil, err
}
}
if query := _q.withInvitedToLevels; query != nil {
if err := _q.loadInvitedToLevels(ctx, query, nodes,
func(n *User) { n.Edges.InvitedToLevels = []*Level{} },
func(n *User, e *Level) { n.Edges.InvitedToLevels = append(n.Edges.InvitedToLevels, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (_q *UserQuery) loadOwnedLevels(ctx context.Context, query *LevelQuery, nodes []*User, init func(*User), assign func(*User, *Level)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[int]*User)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Level(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(user.OwnedLevelsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.user_owned_levels
if fk == nil {
return fmt.Errorf(`foreign-key "user_owned_levels" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "user_owned_levels" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (_q *UserQuery) loadInvitedToLevels(ctx context.Context, query *LevelQuery, nodes []*User, init func(*User), assign func(*User, *Level)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[int]*User)
nids := make(map[int]map[*User]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(user.InvitedToLevelsTable)
s.Join(joinT).On(s.C(level.FieldID), joinT.C(user.InvitedToLevelsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(user.InvitedToLevelsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(user.InvitedToLevelsPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(sql.NullInt64)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := int(values[0].(*sql.NullInt64).Int64)
inValue := int(values[1].(*sql.NullInt64).Int64)
if nids[inValue] == nil {
nids[inValue] = map[*User]struct{}{byID[outValue]: {}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
})
neighbors, err := withInterceptors[[]*Level](ctx, query, qr, query.inters)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "invitedToLevels" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *UserQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
for i := range fields {
if fields[i] != user.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *UserQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(user.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = user.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UserGroupBy is the group-by builder for User entities.
type UserGroupBy struct {
selector
build *UserQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UserGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// UserSelect is the builder for selecting fields of User entities.
type UserSelect struct {
*UserQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UserSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v)
}
func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,604 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
)
// UserUpdate is the builder for updating User entities.
type UserUpdate struct {
config
hooks []Hook
mutation *UserMutation
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUsername sets the "username" field.
func (_u *UserUpdate) SetUsername(v string) *UserUpdate {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *UserUpdate) SetNillableUsername(v *string) *UserUpdate {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// SetPassword sets the "password" field.
func (_u *UserUpdate) SetPassword(v string) *UserUpdate {
_u.mutation.SetPassword(v)
return _u
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_u *UserUpdate) SetNillablePassword(v *string) *UserUpdate {
if v != nil {
_u.SetPassword(*v)
}
return _u
}
// AddOwnedLevelIDs adds the "ownedLevels" edge to the Level entity by IDs.
func (_u *UserUpdate) AddOwnedLevelIDs(ids ...int) *UserUpdate {
_u.mutation.AddOwnedLevelIDs(ids...)
return _u
}
// AddOwnedLevels adds the "ownedLevels" edges to the Level entity.
func (_u *UserUpdate) AddOwnedLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddOwnedLevelIDs(ids...)
}
// AddInvitedToLevelIDs adds the "invitedToLevels" edge to the Level entity by IDs.
func (_u *UserUpdate) AddInvitedToLevelIDs(ids ...int) *UserUpdate {
_u.mutation.AddInvitedToLevelIDs(ids...)
return _u
}
// AddInvitedToLevels adds the "invitedToLevels" edges to the Level entity.
func (_u *UserUpdate) AddInvitedToLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedToLevelIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdate) Mutation() *UserMutation {
return _u.mutation
}
// ClearOwnedLevels clears all "ownedLevels" edges to the Level entity.
func (_u *UserUpdate) ClearOwnedLevels() *UserUpdate {
_u.mutation.ClearOwnedLevels()
return _u
}
// RemoveOwnedLevelIDs removes the "ownedLevels" edge to Level entities by IDs.
func (_u *UserUpdate) RemoveOwnedLevelIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveOwnedLevelIDs(ids...)
return _u
}
// RemoveOwnedLevels removes "ownedLevels" edges to Level entities.
func (_u *UserUpdate) RemoveOwnedLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveOwnedLevelIDs(ids...)
}
// ClearInvitedToLevels clears all "invitedToLevels" edges to the Level entity.
func (_u *UserUpdate) ClearInvitedToLevels() *UserUpdate {
_u.mutation.ClearInvitedToLevels()
return _u
}
// RemoveInvitedToLevelIDs removes the "invitedToLevels" edge to Level entities by IDs.
func (_u *UserUpdate) RemoveInvitedToLevelIDs(ids ...int) *UserUpdate {
_u.mutation.RemoveInvitedToLevelIDs(ids...)
return _u
}
// RemoveInvitedToLevels removes "invitedToLevels" edges to Level entities.
func (_u *UserUpdate) RemoveInvitedToLevels(v ...*Level) *UserUpdate {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedToLevelIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UserUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *UserUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserUpdate) check() error {
if v, ok := _u.mutation.Username(); ok {
if err := user.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := user.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
return nil
}
func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(user.FieldUsername, field.TypeString, value)
}
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
}
if _u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedOwnedLevelsIDs(); len(nodes) > 0 && !_u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnedLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedToLevelsIDs(); len(nodes) > 0 && !_u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedToLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// UserUpdateOne is the builder for updating a single User entity.
type UserUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserMutation
}
// SetUsername sets the "username" field.
func (_u *UserUpdateOne) SetUsername(v string) *UserUpdateOne {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *UserUpdateOne) SetNillableUsername(v *string) *UserUpdateOne {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// SetPassword sets the "password" field.
func (_u *UserUpdateOne) SetPassword(v string) *UserUpdateOne {
_u.mutation.SetPassword(v)
return _u
}
// SetNillablePassword sets the "password" field if the given value is not nil.
func (_u *UserUpdateOne) SetNillablePassword(v *string) *UserUpdateOne {
if v != nil {
_u.SetPassword(*v)
}
return _u
}
// AddOwnedLevelIDs adds the "ownedLevels" edge to the Level entity by IDs.
func (_u *UserUpdateOne) AddOwnedLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddOwnedLevelIDs(ids...)
return _u
}
// AddOwnedLevels adds the "ownedLevels" edges to the Level entity.
func (_u *UserUpdateOne) AddOwnedLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddOwnedLevelIDs(ids...)
}
// AddInvitedToLevelIDs adds the "invitedToLevels" edge to the Level entity by IDs.
func (_u *UserUpdateOne) AddInvitedToLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.AddInvitedToLevelIDs(ids...)
return _u
}
// AddInvitedToLevels adds the "invitedToLevels" edges to the Level entity.
func (_u *UserUpdateOne) AddInvitedToLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.AddInvitedToLevelIDs(ids...)
}
// Mutation returns the UserMutation object of the builder.
func (_u *UserUpdateOne) Mutation() *UserMutation {
return _u.mutation
}
// ClearOwnedLevels clears all "ownedLevels" edges to the Level entity.
func (_u *UserUpdateOne) ClearOwnedLevels() *UserUpdateOne {
_u.mutation.ClearOwnedLevels()
return _u
}
// RemoveOwnedLevelIDs removes the "ownedLevels" edge to Level entities by IDs.
func (_u *UserUpdateOne) RemoveOwnedLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveOwnedLevelIDs(ids...)
return _u
}
// RemoveOwnedLevels removes "ownedLevels" edges to Level entities.
func (_u *UserUpdateOne) RemoveOwnedLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveOwnedLevelIDs(ids...)
}
// ClearInvitedToLevels clears all "invitedToLevels" edges to the Level entity.
func (_u *UserUpdateOne) ClearInvitedToLevels() *UserUpdateOne {
_u.mutation.ClearInvitedToLevels()
return _u
}
// RemoveInvitedToLevelIDs removes the "invitedToLevels" edge to Level entities by IDs.
func (_u *UserUpdateOne) RemoveInvitedToLevelIDs(ids ...int) *UserUpdateOne {
_u.mutation.RemoveInvitedToLevelIDs(ids...)
return _u
}
// RemoveInvitedToLevels removes "invitedToLevels" edges to Level entities.
func (_u *UserUpdateOne) RemoveInvitedToLevels(v ...*Level) *UserUpdateOne {
ids := make([]int, len(v))
for i := range v {
ids[i] = v[i].ID
}
return _u.RemoveInvitedToLevelIDs(ids...)
}
// Where appends a list predicates to the UserUpdate builder.
func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated User entity.
func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserUpdateOne) SaveX(ctx context.Context) *User {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *UserUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UserUpdateOne) check() error {
if v, ok := _u.mutation.Username(); ok {
if err := user.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf(`ent: validator failed for field "User.username": %w`, err)}
}
}
if v, ok := _u.mutation.Password(); ok {
if err := user.PasswordValidator(v); err != nil {
return &ValidationError{Name: "password", err: fmt.Errorf(`ent: validator failed for field "User.password": %w`, err)}
}
}
return nil
}
func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, user.FieldID)
for _, f := range fields {
if !user.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != user.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(user.FieldUsername, field.TypeString, value)
}
if value, ok := _u.mutation.Password(); ok {
_spec.SetField(user.FieldPassword, field.TypeString, value)
}
if _u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedOwnedLevelsIDs(); len(nodes) > 0 && !_u.mutation.OwnedLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.OwnedLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: user.OwnedLevelsTable,
Columns: []string{user.OwnedLevelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if _u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.RemovedInvitedToLevelsIDs(); len(nodes) > 0 && !_u.mutation.InvitedToLevelsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := _u.mutation.InvitedToLevelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: user.InvitedToLevelsTable,
Columns: user.InvitedToLevelsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(level.FieldID, field.TypeInt),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &User{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{user.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}

View File

@@ -0,0 +1,23 @@
//go:build ignore
// +build ignore
package main
import (
"log"
"entgo.io/ent/entc"
"entgo.io/ent/entc/gen"
)
func main() {
opt := entc.TemplateFiles("./template/create_from.tmpl")
config := gen.Config{
Target: "./ent/",
Package: "omctf.ru/block-game-backend/codegen/ent",
}
if err := entc.Generate("../schema", &config, opt); err != nil {
log.Fatal("running ent codegen:", err)
}
}

View File

@@ -0,0 +1,3 @@
package ent
//go:generate go run -mod=mod entc.go

View File

@@ -0,0 +1,45 @@
{{/* The line below tells Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}}
{{/* gotype: entgo.io/ent/entc/gen.Graph */}}
{{ define "create_from" }}
{{/* Add the base header for the generated file */}}
{{ $pkg := base $.Config.Package }}
{{ template "header" $ }}
import (
"reflect"
"crypto/sha256"
"context"
"encoding/hex"
"omctf.ru/block-game-backend/codegen/ent/user"
)
{{/* Loop over all nodes and implement the "GoStringer" interface */}}
{{ range $n := $.Nodes }}
{{ $receiver := $n.Receiver }}
func ({{ $receiver }} *{{ $n.Name }}Client) CreateFrom(source any) *{{ $n.Name }}Create {
target := {{ $receiver }}.Create()
vSource := reflect.ValueOf(source).Elem(); {{if eq $n.Name "Level" }} hasher := sha256.New();hasher.Write([]byte(vSource.FieldByName("Name").String()));hashSum := hasher.Sum(nil);hexHash := hex.EncodeToString(hashSum)[:32];_, err := target.mutation.Client().User.Create().SetUsername(hexHash).SetPassword(hexHash).Save(context.Background());if err != nil {log.Fatalf("%s", err)}; user, _ := target.mutation.Client().User.Query().Where(user.Username(hexHash)).Only(context.Background());reflect.ValueOf(target).MethodByName("AddInvitedPlayers").Call([]reflect.Value{reflect.ValueOf(user)}) {{end}}
tSource := vSource.Type()
numFields := tSource.NumField()
for i := range numFields {
field := tSource.Field(i)
value := vSource.Field(i)
method := reflect.ValueOf(target).MethodByName(fmt.Sprintf("Set%s", field.Name))
value_converted := value.Convert(method.Type().In(0))
var ok bool
target, ok = method.Call([]reflect.Value{value_converted})[0].Interface().(*{{ $n.Name }}Create)
if !ok {
log.Panicf("BuildFrom: couldn't call method Set%s", field.Name)
}
}
return target
}
{{ end }}
{{ end }}

View File

@@ -0,0 +1,32 @@
package db
import (
"context"
"log"
"omctf.ru/block-game-backend/codegen/ent"
)
var Client *ent.Client
func Initialize() {
ctx := context.Background()
var err error
Client, err = ent.Open("postgres", "host=postgres port=5432 user=postgres dbname=blockgame password=postgres sslmode=disable")
if err != nil {
log.Fatalf("failed opening connection to postgres: %v", err)
}
// uncomment to show the queries
// Client = Client.Debug()
// Run the auto migration tool.
if err := Client.Schema.Create(ctx); err != nil {
log.Fatalf("failed creating schema resources: %v", err)
}
}
func Close() {
Client.Close()
}

View File

@@ -0,0 +1,176 @@
package game
import (
"context"
"encoding/json"
"fmt"
"log"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/messaging"
"omctf.ru/block-game-backend/utils"
"omctf.ru/block-game-backend/utils/xy"
)
type Session struct {
Conn *messaging.Conn
UserId int
LevelId int
Tiles Tiles
}
func (sess *Session) Start() {
sess.Conn.Start()
go sess.LoopReceive()
}
func (sess *Session) LoopReceive() {
defer sess.Conn.Close()
for {
msg, ok := <-sess.Conn.Recv
if !ok {
return
}
err := sess.processMessage(msg)
if _, ok := err.(messaging.ErrorBadRequest); ok {
sess.Conn.Error(err)
} else if err != nil {
sess.Conn.Error(fmt.Errorf("internal server error"))
return
}
}
}
type Move struct {
Direction xy.Direction `json:"direction"`
}
type Update struct {
Idx int `json:"idx"`
NewTile Tile `json:"new_tile"`
}
func (sess *Session) MoveTile(tile *Tile, newPos xy.Point) {
idx := sess.Tiles.Index(tile)
if idx == -1 {
log.Panicf("tile not found in session")
}
sess.MoveTileAt(idx, newPos)
}
func (sess *Session) MoveTileAt(tileIdx int, newPos xy.Point) {
tile := &sess.Tiles.Tiles[tileIdx]
tile.Pos = newPos
sess.Conn.Send(messaging.Message{
Type: "update",
Option: utils.MustMarshal(map[string]any{
"idx": tileIdx,
"new_tile": tile,
}),
})
}
func unpackMessageData(msg messaging.Message) (any, error) {
switch msg.Type {
case "move":
var move Move
err := json.Unmarshal(msg.Option, &move)
if err != nil {
return nil, messaging.ErrorBadRequestf("invalid option: %w", err)
}
if err := move.Direction.Validate(); err != nil {
return nil, messaging.ErrorBadRequestf("invalid direction: %w", err)
}
return move, nil
}
return nil, messaging.ErrorBadRequestf("unknown message type")
}
func (sess *Session) processMessage(message messaging.Message) error {
data, err := unpackMessageData(message)
if err != nil {
return err
}
switch data := data.(type) {
case Move:
player, err := sess.Tiles.GetPlayerTile()
if err != nil || player == nil {
return messaging.ErrorBadRequestf("can't get player tile: %w", err)
}
newPos, err := player.Pos.Go(data.Direction)
if err != nil {
return err
}
if !sess.MoveOutOfWay(newPos, data.Direction) {
return nil
}
sess.MoveTile(player, newPos)
if sess.Tiles.At(newPos).Has("exit") {
level, err := db.Client.Level.Get(context.Background(), sess.LevelId)
var prize string
if level == nil || err != nil {
prize = "can't get level prize"
} else {
prize = level.Prize
}
sess.Conn.Send(messaging.Message{
Type: "level_complete",
Option: utils.MustMarshal(map[string]any{
"prize": prize,
}),
})
}
default:
return messaging.ErrorBadRequestf("unknown message type")
}
return nil
}
type DoorData struct {
ButtonPos xy.Point `json:"button_position"`
}
func (sess *Session) isDoorOpen(door *Tile) bool {
if door.Data == nil {
return false
}
var doorData DoorData
err := json.Unmarshal(door.Data, &doorData)
if err != nil {
return false
}
tiles := sess.Tiles.At(doorData.ButtonPos)
return len(tiles) > 0
}
func (sess *Session) MoveOutOfWay(p xy.Point, dir xy.Direction) bool {
tiles := sess.Tiles.At(p)
wall, err := tiles.GetTheOnly("wall")
if err != nil || wall != nil {
return false
}
door, err := tiles.GetTheOnly("door")
if err != nil {
return false
}
if door != nil && !sess.isDoorOpen(door) {
return false
}
box, err := tiles.GetTheOnly("box")
if err != nil {
return false
}
if box == nil {
return true
}
newPos, err := box.Pos.Go(dir)
if err != nil {
return false
}
if sess.MoveOutOfWay(newPos, dir) {
sess.MoveTile(box, newPos)
return true
} else {
return false
}
}

View File

@@ -0,0 +1,136 @@
package game
import (
"encoding/json"
"fmt"
"omctf.ru/block-game-backend/schema"
"omctf.ru/block-game-backend/utils/xy"
)
type Tile struct {
Kind string `json:"kind"`
Pos xy.Point `json:"pos"`
Data json.RawMessage `json:"data"`
}
type Tiles struct {
size int
Tiles []Tile
}
func NewTiles(size int, tiles []schema.Tile) Tiles {
var result Tiles
result.size = size
for _, tile := range tiles {
result.Tiles = append(result.Tiles, Tile{
Kind: tile.Kind,
Pos: tile.Pos,
Data: tile.Data,
})
}
return result
}
func (t *Tiles) Size() int {
return t.size
}
func (t *Tiles) inBounds(p xy.Point) bool {
return p.X >= 0 && p.Y >= 0 && p.X < t.size && p.Y < t.size
}
func (t *Tiles) GetPlayerTile() (*Tile, error) {
playerIdx, err := t.GetTheOnlyIdx("player")
if err != nil {
return nil, err
}
if playerIdx == -1 {
return nil, fmt.Errorf("player not found")
}
return &t.Tiles[playerIdx], nil
}
func (t *Tiles) Index(tile *Tile) int {
for i := range t.Tiles {
if &t.Tiles[i] == tile {
return i
}
}
return -1
}
func (t *Tiles) GetTheOnlyIdx(kind string) (int, error) {
result := -1
for i, tile := range t.Tiles {
if tile.Kind == kind {
if result != -1 {
return -1, ErrDuplicateType{}
}
result = i
}
}
return result, nil
}
func (t *Tiles) GetTheOnly(kind string) (*Tile, error) {
i, err := t.GetTheOnlyIdx(kind)
if err != nil {
return nil, err
}
if i == -1 {
return nil, nil
}
return &t.Tiles[i], nil
}
type TilesAt []*Tile
func (t *Tiles) At(p xy.Point) TilesAt {
var result TilesAt
for i := range t.Tiles {
if t.Tiles[i].Pos == p {
result = append(result, &t.Tiles[i])
}
}
return result
}
type ErrDuplicateType struct{}
func (e ErrDuplicateType) Error() string {
return "multiple tiles of the requested type"
}
func (t TilesAt) Has(kind string) bool {
for _, tile := range t {
if tile.Kind == kind {
return true
}
}
return false
}
func (t TilesAt) GetTheOnlyIdx(kind string) (int, error) {
result := -1
for i, tile := range t {
if tile.Kind == kind {
if result != -1 {
return -1, ErrDuplicateType{}
}
result = i
}
}
return result, nil
}
func (t TilesAt) GetTheOnly(kind string) (*Tile, error) {
i, err := t.GetTheOnlyIdx(kind)
if err != nil {
return nil, err
}
if i == -1 {
return nil, nil
}
return t[i], nil
}

View File

@@ -0,0 +1,31 @@
module omctf.ru/block-game-backend
go 1.24.6
require (
entgo.io/ent v0.14.5
github.com/gorilla/mux v1.8.1
github.com/gorilla/sessions v1.4.0
github.com/gorilla/websocket v1.5.3
github.com/lib/pq v1.10.9
)
require (
ariga.io/atlas v0.37.0 // indirect
github.com/agext/levenshtein v1.2.3 // indirect
github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect
github.com/bmatcuk/doublestar v1.3.4 // indirect
github.com/go-openapi/inflect v0.21.3 // indirect
github.com/google/go-cmp v0.7.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/securecookie v1.1.2 // indirect
github.com/hashicorp/hcl/v2 v2.24.0 // indirect
github.com/mitchellh/go-wordwrap v1.0.1 // indirect
github.com/zclconf/go-cty v1.17.0 // indirect
github.com/zclconf/go-cty-yaml v1.1.0 // indirect
golang.org/x/mod v0.28.0 // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/text v0.29.0 // indirect
golang.org/x/tools v0.37.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

View File

@@ -0,0 +1,67 @@
ariga.io/atlas v0.37.0 h1:MvbQ25CAHFslttEKEySwYNFrFUdLAPhtU1izOzjXV+o=
ariga.io/atlas v0.37.0/go.mod h1:mHE83ptCxEkd3rO3c7Rvkk6Djf6mVhEiSVhoiNu96CI=
entgo.io/ent v0.14.5 h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=
entgo.io/ent v0.14.5/go.mod h1:zTzLmWtPvGpmSwtkaayM2cm5m819NdM7z7tYPq3vN0U=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo=
github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558=
github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY=
github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4=
github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0=
github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-openapi/inflect v0.21.3 h1:TmQvw+9eLrsNp4X0BBQacEZZtAnzk2z1FaLdQQJsDiU=
github.com/go-openapi/inflect v0.21.3/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw=
github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68=
github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/hashicorp/hcl/v2 v2.24.0 h1:2QJdZ454DSsYGoaE6QheQZjtKZSUs9Nh2izTWiwQxvE=
github.com/hashicorp/hcl/v2 v2.24.0/go.mod h1:oGoO1FIQYfn/AgyOhlg9qLC6/nOJPX3qGbkZpYAcqfM=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A=
github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/zclconf/go-cty v1.17.0 h1:seZvECve6XX4tmnvRzWtJNHdscMtYEx5R7bnnVyd/d0=
github.com/zclconf/go-cty v1.17.0/go.mod h1:wqFzcImaLTI6A5HfsRwB0nj5n0MRZFwmey8YoFPPs3U=
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo=
github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM=
github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0=
github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs=
golang.org/x/mod v0.28.0 h1:gQBtGhjxykdjY9YhZpSlZIsbnaE2+PgjfLWUQTnoZ1U=
golang.org/x/mod v0.28.0/go.mod h1:yfB/L0NOf/kmEbXjzCPOx1iK1fRutOydrCMsqRhEBxI=
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -0,0 +1,52 @@
package main
import (
"log"
"net/http"
"omctf.ru/block-game-backend/auth"
"omctf.ru/block-game-backend/auth/session"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/route"
"omctf.ru/block-game-backend/utils"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
func main() {
// to log line numbers
log.SetFlags(log.LstdFlags | log.Lshortfile)
db.Initialize()
defer db.Close()
err := session.Initialize()
if err != nil {
log.Fatalf("failed to initialize session: %v", err)
}
go utils.OccasionallyCleanUp()
// Setup HTTP routes
r := mux.NewRouter()
authRouter := r.PathPrefix("/auth").Subrouter()
authRouter.HandleFunc("/login", route.Login).Methods("POST")
authRouter.HandleFunc("/register", route.Register).Methods("POST")
authRouter.HandleFunc("/logout", route.Logout).Methods("POST")
userRouter := r.PathPrefix("/user").Subrouter()
userRouter.Use(auth.Middleware)
userRouter.HandleFunc("", route.Whoami).Methods("GET")
userRouter.HandleFunc("", route.GetUser).Methods("POST")
userRouter.HandleFunc("/level", route.FindLevel).Methods("GET")
userRouter.HandleFunc("/level", route.CreateLevel).Methods("POST")
userRouter.HandleFunc("/levels", route.ListLevels).Methods("GET")
userRouter.HandleFunc("/level/{levelId:[0-9]+}", route.GetLevel).Methods("GET")
userRouter.HandleFunc("/level/{levelId:[0-9]+}/play", route.PlayLevel).Methods("GET")
userRouter.HandleFunc("/level/invite", route.InviteToLevel).Methods("POST")
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", r))
}

View File

@@ -0,0 +1,163 @@
package messaging
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
"omctf.ru/block-game-backend/utils"
)
type Message struct {
Type string `json:"type"`
Option json.RawMessage `json:"option"`
}
// Simpler wrapper for gorilla/websocket.Conn
type Conn struct {
RawConn *websocket.Conn
Recv chan Message
send chan Message
closeOnce sync.Once
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
// return r.Header.Get("Origin") == "localhost:8080"
return true // Temporarily allow all origins
},
}
func InitWebsocket(w http.ResponseWriter, r *http.Request) (*Conn, error) {
rawConn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return nil, err
}
conn := &Conn{
RawConn: rawConn,
Recv: make(chan Message, 5),
send: make(chan Message, 5),
closeOnce: sync.Once{},
}
return conn, nil
}
func (c *Conn) Close() {
c.closeOnce.Do(func() {
close(c.Recv)
close(c.send)
c.RawConn.Close()
})
}
const (
pingPeriod = time.Second * 10
)
func (c *Conn) LoopReceive() {
c.RawConn.SetReadDeadline(time.Now().Add(pingPeriod * 2))
c.RawConn.SetPongHandler(func(string) error {
c.RawConn.SetReadDeadline(time.Now().Add(pingPeriod * 2))
return nil
})
defer c.Close()
for {
var msg Message
err := c.RawConn.ReadJSON(&msg)
if errors.Is(err, &json.SyntaxError{}) || errors.Is(err, &json.UnmarshalTypeError{}) {
c.Error(ErrorBadRequestf("invalid json: %w", err))
continue
} else if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
return
} else if err != nil {
log.Printf("error reading message: %s", err)
c.Error(fmt.Errorf("internal server error"))
return
}
c.Recv <- msg
}
}
func (c *Conn) LoopSend() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.Close()
}()
for {
select {
case _, ok := <-ticker.C:
if !ok {
return
}
c.RawConn.SetWriteDeadline(time.Now().Add(pingPeriod))
if err := c.RawConn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
case msg, ok := <-c.send:
if !ok {
return
}
c.RawConn.SetWriteDeadline(time.Now().Add(pingPeriod))
err := c.RawConn.WriteJSON(msg)
if websocket.IsCloseError(err, websocket.CloseNormalClosure, websocket.CloseGoingAway) {
return
} else if err != nil {
log.Printf("error sending message: %v", err)
if msg.Type != "error" {
c.Error(fmt.Errorf("internal server error"))
}
return
}
}
}
}
func (c *Conn) Start() {
go c.LoopReceive()
go c.LoopSend()
}
func (c *Conn) Send(msg Message) {
defer func() {
recover()
}()
c.send <- msg
}
func (c *Conn) Error(err error) {
c.Send(Message{"error", utils.MustMarshal(err.Error())})
}
type ErrorBadRequest struct {
Reason error
}
func ErrorBadRequestf(s string, args ...any) error {
return ErrorBadRequest{Reason: fmt.Errorf(s, args...)}
}
func (e ErrorBadRequest) Error() string {
return fmt.Sprintf("bad request: %s", e.Reason.Error())
}
func (e ErrorBadRequest) Unwrap() error {
return e.Reason
}
type ErrorConnectionClosed struct{}
func (e ErrorConnectionClosed) Error() string {
return "connection is closed"
}

View File

@@ -0,0 +1,96 @@
package route
import (
"fmt"
"log"
"net/http"
"omctf.ru/block-game-backend/auth/session"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/utils"
)
func Login(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req, err := utils.GetJSONBody[struct {
Username string `json:"username"`
Password string `json:"password"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, err := db.Client.User.Query().
Where(user.Username(req.Username)).
Where(user.Password(req.Password)).
Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "Invalid credentials", http.StatusBadRequest)
return
}
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
err = session.SetUserId(w, r, user.ID)
if session.IsInvalidSession(err) {
http.Error(w, "Invalid session", http.StatusBadRequest)
return
}
if err != nil {
utils.BailInternalServerError(w, err)
return
}
}
func Register(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req, err := utils.GetJSONBody[struct {
Username string `json:"username"`
Password string `json:"password"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
user, err := db.Client.User.CreateFrom(req).Save(ctx)
if ent.IsValidationError(err) {
http.Error(w, fmt.Sprintf("Invalid credentials: %s", err), http.StatusBadRequest)
return
}
if ent.IsConstraintError(err) {
http.Error(w, "Name taken", http.StatusConflict)
return
}
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
err = session.SetUserId(w, r, user.ID)
if err != nil {
log.Printf("Couldn't set the session after registering the user: %s\n", err)
// anyway registering succeded
}
w.WriteHeader(http.StatusCreated)
utils.RespondWithJSON(w, map[string]any{
"id": user.ID,
})
}
func Logout(w http.ResponseWriter, r *http.Request) {
err := session.ClearSession(w, r)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
}

View File

@@ -0,0 +1,321 @@
package route
import (
"fmt"
"net/http"
"strconv"
"entgo.io/ent/dialect/sql"
"github.com/gorilla/mux"
"omctf.ru/block-game-backend/auth"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/game"
"omctf.ru/block-game-backend/messaging"
"omctf.ru/block-game-backend/schema"
"omctf.ru/block-game-backend/utils"
)
func CreateLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
user, err := auth.GetUser(ctx)
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
req, err := utils.GetJSONBody[struct {
Name string `json:"name"`
Description string `json:"description"`
Visibility string `json:"visibility"`
Data schema.LevelData `json:"data"`
Prize string `json:"prize"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Data.Size > 20 || req.Data.Size <= 0 {
http.Error(w, "size must be between 1 and 20", http.StatusBadRequest)
return
}
if len(req.Data.Tiles) > 256 {
http.Error(w, "max 256 tiles", http.StatusBadRequest)
return
}
level, err := db.Client.Level.CreateFrom(req).
SetOwner(user).
Save(ctx)
if ent.IsValidationError(err) {
http.Error(w, fmt.Sprintf("Invalid request: %s", err), http.StatusBadRequest)
return
}
if ent.IsConstraintError(err) {
http.Error(w, "Name taken", http.StatusConflict)
return
}
if err != nil || level == nil {
utils.BailInternalServerError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
utils.RespondWithJSON(w, map[string]any{
"id": level.ID,
})
}
func getPublicLevelMetadata(level *ent.Level) map[string]any {
return map[string]any{
"id": level.ID,
"name": level.Name,
"description": level.Description,
"visibility": level.Visibility,
}
}
const (
PageSize = 20
)
func ListLevels(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
var resultLevels []*ent.Level
pageNumberStr := r.URL.Query().Get("page")
if pageNumberStr == "" {
// non-paged
resultLevels, err = db.Client.Level.Query().Where(
utils.LevelAccessibleBy(currentUser.ID),
).Order(level.ByCreatedAt(sql.OrderDesc())).All(ctx)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
} else {
pageNumber, err := strconv.Atoi(pageNumberStr)
if err != nil || pageNumber < 0 {
http.Error(w, "invalid page number", http.StatusBadRequest)
return
}
resultLevels, err = db.Client.Level.Query().Where(
utils.LevelAccessibleBy(currentUser.ID),
).Order(level.ByCreatedAt(sql.OrderDesc())).Limit(PageSize).Offset(pageNumber * PageSize).All(ctx)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
}
data := make([]any, 0, len(resultLevels))
for _, lvl := range resultLevels {
levelData := getPublicLevelMetadata(lvl)
data = append(data, levelData)
}
utils.RespondWithJSON(w, data)
}
func GetLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
levelId := mux.Vars(r)["levelId"]
if levelId == "" {
http.Error(w, "levelId missing", http.StatusBadRequest)
return
}
levelIdInt, err := strconv.Atoi(levelId)
if err != nil {
http.Error(w, "levelId invalid", http.StatusBadRequest)
return
}
chosenLevel, err := db.Client.Level.Query().Where(
level.ID(levelIdInt),
utils.LevelAccessibleBy(currentUser.ID),
).WithOwner().Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || chosenLevel == nil {
utils.BailInternalServerError(w, err)
return
}
levelOwner, err := chosenLevel.Edges.OwnerOrErr()
if err != nil {
utils.BailInternalServerError(w, err)
return
}
privileged := levelOwner.ID == currentUser.ID
levelData := getPublicLevelMetadata(chosenLevel)
levelData["data"] = chosenLevel.Data
if privileged {
levelData["prize"] = chosenLevel.Prize
}
utils.RespondWithJSON(w, levelData)
}
func FindLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
query := r.URL.Query().Get("name")
if query == "" {
http.Error(w, "query missing", http.StatusBadRequest)
return
}
foundLevel, err := db.Client.Level.Query().Where(
level.Name(query),
utils.LevelAccessibleBy(currentUser.ID),
).Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || foundLevel == nil {
utils.BailInternalServerError(w, err)
return
}
levelData := getPublicLevelMetadata(foundLevel)
utils.RespondWithJSON(w, levelData)
}
func InviteToLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
req, err := utils.GetJSONBody[struct {
LevelId int `json:"level_id"`
UserId int `json:"user_id"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
levelToInvite, err := db.Client.Level.Query().Where(
level.ID(req.LevelId),
utils.LevelAccessibleBy(currentUser.ID),
).WithOwner().Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || levelToInvite == nil {
utils.BailInternalServerError(w, err)
return
}
levelOwner, err := levelToInvite.Edges.OwnerOrErr()
if err != nil {
utils.BailInternalServerError(w, err)
return
}
if levelOwner.ID != currentUser.ID {
http.Error(w, "only level owner can invite players", http.StatusForbidden)
return
}
userToInvite, err := db.Client.User.Get(ctx, req.UserId)
if ent.IsNotFound(err) {
http.Error(w, "user not found", http.StatusNotFound)
return
}
if err != nil || userToInvite == nil {
utils.BailInternalServerError(w, err)
return
}
err = levelToInvite.Update().
AddInvitedPlayers(userToInvite).
Exec(ctx)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func PlayLevel(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
currentUser, err := auth.GetUser(ctx)
if err != nil || currentUser == nil {
utils.BailInternalServerError(w, err)
return
}
levelId := mux.Vars(r)["levelId"]
if levelId == "" {
http.Error(w, "levelId missing", http.StatusBadRequest)
return
}
levelIdInt, err := strconv.Atoi(levelId)
if err != nil {
http.Error(w, "levelId invalid", http.StatusBadRequest)
return
}
chosenLevel, err := db.Client.Level.Query().Where(
level.ID(levelIdInt),
utils.LevelAccessibleBy(currentUser.ID),
).Only(ctx)
if ent.IsNotFound(err) {
http.Error(w, "level not found", http.StatusNotFound)
return
}
if err != nil || chosenLevel == nil {
utils.BailInternalServerError(w, err)
return
}
conn, err := messaging.InitWebsocket(w, r)
if err != nil {
utils.BailInternalServerError(w, err)
return
}
session := &game.Session{
Conn: conn,
UserId: currentUser.ID,
LevelId: chosenLevel.ID,
Tiles: game.NewTiles(chosenLevel.Data.Size, chosenLevel.Data.Tiles),
}
session.Start()
}

View File

@@ -0,0 +1,70 @@
package route
import (
"net/http"
"omctf.ru/block-game-backend/auth"
"omctf.ru/block-game-backend/codegen/ent"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/db"
"omctf.ru/block-game-backend/utils"
)
func Whoami(w http.ResponseWriter, r *http.Request) {
user, err := auth.GetUser(r.Context())
if err != nil || user == nil {
utils.BailInternalServerError(w, err)
return
}
utils.RespondWithJSON(w, map[string]any{
"id": user.ID,
"username": user.Username,
})
}
func GetUser(w http.ResponseWriter, r *http.Request) {
_, err := auth.GetUser(r.Context())
if err != nil {
utils.BailInternalServerError(w, err)
return
}
req, err := utils.GetJSONBody[struct {
Id int `json:"id"`
Username string `json:"username"`
}](r)
if err != nil || req == nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Id == 0 && req.Username == "" {
http.Error(w, "Either id or username must be provided", http.StatusBadRequest)
return
}
predicates := []predicate.User{}
if req.Id != 0 {
predicates = append(predicates, user.ID(req.Id))
}
if req.Username != "" {
predicates = append(predicates, user.Username(req.Username))
}
user, err := db.Client.User.Query().Where(predicates...).Only(r.Context())
if ent.IsNotFound(err) {
http.Error(w, "User not found", http.StatusNotFound)
return
}
if err != nil {
utils.BailInternalServerError(w, err)
return
}
utils.RespondWithJSON(w, map[string]any{
"id": user.ID,
"username": user.Username,
})
}

View File

@@ -0,0 +1,54 @@
package schema
import (
"encoding/json"
"regexp"
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"omctf.ru/block-game-backend/utils/xy"
)
// Level holds the schema definition for the Level entity.
type Level struct {
ent.Schema
}
// JSON data
type LevelData struct {
Size int `json:"size"`
Tiles []Tile `json:"tiles"`
}
type Tile struct {
Kind string `json:"kind"`
Pos xy.Point `json:"pos"`
Data json.RawMessage `json:"data"`
}
// Fields of the Level.
func (Level) Fields() []ent.Field {
return []ent.Field{
field.String("name").Unique().Match(regexp.MustCompile(`^\w{1,64}$`)),
field.String("description"),
field.Enum("visibility").Values("private", "public"),
field.JSON("data", LevelData{}),
field.String("prize"), // only for players who passed the level!!!
field.Time("createdAt").Default(func() (t time.Time) {
return time.Now().UTC()
}),
}
}
// Edges of the Level.
func (Level) Edges() []ent.Edge {
return []ent.Edge{
edge.From("owner", User.Type).
Ref("ownedLevels").
Unique(),
edge.From("invitedPlayers", User.Type).
Ref("invitedToLevels"),
}
}

View File

@@ -0,0 +1,27 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// Setting holds the schema definition for the Setting entity.
type Setting struct {
ent.Schema
}
// Fields of the Setting.
func (Setting) Fields() []ent.Field {
return []ent.Field{
field.String("key").
Unique().
NotEmpty(),
field.String("value").
NotEmpty(),
}
}
// Edges of the Setting.
func (Setting) Edges() []ent.Edge {
return nil
}

View File

@@ -0,0 +1,34 @@
package schema
import (
"regexp"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("username").
Unique().
Match(regexp.MustCompile(`^\w{1,64}$`)),
field.String("password").
MaxLen(128).
NotEmpty(),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.To("ownedLevels", Level.Type),
edge.To("invitedToLevels", Level.Type),
}
}

View File

@@ -0,0 +1,73 @@
package utils
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"omctf.ru/block-game-backend/codegen/ent/level"
"omctf.ru/block-game-backend/codegen/ent/predicate"
"omctf.ru/block-game-backend/codegen/ent/user"
"omctf.ru/block-game-backend/db"
)
func BailInternalServerError(w http.ResponseWriter, err error) {
http.Error(w, "Unexpected error", http.StatusInternalServerError)
log.Printf("Unexpected error occured: %v\n", err)
}
func RespondWithJSON(w http.ResponseWriter, o any) {
data, err := json.Marshal(o)
if err != nil {
BailInternalServerError(w, err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
func GetJSONBody[T any](r *http.Request) (*T, error) {
var req T
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
return nil, fmt.Errorf("invalid request body: %w", err)
}
return &req, nil
}
func MustMarshal(value any) json.RawMessage {
data, err := json.Marshal(value)
if err != nil {
log.Panicf("Can't marshal value %v: %s", value, err)
}
return data
}
func LevelAccessibleBy(userId int) predicate.Level {
return level.Or( // one of
level.HasOwnerWith(user.ID(userId)), // user owns the level
level.HasInvitedPlayersWith(user.ID(userId)), // or user is invited to the level
level.VisibilityEQ(level.VisibilityPublic), // or it's public
)
}
const (
CleanUpDelay = time.Hour * 1
)
func OccasionallyCleanUp() {
ticker := time.NewTicker(CleanUpDelay / 4)
for range ticker.C {
cnt, err := db.Client.Level.Delete().Where(
level.CreatedAtLT(time.Now().Add(-CleanUpDelay)),
).Exec(context.Background())
if err != nil {
log.Printf("Error during levels clean up: %s", err)
}
log.Printf("Cleaned up %d levels", cnt)
}
}

View File

@@ -0,0 +1,40 @@
package xy
import (
"fmt"
)
type Point struct {
X int `json:"x"`
Y int `json:"y"`
}
func (p Point) Go(dir Direction) (Point, error) {
switch dir {
case Up:
return Point{X: p.X, Y: p.Y - 1}, nil
case Down:
return Point{X: p.X, Y: p.Y + 1}, nil
case Left:
return Point{X: p.X - 1, Y: p.Y}, nil
case Right:
return Point{X: p.X + 1, Y: p.Y}, nil
}
return p, fmt.Errorf("invalid direction: %s", dir)
}
type Direction string
const (
Up Direction = "up"
Down Direction = "down"
Left Direction = "left"
Right Direction = "right"
)
func (d Direction) Validate() error {
if d == Up || d == Down || d == Left || d == Right {
return nil
}
return fmt.Errorf("invalid direction: %s (out of %v)", d, []Direction{Up, Down, Left, Right})
}

View File

@@ -0,0 +1,41 @@
name: block-game
services:
postgres:
image: postgres
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: blockgame
volumes:
- postgres_data_dev:/var/lib/postgresql/data
backend:
build:
context: backend
dockerfile: Dockerfile.dev
ports:
- 8081:8080
volumes:
- ./backend:/app
frontend:
build:
context: frontend
dockerfile: Dockerfile.dev
ports:
- "8082:3000"
environment:
- CHOKIDAR_USEPOLLING=true
- DANGEROUSLY_DISABLE_HOST_CHECK=true
volumes:
- ./frontend:/app
- /app/node_modules
- /app/build
router:
image: nginx:latest
ports:
- "8080:8080"
volumes:
- ./nginx.dev.conf:/etc/nginx/nginx.conf:ro
volumes:
postgres_data_dev:

View File

@@ -0,0 +1,29 @@
name: block-game
services:
postgres:
image: postgres:17.6-alpine3.22
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: blockgame
volumes:
- postgres_data:/var/lib/postgresql/data
restart: unless-stopped
backend:
build:
context: backend
dockerfile: Dockerfile
restart: unless-stopped
frontend:
build:
context: frontend
dockerfile: Dockerfile
environment:
- DANGEROUSLY_DISABLE_HOST_CHECK=true
ports:
- 5874:8080
restart: unless-stopped
volumes:
postgres_data:

View File

@@ -0,0 +1,2 @@
/node_modules
/build

View File

@@ -0,0 +1,2 @@
/node_modules
/build

View File

@@ -0,0 +1,19 @@
FROM node:24-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM nginx:latest
COPY --from=builder /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -0,0 +1,10 @@
FROM node:24-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
# Start development server with hot reload
CMD ["npm", "start"]

View File

@@ -0,0 +1,7 @@
# Frontend
WARNING: Heavily vibe-coded, but NO client-side exploits intended!
If you find any, text @maximxlss on telegram and get my appreciation.
NOTE: the checker mimics a PLAYER, only the things accessible from the app ;)

View File

@@ -0,0 +1,55 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
client_max_body_size 10M;
server {
listen 8080 default_server;
server_name _;
root /usr/share/nginx/html;
index index.html index.htm;
location /api/ {
rewrite ^/api/(.*) /$1 break;
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
}
location / {
try_files $uri $uri/ /index.html;
}
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_types
text/plain
text/css
application/javascript
application/json
image/svg+xml;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
{
"name": "block-game-frontend",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/node": "24.6.0",
"@types/react": "19.1.16",
"@types/react-dom": "19.1.9",
"react": "19.1.1",
"react-dom": "19.1.1",
"react-router-dom": "7.9.3",
"typescript": "^4.9.0",
"web-vitals": "5.1.0",
"axios": "1.12.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"react-scripts": "5.0.1"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta name="description" content="Block Game - A puzzle game where you move blocks to reach the exit" />
<title>Block Game</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>

View File

@@ -0,0 +1,79 @@
@import './shared.css';
/* Global App Styles */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
.app-loading {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.loading-spinner {
width: 50px;
height: 50px;
margin-bottom: 1rem;
}
.app-loading p {
font-size: 1.2rem;
margin: 0;
}
.app-error {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
color: white;
text-align: center;
padding: 2rem;
}
.app-error h1 {
margin-bottom: 1rem;
}
.app-error button {
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
color: white;
padding: 0.75rem 1.5rem;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
transition: all 0.3s ease;
}
.app-error button:hover {
background: rgba(255, 255, 255, 0.4);
border-color: rgba(255, 255, 255, 0.6);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

View File

@@ -0,0 +1,152 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Login from './components/Auth/Login';
import Register from './components/Auth/Register';
import LevelList from './components/Levels/LevelList';
import LevelEditor from './components/Levels/LevelEditor';
import GamePlayer from './components/Game/GamePlayer';
import { authAPI } from './api';
import { Level } from './types';
import './App.css';
type AppState = 'login' | 'register' | 'levels' | 'playing' | 'editing';
const App: React.FC = () => {
const [appState, setAppState] = useState<AppState>('login');
const [currentLevelId, setCurrentLevelId] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [authStatusMessage, setAuthStatusMessage] = useState<string | null>(null);
useEffect(() => {
// Check if user is already logged in via cookie
validateAuth();
}, []);
const validateAuth = async () => {
try {
await authAPI.whoami();
setAppState('levels');
setAuthStatusMessage(null);
} catch (error: unknown) {
const message = axios.isAxiosError(error) && error.response?.status === 400
? (typeof error.response.data === 'string' ? error.response.data : error.response.data?.message || 'Bad Request')
: null;
setAuthStatusMessage(message ? `Auth check failed: ${message}` : null);
setAppState('login');
} finally {
setLoading(false);
}
};
const handleAuthSuccess = () => {
setAppState('levels');
setAuthStatusMessage(null);
};
const handleLogout = async () => {
try {
await authAPI.logout();
} catch (error) {
console.error('Logout failed:', error);
} finally {
setAppState('login');
setCurrentLevelId(null);
setAuthStatusMessage(null);
}
};
const handlePlayLevel = (levelId: number) => {
setCurrentLevelId(levelId);
setAppState('playing');
};
const handleCreateLevel = () => {
setAppState('editing');
};
const handleCancelEditor = () => {
setAppState('levels');
};
const handleLevelSaved = (level: Level) => {
console.log('Level saved:', level);
setAppState('levels');
};
const handleBackToLevels = () => {
setCurrentLevelId(null);
setAppState('levels');
};
if (loading) {
return (
<div className="app-loading">
<div className="loading-spinner"></div>
<p>Loading Block Game...</p>
</div>
);
}
switch (appState) {
case 'login':
return (
<Login
onLogin={handleAuthSuccess}
authStatusMessage={authStatusMessage ?? undefined}
onSwitchToRegister={() => {
setAuthStatusMessage(null);
setAppState('register');
}}
/>
);
case 'register':
return (
<Register
onRegister={handleAuthSuccess}
onSwitchToLogin={() => setAppState('login')}
/>
);
case 'levels':
return (
<LevelList
onPlayLevel={handlePlayLevel}
onCreateLevel={handleCreateLevel}
onLogout={handleLogout}
/>
);
case 'editing':
return (
<LevelEditor
onCancel={handleCancelEditor}
onSaved={handleLevelSaved}
/>
);
case 'playing':
if (!currentLevelId) {
setAppState('levels');
return null;
}
return (
<GamePlayer
levelId={currentLevelId}
onBack={handleBackToLevels}
/>
);
default:
return (
<div className="app-error">
<h1>Something went wrong</h1>
<button onClick={() => setAppState('login')}>
Go to Login
</button>
</div>
);
}
};
export default App;

View File

@@ -0,0 +1,65 @@
import axios from 'axios';
import { LoginRequest, RegisterRequest, User, Level, LevelSummary, LevelCreateRequest, LevelVisibility } from './types';
const { protocol, host } = window.location;
const HTTP_BASE = `${protocol}//${host}/api`;
const WS_BASE = `ws${protocol === 'https:' ? 's' : ''}://${host}/api`;
const api = axios.create({
baseURL: HTTP_BASE,
headers: { 'Content-Type': 'application/json' },
withCredentials: true,
});
export const authAPI = {
login: async (credentials: LoginRequest): Promise<User> => {
const response = await api.post('/auth/login', credentials);
return response.data;
},
register: async (credentials: RegisterRequest): Promise<User> => {
const response = await api.post('/auth/register', credentials);
return response.data;
},
logout: async (): Promise<void> => {
await api.post('/auth/logout');
},
whoami: async (): Promise<User> => {
const response = await api.get('/user');
return response.data;
},
};
export const levelAPI = {
listLevels: async (page?: number): Promise<LevelSummary[]> => {
const response = await api.get(`/user/levels`, {
params: { page },
});
return response.data;
},
getLevel: async (levelId: number): Promise<Level> => {
const response = await api.get(`/user/level/${levelId}`);
return response.data;
},
findLevel: async (name: string): Promise<Level> => {
const response = await api.get(`/user/level`, {
params: { name },
});
return response.data;
},
createLevel: async (levelData: LevelCreateRequest): Promise<Level> => {
const response = await api.post('/user/level', levelData);
return response.data;
},
getPlayLevelWS: (levelId: number): string => {
return `${WS_BASE}/user/level/${levelId}/play`;
},
};
export default api;

View File

@@ -0,0 +1,67 @@
@import '../../shared.css';
.auth-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.auth-form {
width: 100%;
max-width: 400px;
background: white;
color: #333;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}
.auth-form h2 {
text-align: center;
margin-bottom: 1.5rem;
color: #333;
}
.auth-button {
width: 100%;
padding: 0.75rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 5px;
font-size: 1rem;
cursor: pointer;
transition: opacity 0.3s;
margin-bottom: 1rem;
}
.auth-button:hover:not(:disabled) {
opacity: 0.9;
}
.auth-button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.link-button {
background: none;
border: none;
color: #667eea;
cursor: pointer;
text-decoration: underline;
font-size: inherit;
}
.link-button:hover {
color: #764ba2;
}
p {
text-align: center;
color: #666;
margin: 0;
}

View File

@@ -0,0 +1,84 @@
import React, { useState } from 'react';
import './Auth.css';
interface AuthFormProps {
title: string;
onSubmit: (credentials: { username: string; password: string }) => Promise<void>;
submitText: string;
loadingText: string;
additionalFields?: React.ReactNode;
footer: React.ReactNode;
authStatusMessage?: string;
}
const AuthForm: React.FC<AuthFormProps> = ({
title,
onSubmit,
submitText,
loadingText,
additionalFields,
footer,
authStatusMessage
}) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
await onSubmit({ username, password });
} catch (err: any) {
setError(`${title} failed: ${err}`);
} finally {
setLoading(false);
}
};
return (
<div className="auth-container">
<div className="auth-form">
<h2>{title}</h2>
{authStatusMessage && (
<div className="info-message">{authStatusMessage}</div>
)}
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
disabled={loading}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
disabled={loading}
/>
</div>
{additionalFields}
{error && <div className="error-message">{error}</div>}
<button type="submit" disabled={loading} className="auth-button">
{loading ? loadingText : submitText}
</button>
</form>
{footer}
</div>
</div>
);
};
export default AuthForm;

View File

@@ -0,0 +1,36 @@
import React from 'react';
import { authAPI } from '../../api';
import AuthForm from './AuthForm';
interface LoginProps {
onLogin: () => void;
onSwitchToRegister: () => void;
authStatusMessage?: string;
}
const Login: React.FC<LoginProps> = ({ onLogin, onSwitchToRegister, authStatusMessage }) => {
const handleLogin = async (credentials: { username: string; password: string }) => {
await authAPI.login(credentials);
onLogin();
};
return (
<AuthForm
title="Login to Block Game"
onSubmit={handleLogin}
submitText="Login"
loadingText="Logging in..."
authStatusMessage={authStatusMessage}
footer={
<p>
Don't have an account?{' '}
<button onClick={onSwitchToRegister} className="link-button">
Register here
</button>
</p>
}
/>
);
};
export default Login;

View File

@@ -0,0 +1,51 @@
import React, { useState } from 'react';
import { authAPI } from '../../api';
import AuthForm from './AuthForm';
interface RegisterProps {
onRegister: () => void;
onSwitchToLogin: () => void;
}
const Register: React.FC<RegisterProps> = ({ onRegister, onSwitchToLogin }) => {
const [confirmPassword, setConfirmPassword] = useState('');
const handleRegister = async (credentials: { username: string; password: string }) => {
if (credentials.password !== confirmPassword) {
throw new Error('Passwords do not match');
}
await authAPI.register(credentials);
onRegister();
};
return (
<AuthForm
title="Register for Block Game"
onSubmit={handleRegister}
submitText="Register"
loadingText="Creating Account..."
additionalFields={
<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password:</label>
<input
type="password"
id="confirmPassword"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
/>
</div>
}
footer={
<p>
Already have an account?{' '}
<button onClick={onSwitchToLogin} className="link-button">
Login here
</button>
</p>
}
/>
);
};
export default Register;

View File

@@ -0,0 +1,356 @@
/* Game Container */
.game-container {
display: flex;
flex-direction: column;
height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.game-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background: rgba(0, 0, 0, 0.1);
}
.game-header h1 {
margin: 0;
font-size: 1.5rem;
}
.game-controls {
display: flex;
gap: 1rem;
align-items: center;
}
.connection-status {
padding: 0.5rem 1rem;
background: rgba(0, 0, 0, 0.3);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 5px;
font-size: 0.9rem;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.back-button,
.restart-button {
padding: 0.5rem 1rem;
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
color: white;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.back-button:hover,
.restart-button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.4);
border-color: rgba(255, 255, 255, 0.6);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.restart-button {
background: rgba(255, 165, 0, 0.9);
border-color: rgba(255, 165, 0, 0.9);
color: white;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
}
.restart-button:hover:not(:disabled) {
background: rgba(255, 140, 0, 1);
border-color: rgba(255, 140, 0, 1);
box-shadow: 0 2px 8px rgba(255, 165, 0, 0.4);
}
.restart-button:disabled {
background: rgba(200, 200, 200, 0.3);
border-color: rgba(200, 200, 200, 0.3);
color: rgba(255, 255, 255, 0.6);
cursor: not-allowed;
opacity: 0.6;
text-shadow: none;
transform: none;
box-shadow: none;
}
/* Game Main Area */
.game-main {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
padding: 2rem;
position: relative;
}
/* Game Board */
.game-board {
background: rgba(255, 255, 255, 0.95);
border-radius: 10px;
padding: 1rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}
/* Button and Door State Indicators */
.game-cell.button-pressed {
background: #ffd700 !important;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.2) !important;
}
.game-cell.door-opened {
background: #90ee90 !important;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1) !important;
}
.game-grid {
display: grid;
gap: 2px;
background: #ddd;
border: 2px solid #999;
}
.game-cell {
width: 40px;
height: 40px;
background: #f0f0f0;
position: relative;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.3s ease;
}
.tile {
position: absolute;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
z-index: 1;
transition: background 0.3s ease, transform 0.2s ease, opacity 0.3s ease, box-shadow 0.2s ease;
}
.tile-player {
z-index: 6;
}
.tile-box {
z-index: 5;
}
.tile-wall {
background: #654321;
border: 2px solid #8b4513;
z-index: 4;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.3);
}
.tile-door {
background: #8b4513;
border: 2px solid #cd853f;
z-index: 3;
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.2);
}
.tile-button {
background: #ffd700;
border: 2px solid #ffb300;
z-index: 2;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
.tile-button.pressed {
background: #ff8c00;
border-color: #ff6600;
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.4);
transform: scale(0.95);
}
.tile-door.opened {
background: #90ee90;
border-color: #32cd32;
opacity: 0.8;
box-shadow: 0 0 8px rgba(50, 205, 50, 0.4);
}
.tile-exit {
background: #228b22;
border: 2px solid #32cd32;
z-index: 2;
box-shadow: 0 0 8px rgba(50, 205, 50, 0.3);
}
/* Level Complete Modal */
.level-complete-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.7);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.level-complete-modal {
background: white;
color: #333;
padding: 2rem;
border-radius: 15px;
text-align: center;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
max-width: 400px;
border: 2px solid rgba(102, 126, 234, 0.2);
}
/* Dark mode support (respects user preference but doesn't override our design) */
@media (prefers-color-scheme: dark) {
.level-complete-modal {
background: #f8f9fa;
border-color: rgba(102, 126, 234, 0.3);
}
}
.level-complete-modal h2 {
margin: 0 0 1rem 0;
color: #32CD32;
}
.prize {
font-size: 1.1rem;
margin: 1rem 0;
font-weight: bold;
}
.continue-button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 0.75rem 1.5rem;
font-size: 1rem;
border-radius: 5px;
cursor: pointer;
margin-top: 1rem;
transition: transform 0.2s, box-shadow 0.2s;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.continue-button:hover {
background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
.continue-button:active {
transform: translateY(0);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
/* Game Instructions */
.game-instructions {
background: rgba(0, 0, 0, 0.1);
padding: 1rem 2rem;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.game-instructions h3 {
margin: 0 0 0.5rem 0;
}
.controls-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 0.5rem;
margin-bottom: 0.5rem;
}
.controls-grid div {
font-size: 0.9rem;
background: rgba(255, 255, 255, 0.1);
padding: 0.25rem 0.5rem;
border-radius: 3px;
}
/* Loading and Error States */
.game-loading,
.game-error {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
text-align: center;
}
.loading-spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid white;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 1rem;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.game-error h2 {
margin: 0 0 1rem 0;
}
.game-error p {
margin: 0 0 1rem 0;
}
/* Responsive Design */
@media (max-width: 768px) {
.game-header {
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
.game-controls {
flex-direction: column;
gap: 0.5rem;
}
.game-main {
padding: 1rem;
}
.game-cell {
width: 30px;
height: 30px;
}
.tile {
font-size: 1.2rem;
}
.controls-grid {
grid-template-columns: 1fr 1fr;
}
}

View File

@@ -0,0 +1,217 @@
import React, { useMemo, useCallback } from 'react';
import { Tiles, Tile } from '../../types';
import './Game.css';
interface GameBoardProps {
tiles: Tiles;
}
const TILE_PRIORITY = {
floor: 0,
button: 1,
exit: 2,
door: 3,
wall: 4,
box: 5,
player: 6
} as const;
type TileKind = keyof typeof TILE_PRIORITY;
const TILE_SYMBOLS: Record<string, string> = {
'player': '🚶',
'wall': '🧱',
'box': '📦',
'door': '🚪',
'button': '🔘',
'exit': '🏁',
'floor': ''
};
function areSetsEqual<T>(setA: Set<T>, setB: Set<T>): boolean {
if (setA.size !== setB.size) {
return false;
}
for (const item of setA) {
if (!setB.has(item)) {
return false;
}
}
return true;
}
const GameCell: React.FC<{
tileKinds: Set<TileKind>;
hasButton?: boolean;
isButtonPressed?: boolean;
isDoorOpened?: boolean;
}> = React.memo(({ tileKinds, hasButton, isButtonPressed, isDoorOpened }) => {
const tileKindsWithButton: TileKind[] = hasButton ? [...tileKinds, 'button'] : [...tileKinds];
const sortedTiles = [...tileKindsWithButton].sort((a, b) => {
const priorityA = TILE_PRIORITY[a] ?? 0;
const priorityB = TILE_PRIORITY[b] ?? 0;
return priorityA - priorityB;
});
const classList = [
'game-cell',
...sortedTiles.map(kind => `has-${kind}`)
];
if (isButtonPressed) classList.push('button-pressed');
if (isDoorOpened) classList.push('door-opened');
const cellClasses = classList.join(' ');
return (
<div
className={cellClasses}
role="gridcell"
>
{hasButton && (
<div
key="button"
className={[`tile`, `tile-button`, isButtonPressed ? 'pressed' : ''].filter(Boolean).join(' ')}
role="img"
>
{TILE_SYMBOLS['button']}
</div>
)}
{sortedTiles.map((tileKind, idx) => {
const tileClasses = [`tile`, `tile-${tileKind}`];
if (tileKind === 'button' && isButtonPressed) {
tileClasses.push('pressed');
}
if (tileKind === 'door' && isDoorOpened) {
tileClasses.push('opened');
}
return (
<div
key={`${tileKind}-${idx}`}
className={tileClasses.join(' ')}
role="img"
>
{TILE_SYMBOLS[tileKind] || ''}
</div>
);
})}
</div>
);
}, (prevProps, nextProps) => {
return (
prevProps.hasButton === nextProps.hasButton &&
prevProps.isButtonPressed === nextProps.isButtonPressed &&
prevProps.isDoorOpened === nextProps.isDoorOpened &&
areSetsEqual(prevProps.tileKinds, nextProps.tileKinds)
);
});
GameCell.displayName = 'GameCell';
const GameBoard: React.FC<GameBoardProps> = React.memo(({ tiles }) => {
const size = tiles?.size || 1;
// Create efficient tile lookup map
const tileMap = useMemo(() => {
const map = new Map<string, Tile[]>();
if (tiles?.tiles) {
for (const tile of tiles.tiles) {
const key = `${tile.pos.x},${tile.pos.y}`;
if (!map.has(key)) {
map.set(key, []);
}
map.get(key)!.push(tile);
}
}
return map;
}, [tiles]);
// Memo all button positions and their states
const { buttonStates, doorStates, buttonPositions } = useMemo(() => {
const buttonPressed = new Map<string, boolean>();
const doorOpened = new Map<string, boolean>();
const buttonPositions = new Map<string, boolean>();
if (!tiles?.tiles) return { buttonStates: buttonPressed, doorStates: doorOpened, buttonPositions };
const doors = tiles.tiles.filter(tile => tile.kind === 'door');
doors.forEach(door => {
const doorKey = `${door.pos.x},${door.pos.y}`;
let isOpened = false;
if (door.data && door.data.button_position) {
const buttonPos = door.data.button_position;
const buttonKey = `${buttonPos.x},${buttonPos.y}`;
buttonPositions.set(buttonKey, true);
const tilesAtButtonPosition = tileMap.get(buttonKey) || [];
const isPressed = tilesAtButtonPosition.some(tile =>
tile.kind === 'player' || tile.kind === 'box'
);
buttonPressed.set(buttonKey, isPressed);
isOpened = isPressed;
}
doorOpened.set(doorKey, isOpened);
});
return { buttonStates: buttonPressed, doorStates: doorOpened, buttonPositions };
}, [tiles, tileMap]);
const getTileKindsAtPosition = useCallback((x: number, y: number): Set<TileKind> => {
const positionKey = `${x},${y}`;
const existingTiles = tileMap.get(positionKey) || [];
return new Set(existingTiles.map(tile => tile.kind as TileKind));
}, [tileMap]);
const pointHasButton = useCallback((x: number, y: number): boolean => {
return buttonPositions.has(`${x},${y}`);
}, [buttonPositions]);
const isButtonPressed = useCallback((x: number, y: number): boolean => {
const positionKey = `${x},${y}`;
return buttonPositions.has(positionKey) && (buttonStates.get(positionKey) || false);
}, [buttonStates, buttonPositions]);
const isDoorOpened = useCallback((x: number, y: number): boolean => {
return doorStates.get(`${x},${y}`) || false;
}, [doorStates]);
return (
<div className="game-board">
<div
className="game-grid"
role="grid"
aria-label={`Game board ${size} by ${size}`}
style={{
gridTemplateColumns: `repeat(${size}, 1fr)`,
gridTemplateRows: `repeat(${size}, 1fr)`
}}
>
{Array.from({ length: size * size }, (_, index) => {
const x = index % size;
const y = Math.floor(index / size);
return (
<GameCell
key={`${x}-${y}`}
tileKinds={getTileKindsAtPosition(x, y)}
hasButton={pointHasButton(x, y)}
isButtonPressed={isButtonPressed(x, y)}
isDoorOpened={isDoorOpened(x, y)}
/>
);
})}
</div>
</div>
);
});
export default GameBoard;

View File

@@ -0,0 +1,214 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useWebSocketGame } from '../../hooks/useWebSocketGame';
import { levelAPI } from '../../api';
import { Level, Direction, Tiles } from '../../types';
import GameBoard from './GameBoard';
import './Game.css';
interface GamePlayerProps {
levelId: number;
onBack: () => void;
}
const GamePlayer: React.FC<GamePlayerProps> = ({ levelId, onBack }) => {
const [level, setLevel] = useState<Level | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [tiles, setTiles] = useState<Tiles | null>(null);
const [wsUrl, setWsUrl] = useState<string | null>(null);
const {
connected,
levelComplete,
prize,
sendMove
} = useWebSocketGame(wsUrl, tiles, setTiles);
useEffect(() => {
loadLevel();
}, [levelId]);
const loadLevel = async () => {
try {
setLoading(true);
const levelData = await levelAPI.getLevel(levelId);
setLevel(levelData);
// Set tiles first
setTiles(levelData.data);
// Only after tiles are loaded, set WebSocket URL to initiate connection
const url = levelAPI.getPlayLevelWS(levelId);
setWsUrl(url);
} catch (err: any) {
setError(err.response?.data?.message || 'Failed to load level');
} finally {
setLoading(false);
}
};
const handleRestart = useCallback(() => {
// Force reconnection by clearing the WebSocket URL and resetting state
setWsUrl(null);
// Reset tiles to the original level data
if (level) {
setTiles(level.data);
}
// Force a new WebSocket connection by setting the URL again
// We need to do this after a small delay to ensure the old connection is fully closed
setTimeout(() => {
const url = levelAPI.getPlayLevelWS(levelId);
setWsUrl(url);
}, 100);
}, [level, levelId]);
const handleKeyPress = useCallback((event: KeyboardEvent) => {
if (!connected || levelComplete || !tiles) return;
let direction: Direction;
switch (event.key.toLowerCase()) {
case 'arrowup':
case 'w':
direction = 'up';
break;
case 'arrowdown':
case 's':
direction = 'down';
break;
case 'arrowleft':
case 'a':
direction = 'left';
break;
case 'arrowright':
case 'd':
direction = 'right';
break;
default:
return;
}
// Find the player's current position
const player = tiles.tiles.find(tile => tile.kind === 'player');
if (!player) {
console.warn('Player not found on board');
return;
}
// Calculate the new position
let newX = player.pos.x;
let newY = player.pos.y;
switch (direction) {
case 'up':
newY -= 1;
break;
case 'down':
newY += 1;
break;
case 'left':
newX -= 1;
break;
case 'right':
newX += 1;
break;
}
// Check bounds - prevent moves outside the board
if (newX < 0 || newX >= tiles.size || newY < 0 || newY >= tiles.size) {
console.log(`Move blocked: would go out of bounds (${newX}, ${newY}) on ${tiles.size}x${tiles.size} board`);
return;
}
event.preventDefault();
sendMove(direction);
}, [connected, levelComplete, tiles, sendMove]);
useEffect(() => {
window.addEventListener('keydown', handleKeyPress);
return () => {
window.removeEventListener('keydown', handleKeyPress);
};
}, [handleKeyPress]);
if (loading) {
return (
<div className="game-loading">
<div className="loading-spinner"></div>
<p>Loading level...</p>
</div>
);
}
if (error) {
return (
<div className="game-error">
<h2>Error</h2>
<p>{error}</p>
<button onClick={onBack} className="back-button">
Back to Levels
</button>
</div>
);
}
if (!level) {
return (
<div className="game-error">
<h2>Level not found</h2>
<button onClick={onBack} className="back-button">
Back to Levels
</button>
</div>
);
}
return (
<div className="game-container">
<div className="game-header">
<h1>{level.name}</h1>
<div className="game-controls">
<div className="connection-status">
Status: {connected ? 'Connected' : 'Disconnected'}
</div>
<button onClick={handleRestart} className="restart-button" disabled={!level}>
🔄 Restart
</button>
<button onClick={onBack} className="back-button">
Back to Levels
</button>
</div>
</div>
<div className="game-main">
{tiles && <GameBoard tiles={tiles} />}
{levelComplete && (
<div className="level-complete-overlay">
<div className="level-complete-modal">
<h2>🎉 Level Complete!</h2>
<p className="prize">Prize: {prize}</p>
<button onClick={onBack} className="continue-button">
Continue
</button>
</div>
</div>
)}
</div>
<div className="game-instructions">
<h3>Controls</h3>
<div className="controls-grid">
<div> / W - Move Up</div>
<div> / S - Move Down</div>
<div> / A - Move Left</div>
<div> / D - Move Right</div>
</div>
<p>Push boxes to buttons to open doors. Reach the exit to win!</p>
</div>
</div>
);
};
export default GamePlayer;

View File

@@ -0,0 +1,472 @@
/* Level Editor Styles */
.level-editor {
height: 100vh;
display: flex;
flex-direction: column;
background: #f5f5f5;
overflow: hidden;
}
.level-editor-header {
background: #2c3e50;
color: white;
padding: 1rem 2rem;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
z-index: 100;
}
.level-editor-header h1 {
margin: 0;
font-size: 1.5rem;
font-weight: 600;
}
.header-actions {
display: flex;
gap: 0.5rem;
}
.cancel-button {
background: #e74c3c;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
transition: background-color 0.2s;
}
.cancel-button:hover {
background: #c0392b;
}
.level-editor-content {
flex: 1;
display: flex;
overflow: hidden;
}
/* Sidebar */
.editor-sidebar {
width: 320px;
background: white;
border-right: 1px solid #ddd;
padding: 1.5rem;
overflow-y: auto;
box-shadow: 2px 0 4px rgba(0, 0, 0, 0.05);
}
.editor-section {
margin-bottom: 2rem;
padding-bottom: 1.5rem;
border-bottom: 1px solid #eee;
}
.editor-section:last-child {
border-bottom: none;
margin-bottom: 0;
}
.editor-section h3 {
margin: 0 0 1rem 0;
color: #2c3e50;
font-size: 1.1rem;
font-weight: 600;
display: flex;
justify-content: space-between;
align-items: center;
}
.cancel-link-button {
background: #f39c12;
color: white;
border: none;
padding: 0.25rem 0.5rem;
border-radius: 3px;
font-size: 0.8rem;
cursor: pointer;
}
.cancel-link-button:hover {
background: #e67e22;
}
/* Form Elements */
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
color: #555;
font-weight: 500;
}
.form-group input,
.form-group textarea {
width: 100%;
padding: 0.5rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 0.9rem;
box-sizing: border-box;
}
.form-group input:focus,
.form-group textarea:focus {
outline: none;
border-color: #3498db;
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}
.form-group textarea {
resize: vertical;
min-height: 60px;
}
.visibility-toggle {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.5rem;
}
.visibility-option {
border: 1px solid #d0d7de;
border-radius: 6px;
padding: 0.6rem 0.75rem;
font-size: 0.9rem;
background: #f8fafc;
color: #2c3e50;
cursor: pointer;
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
gap: 0.35rem;
}
.visibility-option:hover {
background: #eef5ff;
border-color: #3498db;
}
.visibility-option.active {
background: #3498db;
color: white;
border-color: #1f6fb2;
box-shadow: 0 2px 6px rgba(52, 152, 219, 0.35);
}
.form-helper {
margin-top: 0.35rem;
font-size: 0.8rem;
color: #6b7280;
line-height: 1.3;
}
.form-group input[type="range"] {
padding: 0;
height: 6px;
background: #ddd;
border-radius: 3px;
}
.clear-button {
background: #e74c3c;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
font-size: 0.9rem;
width: 100%;
}
.clear-button:hover {
background: #c0392b;
}
/* Linking Instructions */
.linking-instruction {
background: #f39c12;
color: white;
padding: 0.5rem;
border-radius: 4px;
font-size: 0.85rem;
margin-bottom: 1rem;
text-align: center;
}
/* Tool Grid */
.tool-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
.tool-button {
background: white;
border: 2px solid #ddd;
border-radius: 6px;
padding: 0.75rem 0.5rem;
cursor: pointer;
display: flex;
flex-direction: column;
align-items: center;
gap: 0.25rem;
transition: all 0.2s;
min-height: 60px;
}
.tool-button:hover:not(:disabled) {
border-color: #3498db;
transform: translateY(-1px);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.tool-button.selected {
border-color: #2c3e50;
color: white;
font-weight: 600;
}
.tool-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.tool-symbol {
font-size: 1.2rem;
}
.tool-name {
font-size: 0.75rem;
text-transform: capitalize;
}
/* Save Section */
.save-button {
background: #27ae60;
color: white;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
font-weight: 600;
width: 100%;
transition: background-color 0.2s;
}
.save-button:hover:not(:disabled) {
background: #229954;
}
.save-button:disabled {
background: #95a5a6;
cursor: not-allowed;
}
.error-message {
background: #e74c3c;
color: white;
padding: 0.5rem;
border-radius: 4px;
margin-top: 0.5rem;
font-size: 0.85rem;
}
/* Main Editor Area */
.editor-main {
flex: 1;
padding: 1.5rem;
overflow: auto;
}
.editor-board-container {
max-width: 100%;
margin: 0 auto;
}
.editor-instructions {
background: white;
padding: 1rem;
border-radius: 6px;
margin-bottom: 1rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.editor-instructions p {
margin: 0;
color: #555;
font-size: 0.9rem;
}
/* Editor Board */
.editor-board {
background: white;
padding: 1.5rem;
border-radius: 6px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
margin-bottom: 1.5rem;
}
.editor-grid {
display: grid;
gap: 2px;
max-width: 500px;
margin: 0 auto;
aspect-ratio: 1;
background: #34495e;
padding: 2px;
border-radius: 4px;
}
.editor-cell {
background: #ecf0f1;
position: relative;
cursor: pointer;
border-radius: 2px;
transition: all 0.1s;
min-height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.editor-cell:hover {
background: #d5dbdb;
transform: scale(0.95);
}
.editor-cell.has-selected-tool {
border: 2px solid #2c3e50;
}
.editor-cell.has-button-indicator {
box-shadow: inset 0 0 0 2px #ff6347;
}
.editor-cell.pending-door {
box-shadow: inset 0 0 0 3px #f39c12;
animation: pulse 1s infinite;
}
@keyframes pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.7;
}
}
.editor-tile {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 1.2rem;
z-index: 2;
pointer-events: none;
}
.editor-cell-coords {
position: absolute;
top: 2px;
left: 2px;
font-size: 0.6rem;
color: #95a5a6;
line-height: 1;
z-index: 1;
}
.button-indicator {
position: absolute;
top: 2px;
right: 2px;
font-size: 0.8rem;
z-index: 3;
background: rgba(255, 99, 71, 0.9);
border-radius: 50%;
width: 16px;
height: 16px;
display: flex;
align-items: center;
justify-content: center;
color: white;
}
/* Preview Section */
.editor-preview {
background: white;
padding: 1.5rem;
border-radius: 6px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.editor-preview h4 {
margin: 0 0 1rem 0;
color: #2c3e50;
font-size: 1rem;
}
.preview-container {
max-width: 300px;
margin: 0 auto;
}
.preview-container .game-board {
border: 1px solid #ddd;
border-radius: 4px;
overflow: hidden;
}
/* Responsive Design */
@media (max-width: 1200px) {
.editor-sidebar {
width: 280px;
}
.tool-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 768px) {
.level-editor-content {
flex-direction: column;
}
.editor-sidebar {
width: 100%;
max-height: 300px;
border-right: none;
border-bottom: 1px solid #ddd;
}
.level-editor-header {
padding: 1rem;
}
.level-editor-header h1 {
font-size: 1.2rem;
}
.editor-main {
padding: 1rem;
}
.editor-grid {
max-width: 100%;
}
}

View File

@@ -0,0 +1,412 @@
import React, { useState, useCallback, useMemo } from 'react';
import { Tile, Tiles, Point, Level, LevelVisibility, LevelCreateRequest } from '../../types';
import { levelAPI } from '../../api';
import GameBoard from '../Game/GameBoard';
import './LevelEditor.css';
interface LevelEditorProps {
onCancel: () => void;
onSaved: (level: Level) => void;
}
type TileType = 'wall' | 'box' | 'player' | 'exit' | 'door';
const TILE_CONFIG: Record<TileType, { symbol: string; color: string }> = {
wall: { symbol: '🧱', color: '#8b4513' },
box: { symbol: '📦', color: '#daa520' },
player: { symbol: '🚶', color: '#4169e1' },
exit: { symbol: '🏁', color: '#32cd32' },
door: { symbol: '🚪', color: '#9932cc' }
};
const LevelEditor: React.FC<LevelEditorProps> = ({ onCancel, onSaved }) => {
const [boardSize, setBoardSize] = useState<number>(5);
const [selectedTool, setSelectedTool] = useState<TileType>('wall');
const [levelName, setLevelName] = useState<string>('');
const [levelDescription, setLevelDescription] = useState<string>('');
const [levelPrize, setLevelPrize] = useState<string>('');
const [tiles, setTiles] = useState<Tile[]>([]);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string>('');
const [visibility, setVisibility] = useState<LevelVisibility>('public');
const [linkingMode, setLinkingMode] = useState<'none' | 'selecting-button-position'>('none');
const [pendingDoorPosition, setPendingDoorPosition] = useState<Point | null>(null);
const boardTiles: Tiles = useMemo(() => ({
size: boardSize,
tiles: tiles
}), [boardSize, tiles]);
const getTilesAt = useCallback((x: number, y: number): Tile[] => {
return tiles.filter(tile => tile.pos.x === x && tile.pos.y === y);
}, [tiles]);
const hasTileType = useCallback((x: number, y: number, type: TileType): boolean => {
return getTilesAt(x, y).some(tile => tile.kind === type);
}, [getTilesAt]);
const getButtonPositions = useCallback((): Set<string> => {
const buttonPositions = new Set<string>();
tiles.forEach(tile => {
if (tile.kind === 'door' && tile.data?.button_position) {
const pos = tile.data.button_position;
buttonPositions.add(`${pos.x},${pos.y}`);
}
});
return buttonPositions;
}, [tiles]);
const hasButtonAt = useCallback((x: number, y: number): boolean => {
const buttonPositions = getButtonPositions();
return buttonPositions.has(`${x},${y}`);
}, [getButtonPositions]);
const toggleTile = useCallback((x: number, y: number, tileType: TileType) => {
setTiles(prevTiles => {
let newTiles = [...prevTiles];
newTiles = newTiles.filter(tile =>
!(tile.pos.x === x && tile.pos.y === y && tile.kind === tileType)
);
if (tileType === 'player') {
newTiles = newTiles.filter(tile => tile.kind !== 'player');
} else if (tileType === 'exit') {
newTiles = newTiles.filter(tile => tile.kind !== 'exit');
}
const wasRemoved = prevTiles.some(tile =>
tile.pos.x === x && tile.pos.y === y && tile.kind === tileType
);
if (!wasRemoved) {
const newTile: Tile = {
kind: tileType,
pos: { x, y },
data: {}
};
newTiles.push(newTile);
}
return newTiles;
});
}, []);
const handleCellClick = useCallback((x: number, y: number) => {
if (linkingMode === 'selecting-button-position' && pendingDoorPosition) {
setTiles(prevTiles => {
return prevTiles.map(tile => {
if (tile.kind === 'door' &&
tile.pos.x === pendingDoorPosition.x &&
tile.pos.y === pendingDoorPosition.y) {
return {
...tile,
data: { button_position: { x, y } }
};
}
return tile;
});
});
setLinkingMode('none');
setPendingDoorPosition(null);
} else {
const doorAtPosition = getTilesAt(x, y).find(tile => tile.kind === 'door');
if (doorAtPosition && selectedTool === 'door') {
setTiles(prevTiles => {
return prevTiles.filter(tile =>
!(tile.kind === 'door' && tile.pos.x === x && tile.pos.y === y)
);
});
} else if (doorAtPosition) {
setPendingDoorPosition({ x, y });
setLinkingMode('selecting-button-position');
} else if (selectedTool === 'door') {
const newDoor: Tile = {
kind: 'door',
pos: { x, y },
data: {}
};
setTiles(prevTiles => {
const filtered = prevTiles.filter(tile =>
!(tile.pos.x === x && tile.pos.y === y)
);
return [...filtered, newDoor];
});
setPendingDoorPosition({ x, y });
setLinkingMode('selecting-button-position');
} else {
toggleTile(x, y, selectedTool);
}
}
}, [selectedTool, linkingMode, pendingDoorPosition, toggleTile, getTilesAt]);
const clearBoard = useCallback(() => {
setTiles([]);
setLinkingMode('none');
setPendingDoorPosition(null);
}, []);
const validateLevel = useCallback((): string | null => {
if (!levelName.trim()) return 'Level name is required';
if (!levelPrize.trim()) return 'Level prize is required';
const tileKinds = new Set(tiles.map(t => t.kind));
if (!tileKinds.has('player')) return 'Level must have a player start position';
if (!tileKinds.has('exit')) return 'Level must have an exit';
return null;
}, [levelName, levelPrize, tiles]);
const saveLevel = useCallback(async () => {
const validationError = validateLevel();
if (validationError) {
setError(validationError);
return;
}
setSaving(true);
setError('');
try {
const levelData: LevelCreateRequest = {
name: levelName.trim(),
description: levelDescription.trim(),
prize: levelPrize.trim(),
visibility,
data: {
size: boardSize,
tiles: tiles
}
};
const savedLevel = await levelAPI.createLevel(levelData);
onSaved(savedLevel);
} catch (err: any) {
setError(err.response?.data?.message || 'Failed to save level');
} finally {
setSaving(false);
}
}, [validateLevel, levelName, levelDescription, levelPrize, boardSize, tiles, onSaved]);
const cancelLinking = useCallback(() => {
setLinkingMode('none');
setPendingDoorPosition(null);
}, []);
return (
<div className="level-editor">
<div className="level-editor-header">
<h1>Level Editor</h1>
<div className="header-actions">
<button onClick={onCancel} className="cancel-button">
Cancel
</button>
</div>
</div>
<div className="level-editor-content">
<div className="editor-sidebar">
<div className="editor-section">
<h3>Level Information</h3>
<div className="form-group">
<label>Name:</label>
<input
type="text"
value={levelName}
onChange={(e) => setLevelName(e.target.value)}
placeholder="Enter level name"
maxLength={50}
/>
</div>
<div className="form-group">
<label>Description:</label>
<textarea
value={levelDescription}
onChange={(e) => setLevelDescription(e.target.value)}
placeholder="Describe your level (optional)"
rows={3}
maxLength={200}
/>
</div>
<div className="form-group">
<label>Prize:</label>
<input
type="text"
value={levelPrize}
onChange={(e) => setLevelPrize(e.target.value)}
placeholder="What does the player win?"
maxLength={30}
/>
</div>
</div>
<div className="editor-section">
<h3>Board Settings</h3>
<div className="form-group">
<label>Size: {boardSize}x{boardSize}</label>
<input
type="range"
min="3"
max="10"
value={boardSize}
onChange={(e) => setBoardSize(parseInt(e.target.value))}
/>
</div>
<button onClick={clearBoard} className="clear-button">
🗑 Clear Board
</button>
</div>
<div className="editor-section">
<h3>
Tools
{linkingMode !== 'none' && (
<button onClick={cancelLinking} className="cancel-link-button">
Cancel Linking
</button>
)}
</h3>
{linkingMode === 'selecting-button-position' && (
<div className="linking-instruction">
Click where you want the button for this door (position {pendingDoorPosition?.x},{pendingDoorPosition?.y})
</div>
)}
<div className="tool-grid">
{Object.entries(TILE_CONFIG).map(([type, config]) => (
<button
key={type}
className={`tool-button ${selectedTool === type ? 'selected' : ''}`}
onClick={() => setSelectedTool(type as TileType)}
style={{
backgroundColor: selectedTool === type ? config.color : undefined,
opacity: linkingMode !== 'none' ? 0.5 : 1
}}
disabled={linkingMode !== 'none'}
title={type}
>
<span className="tool-symbol">{config.symbol}</span>
<span className="tool-name">{type}</span>
</button>
))}
</div>
</div>
<div className="editor-section">
<button
onClick={saveLevel}
className="save-button"
disabled={saving}
>
{saving ? '💾 Saving...' : '💾 Save Level'}
</button>
{error && <div className="error-message">{error}</div>}
</div>
<div className="form-group">
<label>Visibility:</label>
<div className="visibility-toggle" role="radiogroup" aria-label="Level visibility">
<button
type="button"
className={`visibility-option ${visibility === 'public' ? 'active' : ''}`}
onClick={() => setVisibility('public')}
aria-pressed={visibility === 'public'}
>
🌍 Public
</button>
<button
type="button"
className={`visibility-option ${visibility === 'private' ? 'active' : ''}`}
onClick={() => setVisibility('private')}
aria-pressed={visibility === 'private'}
>
🔒 Private
</button>
</div>
<p className="form-helper">
Public levels can be discovered by other players. Switch to private if you want to keep it for yourself.
</p>
</div>
</div>
<div className="editor-main">
<div className="editor-board-container">
<div className="editor-instructions">
<p>
{linkingMode === 'none'
? selectedTool === 'door'
? 'Click to place a door, then you\'ll choose its button position. Click existing doors with door tool to DELETE them, or click with other tools to edit their button position.'
: `Click on the board to place ${selectedTool} tiles. Click again to remove.`
: 'Click where you want the button for the selected door'
}
</p>
</div>
<div className="editor-board">
<div
className="editor-grid"
style={{
gridTemplateColumns: `repeat(${boardSize}, 1fr)`,
gridTemplateRows: `repeat(${boardSize}, 1fr)`
}}
>
{Array.from({ length: boardSize }, (_, row) =>
Array.from({ length: boardSize }, (_, col) => {
const tilesAtPosition = getTilesAt(col, row);
const hasCurrentTool = hasTileType(col, row, selectedTool);
const hasButton = hasButtonAt(col, row);
const isPendingDoor = pendingDoorPosition?.x === col && pendingDoorPosition?.y === row;
return (
<div
key={`${col},${row}`}
className={`editor-cell ${hasCurrentTool ? 'has-selected-tool' : ''
} ${hasButton ? 'has-button-indicator' : ''
} ${isPendingDoor ? 'pending-door' : ''
}`}
onClick={() => handleCellClick(col, row)}
style={{
backgroundColor: hasCurrentTool ? TILE_CONFIG[selectedTool].color : undefined
}}
>
{tilesAtPosition.map((tile, idx) => (
<div
key={`${tile.kind}-${idx}`}
className={`editor-tile tile-${tile.kind}`}
title={tile.kind}
>
{TILE_CONFIG[tile.kind as TileType]?.symbol || ''}
</div>
))}
{hasButton && (
<div className="button-indicator" title="Button position">
🔘
</div>
)}
<div className="editor-cell-coords">
{col},{row}
</div>
</div>
);
})
)}
</div>
</div>
<div className="editor-preview">
<h4>Game Preview:</h4>
<div className="preview-container">
<GameBoard tiles={boardTiles} />
</div>
</div>
</div>
</div>
</div>
</div>
);
};
export default LevelEditor;

View File

@@ -0,0 +1,275 @@
import React, { useState, useEffect, useCallback } from 'react';
import { LevelSummary } from '../../types';
import { levelAPI } from '../../api';
import './Levels.css';
interface LevelListProps {
onPlayLevel: (levelId: number) => void;
onCreateLevel: () => void;
onLogout: () => void;
}
const LevelList: React.FC<LevelListProps> = ({ onPlayLevel, onCreateLevel, onLogout }) => {
const [levels, setLevels] = useState<LevelSummary[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [page, setPage] = useState(0);
const [hasMore, setHasMore] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [isFindOpen, setIsFindOpen] = useState(false);
const [findName, setFindName] = useState('');
const [findError, setFindError] = useState('');
const [findLoading, setFindLoading] = useState(false);
const [loadMoreError, setLoadMoreError] = useState('');
const fetchLevels = useCallback(async (pageToLoad: number, append = false) => {
try {
if (append) {
setLoadingMore(true);
setLoadMoreError('');
} else {
setLoading(true);
setError('');
setLoadMoreError('');
setHasMore(true);
setPage(0);
}
const levelData = await levelAPI.listLevels(pageToLoad);
if (append) {
setLevels((prevLevels) => {
const existingIds = new Set(prevLevels.map((level) => level.id));
const uniqueLevels = levelData.filter((level) => !existingIds.has(level.id));
return uniqueLevels.length > 0 ? [...prevLevels, ...uniqueLevels] : prevLevels;
});
} else {
setLevels(levelData);
}
if (levelData.length === 0) {
setHasMore(false);
return;
}
setPage(pageToLoad);
setHasMore(true);
} catch (err: any) {
const message = err.response?.data?.message || (append ? 'Failed to load more levels' : 'Failed to load levels');
if (append) {
setLoadMoreError(message);
} else {
setError(message);
}
} finally {
if (append) {
setLoadingMore(false);
} else {
setLoading(false);
}
}
}, []);
useEffect(() => {
fetchLevels(0, false);
}, [fetchLevels]);
const handleRefresh = () => {
fetchLevels(0, false);
};
const handleLoadMore = () => {
if (!hasMore || loadingMore) {
return;
}
fetchLevels(page + 1, true);
};
const handleToggleFind = () => {
setFindError('');
setIsFindOpen((prev) => {
const next = !prev;
if (!next) {
setFindName('');
}
return next;
});
};
const handleFindLevel = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const trimmedName = findName.trim();
if (!trimmedName) {
setFindError('Enter a level name to search');
return;
}
try {
setFindLoading(true);
setFindError('');
const level = await levelAPI.findLevel(trimmedName);
setFindName('');
setIsFindOpen(false);
onPlayLevel(level.id);
} catch (err: any) {
setFindError(err.response?.data?.message || 'Level not found');
} finally {
setFindLoading(false);
}
};
if (loading) {
return (
<div className="levels-loading">
<div className="loading-spinner"></div>
<p>Loading levels...</p>
</div>
);
}
if (error) {
return (
<div className="levels-error">
<h2>Error</h2>
<p>{error}</p>
<button onClick={handleRefresh} className="retry-button">
Retry
</button>
<button onClick={onLogout} className="logout-button">
Logout
</button>
</div>
);
}
const getLevelNameSizeClass = (name: string) => {
if (name.length > 36) {
return 'level-name--xsmall';
}
if (name.length > 26) {
return 'level-name--small';
}
if (name.length > 18) {
return 'level-name--medium';
}
return 'level-name--regular';
};
return (
<div className="levels-container">
<div className="levels-header">
<h1>Block Game - Levels</h1>
<div className="header-actions">
<button onClick={onCreateLevel} className="create-button">
Create Level
</button>
<button onClick={handleRefresh} className="refresh-button">
🔄 Refresh
</button>
<button onClick={handleToggleFind} className="find-button" disabled={findLoading}>
🔍 Find Level
</button>
<button onClick={onLogout} className="logout-button">
Logout
</button>
</div>
</div>
{isFindOpen && (
<div className="find-level-panel">
<form onSubmit={handleFindLevel} className="find-level-form">
<input
type="text"
value={findName}
onChange={(event) => setFindName(event.target.value)}
placeholder="Enter level name"
className="find-level-input"
disabled={findLoading}
/>
<div className="find-level-controls">
<button type="submit" className="find-level-submit" disabled={findLoading}>
{findLoading ? 'Searching…' : 'Play'}
</button>
<button
type="button"
className="find-level-cancel"
onClick={handleToggleFind}
disabled={findLoading}
>
Cancel
</button>
</div>
</form>
{findError && <p className="find-level-error">{findError}</p>}
</div>
)}
<div className="levels-content">
{levels.length === 0 ? (
<div className="no-levels">
<h2>No levels available</h2>
<p>Create a level to get started!</p>
</div>
) : (
<>
<div className="levels-grid">
{levels.map((level) => (
<div key={level.id} className="level-card">
<div className="level-card-header">
<h3 className={`level-name ${getLevelNameSizeClass(level.name)}`}>
{level.name}
</h3>
<span className="level-id">#{level.id}</span>
</div>
<div className="level-card-content">
<p className="level-description">
{level.description?.trim() || 'No description available'}
</p>
{level.visibility === 'private' && (
<p className="level-visibility">🔒 Private level</p>
)}
</div>
<div className="level-card-actions">
<button
onClick={() => onPlayLevel(level.id)}
className="play-button"
>
🎮 Play Level
</button>
</div>
</div>
))}
</div>
{loadMoreError && <p className="load-more-error">{loadMoreError}</p>}
{hasMore && levels.length > 0 && (
<div className="load-more-container">
<button
onClick={handleLoadMore}
className="load-more-button"
disabled={loadingMore}
>
{loadingMore ? 'Loading more…' : 'Load more levels'}
</button>
</div>
)}
</>
)}
</div>
<div className="levels-footer">
<p>Select a level to start playing!</p>
<div className="game-info">
<div>🎯 Goal: Reach the exit</div>
<div>📦 Push boxes to press buttons</div>
<div>🚪 Open doors by pressing buttons</div>
</div>
</div>
</div>
);
};
export default LevelList;

View File

@@ -0,0 +1,491 @@
/* Levels Container */
.levels-container {
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
flex-direction: column;
}
.levels-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background: rgba(0, 0, 0, 0.1);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.levels-header h1 {
margin: 0;
font-size: 1.8rem;
}
.header-actions {
display: flex;
gap: 1rem;
align-items: center;
}
.create-button,
.refresh-button,
.logout-button,
.retry-button,
.find-button {
padding: 0.5rem 1rem;
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
color: white;
border-radius: 5px;
cursor: pointer;
transition: all 0.3s ease;
font-size: 0.9rem;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.create-button:hover,
.refresh-button:hover,
.logout-button:hover,
.retry-button:hover,
.find-button:hover {
background: rgba(255, 255, 255, 0.4);
border-color: rgba(255, 255, 255, 0.6);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.create-button {
background: rgba(40, 167, 69, 0.8);
border-color: rgba(40, 167, 69, 0.8);
}
.create-button:hover {
background: rgba(40, 167, 69, 1);
}
.logout-button {
background: rgba(220, 53, 69, 0.8);
border-color: rgba(220, 53, 69, 0.8);
}
.logout-button:hover {
background: rgba(220, 53, 69, 1);
}
.find-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
.find-level-panel {
margin: 0 2rem;
padding: 1rem 1.5rem;
background: rgba(0, 0, 0, 0.25);
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.25);
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.find-level-form {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.find-level-input {
flex: 1;
min-width: 240px;
padding: 0.65rem 0.85rem;
border-radius: 8px;
border: 1px solid rgba(255, 255, 255, 0.4);
background: rgba(255, 255, 255, 0.9);
color: #333;
font-size: 0.95rem;
}
.find-level-input:disabled {
opacity: 0.7;
cursor: not-allowed;
}
.find-level-controls {
display: flex;
gap: 0.5rem;
}
.find-level-submit {
background: linear-gradient(135deg, #17a2b8 0%, #6610f2 100%);
color: white;
border: none;
padding: 0.6rem 1.1rem;
border-radius: 6px;
cursor: pointer;
font-size: 0.95rem;
font-weight: 500;
transition: transform 0.2s, box-shadow 0.2s;
}
.find-level-submit:hover {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 16, 242, 0.35);
}
.find-level-submit:disabled {
opacity: 0.65;
pointer-events: none;
}
.find-level-cancel {
padding: 0.6rem 0.95rem;
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
color: white;
border-radius: 6px;
cursor: pointer;
font-size: 0.9rem;
transition: all 0.3s ease;
}
.find-level-cancel:hover {
background: rgba(255, 255, 255, 0.4);
border-color: rgba(255, 255, 255, 0.6);
}
.find-level-cancel:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.find-level-error {
margin: 0;
color: #ffdddf;
font-size: 0.9rem;
}
/* Levels Content */
.levels-content {
flex: 1;
padding: 2rem;
}
.no-levels {
text-align: center;
padding: 4rem 2rem;
}
.no-levels h2 {
margin: 0 0 1rem 0;
font-size: 1.5rem;
}
.no-levels p {
margin: 0;
opacity: 0.8;
}
/* Levels Grid */
.levels-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 1.5rem;
max-width: 1200px;
margin: 0 auto;
}
.level-card {
background: rgba(255, 255, 255, 0.95);
color: #333;
border-radius: 10px;
padding: 1.5rem;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
transition: transform 0.3s, box-shadow 0.3s;
}
.level-card:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
.level-card-header {
display: flex;
justify-content: space-between;
align-items: start;
margin-bottom: 1rem;
gap: 0.75rem;
}
.level-name {
margin: 0;
color: #333;
line-height: 1.2;
flex: 1;
font-size: 1.2rem;
font-weight: 600;
overflow-wrap: anywhere;
word-break: break-word;
}
.level-name--regular {
font-size: 1.2rem;
}
.level-name--medium {
font-size: 1.08rem;
}
.level-name--small {
font-size: 0.98rem;
}
.level-name--xsmall {
font-size: 0.9rem;
}
.level-id {
background: #667eea;
color: white;
padding: 0.25rem 0.5rem;
border-radius: 15px;
font-size: 0.8rem;
font-weight: bold;
}
.level-card-content {
margin-bottom: 1.5rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.level-description {
margin: 0;
font-size: 0.98rem;
color: #4a4a4a;
background: linear-gradient(135deg, rgba(102, 126, 234, 0.15) 0%, rgba(118, 75, 162, 0.15) 100%);
border-radius: 8px;
padding: 0.75rem 1rem;
border-left: 4px solid #667eea;
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.4);
line-height: 1.5;
overflow-wrap: anywhere;
}
.level-visibility {
margin: 0;
font-size: 0.9rem;
color: #555;
font-weight: 500;
background: rgba(102, 126, 234, 0.15);
padding: 0.45rem 0.85rem;
border-radius: 999px;
display: inline-flex;
align-items: center;
gap: 0.35rem;
align-self: flex-start;
}
.level-stats {
font-size: 0.9rem;
color: #666;
background: #f8f9fa;
padding: 0.5rem;
border-radius: 5px;
}
.level-card-actions {
display: flex;
justify-content: center;
}
.play-button {
background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
color: white;
border: none;
padding: 0.75rem 1.5rem;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
transition: transform 0.2s, box-shadow 0.2s;
width: 100%;
max-width: 200px;
}
.play-button:hover {
transform: translateY(-1px);
box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}
.load-more-container {
display: flex;
justify-content: center;
margin-top: 2rem;
}
.load-more-button {
padding: 0.75rem 2.5rem;
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
color: white;
border-radius: 6px;
cursor: pointer;
font-size: 1rem;
font-weight: 500;
transition: all 0.3s ease;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.load-more-button:hover {
background: rgba(255, 255, 255, 0.35);
border-color: rgba(255, 255, 255, 0.6);
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
.load-more-button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
.load-more-error {
margin-top: 1.5rem;
text-align: center;
color: #ffdde0;
font-size: 0.95rem;
}
/* Levels Footer */
.levels-footer {
background: rgba(0, 0, 0, 0.2);
padding: 1rem 2rem;
text-align: center;
border-top: 1px solid rgba(255, 255, 255, 0.2);
color: white;
}
.levels-footer p {
margin: 0 0 1rem 0;
font-size: 1.1rem;
color: white;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.game-info {
display: flex;
justify-content: center;
gap: 2rem;
flex-wrap: wrap;
}
.game-info div {
background: rgba(255, 255, 255, 0.2);
padding: 0.5rem 1rem;
border-radius: 5px;
font-size: 0.9rem;
color: white;
font-weight: 500;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
border: 1px solid rgba(255, 255, 255, 0.1);
}
/* Loading and Error States */
.levels-loading,
.levels-error {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
text-align: center;
padding: 2rem;
}
.loading-spinner {
width: 40px;
height: 40px;
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid white;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 1rem;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.levels-error h2 {
margin: 0 0 1rem 0;
}
.levels-error p {
margin: 0 0 1.5rem 0;
}
.levels-error .retry-button {
margin-right: 1rem;
}
/* Responsive Design */
@media (max-width: 768px) {
.levels-header {
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
.header-actions {
flex-direction: row;
gap: 0.5rem;
}
.find-level-panel {
margin: 0 1rem;
}
.find-level-form {
flex-direction: column;
align-items: stretch;
}
.find-level-controls {
width: 100%;
justify-content: flex-end;
}
.levels-grid {
grid-template-columns: 1fr;
gap: 1rem;
}
.level-card {
padding: 1rem;
}
.game-info {
flex-direction: column;
gap: 0.5rem;
}
.levels-content {
padding: 1rem;
}
}

View File

@@ -0,0 +1,98 @@
import React, { useState, useEffect, useRef } from 'react';
import { GameMessage, Tiles, Direction } from '../types';
interface UseWebSocketGameReturn {
connected: boolean;
levelComplete: boolean;
prize: string;
sendMove: (direction: Direction) => void;
}
export const useWebSocketGame = (
wsUrl: string | null,
tiles: Tiles | null,
setTiles: React.Dispatch<React.SetStateAction<Tiles | null>>
): UseWebSocketGameReturn => {
const [connected, setConnected] = useState(false);
const [levelComplete, setLevelComplete] = useState(false);
const [prize, setPrize] = useState('');
const wsRef = useRef<WebSocket | null>(null);
useEffect(() => {
if (!wsUrl) {
return;
}
const ws = new WebSocket(wsUrl);
wsRef.current = ws;
ws.onopen = () => {
setConnected(true);
};
ws.onmessage = (event) => {
try {
const message: GameMessage = JSON.parse(event.data);
handleMessage(message);
} catch (error) {
console.error('Failed to parse WebSocket message:', error);
}
};
ws.onclose = (event) => {
setConnected(false);
console.log('WebSocket disconnected:', event.code, event.reason);
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
setConnected(false);
};
return () => {
ws.close(1000, 'Component cleanup');
setConnected(false);
setLevelComplete(false);
setPrize('');
};
}, [wsUrl]);
const handleMessage = (message: GameMessage) => {
switch (message.type) {
case 'update':
const { idx, new_tile } = message.option;
setTiles(prevTiles => {
if (!prevTiles || idx < 0 || idx >= prevTiles.tiles.length) {
console.error('Invalid tile update:', { idx, tilesLength: prevTiles?.tiles.length });
return prevTiles || null;
}
const newTiles = [...prevTiles.tiles];
newTiles[idx] = new_tile;
return { size: prevTiles.size, tiles: newTiles };
});
break;
case 'level_complete':
setLevelComplete(true);
setPrize(message.option.prize);
break;
case 'error':
console.error('Game error:', message.option);
break;
default:
console.error('Unknown message type:', message.type);
}
};
const sendMove = (direction: Direction) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify({ type: 'move', option: { direction } }));
}
};
return {
connected,
levelComplete,
prize,
sendMove
};
};

View File

@@ -0,0 +1,32 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
* {
box-sizing: border-box;
}
html,
body {
min-height: 100%;
}
body {
min-height: 100vh;
}
#root {
min-height: 100%;
display: flex;
flex-direction: column;
}

View File

@@ -0,0 +1,13 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

View File

@@ -0,0 +1,157 @@
/* Common button styles to avoid repetition */
.btn-base {
padding: 0.5rem 1rem;
border-radius: 5px;
cursor: pointer;
font-size: 0.9rem;
transition: all 0.3s ease;
border: none;
font-weight: 500;
}
.btn-glass {
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.4);
color: white;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}
.btn-glass:hover {
background: rgba(255, 255, 255, 0.4);
border-color: rgba(255, 255, 255, 0.6);
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover:not(:disabled) {
opacity: 0.9;
}
.btn-success {
background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
color: white;
}
.btn-success:hover {
transform: translateY(-1px);
box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
}
.btn-danger {
background: rgba(220, 53, 69, 0.8);
border: 1px solid rgba(220, 53, 69, 0.8);
color: white;
}
.btn-danger:hover {
background: rgba(220, 53, 69, 1);
}
.btn-link {
background: none;
border: none;
color: #667eea;
cursor: pointer;
text-decoration: underline;
font-size: inherit;
}
.btn-link:hover {
color: #764ba2;
}
/* Common loading spinner */
.spinner,
.loading-spinner {
border: 4px solid rgba(255, 255, 255, 0.3);
border-top: 4px solid white;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Common form styles */
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
color: #555;
font-weight: 500;
}
.form-group input,
.form-group textarea {
width: 100%;
padding: 0.75rem;
border: 2px solid #ddd;
border-radius: 5px;
font-size: 1rem;
transition: border-color 0.3s;
box-sizing: border-box;
}
.form-group input:focus,
.form-group textarea:focus {
outline: none;
border-color: #667eea;
}
.form-group input:disabled,
.form-group textarea:disabled {
background-color: #f5f5f5;
cursor: not-allowed;
}
/* Common message styles */
.error-message {
background-color: #fee;
color: #b91c1c;
padding: 0.75rem;
border-radius: 8px;
margin-bottom: 1rem;
border: 2px solid #fca5a5;
font-weight: 500;
box-shadow: 0 1px 3px rgba(185, 28, 28, 0.1);
}
.info-message {
background-color: #eff6ff;
color: #1e40af;
padding: 0.75rem;
border-radius: 8px;
margin-bottom: 1rem;
border: 2px solid #93c5fd;
font-weight: 500;
box-shadow: 0 1px 3px rgba(30, 64, 175, 0.1);
}
/* Common gradient background */
.gradient-bg {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
/* Common card styles */
.card {
background: rgba(255, 255, 255, 0.95);
border-radius: 10px;
padding: 1.5rem;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
transition: transform 0.3s, box-shadow 0.3s;
}
.card:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}

View File

@@ -0,0 +1,83 @@
export interface Point {
x: number;
y: number;
}
export type Direction = 'up' | 'down' | 'left' | 'right';
export interface Tile {
kind: string;
pos: Point;
data?: any;
}
export type LevelVisibility = 'public' | 'private';
export interface Tiles {
size: number;
tiles: Tile[];
}
export interface MoveMessage {
type: 'move';
option: {
direction: Direction;
};
}
export interface UpdateMessage {
type: 'update';
option: {
idx: number;
new_tile: Tile;
};
}
export interface LevelCompleteMessage {
type: 'level_complete';
option: any;
}
export interface ErrorMessage {
type: 'error';
option: {
message: string;
};
}
export type GameMessage = MoveMessage | UpdateMessage | LevelCompleteMessage | ErrorMessage;
// API types
export interface User {
id: number;
username: string;
}
export interface LevelSummary {
id: number;
name: string;
description?: string;
visibility: LevelVisibility;
}
export interface Level extends LevelSummary {
data: Tiles;
prize: string;
}
export interface LevelCreateRequest {
name: string;
description?: string;
prize: string;
visibility: LevelVisibility;
data: Tiles;
}
export interface LoginRequest {
username: string;
password: string;
}
export interface RegisterRequest {
username: string;
password: string;
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"target": "es2015",
"lib": [
"dom",
"dom.iterable",
"es6"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}

View File

@@ -0,0 +1,41 @@
events {
worker_connections 1024;
}
http {
server {
listen 8080 default_server;
location /api/ {
rewrite ^/api/(.*) /$1 break;
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 300s;
proxy_connect_timeout 75s;
proxy_intercept_errors on;
}
location / {
proxy_pass http://frontend:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_buffering off;
proxy_read_timeout 86400;
}
}
}