package store import ( "aeternalis/server/internal/game" p "aeternalis/server/internal/protocol" "context" "database/sql" "encoding/json" "errors" "fmt" "slices" "strings" ) var ErrHousing = errors.New("housing action rejected") func houseError(s string) error { return fmt.Errorf("%w: %s", ErrHousing, s) } type HouseRequest struct { RequestID string `json:"requestId"` Op string `json:"op"` HouseID string `json:"houseId"` Target string `json:"target"` Item string `json:"item"` Quantity int64 `json:"quantity"` X float64 `json:"x"` Z float64 `json:"z"` Role string `json:"role"` Name string `json:"name"` Permissions map[string]bool `json:"permissions"` Revision int64 `json:"revision"` } type houseMutation struct { Account string Request HouseRequest } type houseRecord struct { View p.House CreatorAccount, CreatorCharacter, DeathWorld, DeathID string } func (d *DB) readHouse(ctx context.Context, tx *sql.Tx, id string, lock bool) (*houseRecord, error) { if lock { if _, e := tx.ExecContext(ctx, d.q(`UPDATE houses SET state=state WHERE id=?`), id); e != nil { return nil, e } } var raw string h := &houseRecord{} e := tx.QueryRowContext(ctx, d.q(`SELECT creator_account,creator_character,death_world,death_id,document FROM houses WHERE id=?`), id).Scan(&h.CreatorAccount, &h.CreatorCharacter, &h.DeathWorld, &h.DeathID, &raw) if errors.Is(e, sql.ErrNoRows) { return nil, houseError("house not found") } if e != nil { return nil, e } if e = json.Unmarshal([]byte(raw), &h.View); e != nil { return nil, e } return h, nil } func (d *DB) writeHouse(ctx context.Context, tx *sql.Tx, h *houseRecord) error { seen := map[string]bool{} if e := game.ValidateHouseInventory(h.View.Floor, seen); e != nil { return houseError(e.Error()) } for id, f := range h.View.Furniture { if id != f.Item.ID || seen[id] || f.Item.Furniture == nil { return houseError("invalid furniture identity") } seen[id] = true if e := game.ValidateHouseInventory(f.Contents, seen); e != nil { return houseError(e.Error()) } } h.View.Revision++ raw, e := json.Marshal(h.View) if e != nil { return e } _, e = tx.ExecContext(ctx, d.q(`UPDATE houses SET state=?,document=? WHERE id=?`), h.View.State, string(raw), h.View.ID) return e } func (d *DB) houseRole(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character) (string, error) { for _, i := range c.View.Items { if i.HouseID == nil || *i.HouseID != h.View.ID { continue } var n int if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil { return "", e } if n == 1 { return "owner", nil } } return h.View.Roles[c.View.Entity.ID], nil } func housePermissions(h *houseRecord, c *game.Character, role string) map[string]bool { out := map[string]bool{} for _, key := range game.HousePermissions { out[key] = role == "owner" || role == "co-owner" || h.View.Permissions[key] if role != "owner" && role != "co-owner" { if v, ok := h.View.Overrides[c.View.Entity.ID][key]; ok { out[key] = v } } } return out } func (d *DB) keyCount(ctx context.Context, tx *sql.Tx, id string) (int64, error) { var n int64 e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE house_id=? AND state='active'`), id).Scan(&n) return n, e } func (d *DB) issueKey(ctx context.Context, tx *sql.Tx, h *houseRecord, c *game.Character, max int) error { if len(c.View.Items) >= max { return houseError("inventory full") } count, e := d.keyCount(ctx, tx, h.View.ID) if e != nil { return e } if count >= 128 { return houseError("house key limit reached") } id := game.ID() _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_keys(id,house_id,state) VALUES(?,?,'active')`), id, h.View.ID) if e != nil { return e } houseID := h.View.ID c.View.Items = append(c.View.Items, p.ItemInstance{ID: id, DefinitionID: "house_key", Name: h.View.Name + " key", Description: "A bearer key granting owner rights. Destroying it takes three seconds.", Slot: "bag", Weight: .1, HouseID: &houseID, Requirements: p.ItemRequirements{Level: 1, Stats: map[string]float64{}, Titles: []string{}}, Modifiers: []p.StatModifier{}}) return nil } func (d *DB) recoveryEnded(ctx context.Context, tx *sql.Tx, h *houseRecord) (bool, error) { if h.DeathWorld == "" { return false, nil } var raw string e := tx.QueryRowContext(ctx, d.q(`SELECT snapshot FROM worlds WHERE id=?`), h.DeathWorld).Scan(&raw) if errors.Is(e, sql.ErrNoRows) { return false, nil } if e != nil { return false, e } var w struct{ Phase string } if e = json.Unmarshal([]byte(raw), &w); e != nil { return false, e } return w.Phase == "lost", nil } func purgeHouse(h *houseRecord) { h.View.State = "purged" h.View.Floor = game.EmptyHouseInventory() h.View.Furniture = map[string]p.HouseFurniture{} h.View.Roles = map[string]string{} h.View.Overrides = map[string]map[string]bool{} } func (l *Lease) HouseAction(ctx context.Context, w *game.World, account string, r HouseRequest) error { if !catalogRequestID.MatchString(r.RequestID) || len(r.HouseID) > 64 || len(r.Item) > 100 || len(r.Target) > 100 || len(r.Name) > 80 || len(r.Permissions) > 6 { return houseError("invalid request") } if e := l.save(ctx, w, "", nil, "", nil, nil, &houseMutation{account, r}); e != nil { return e } if c := w.ForAccount(account); c != nil && game.HouseID(c) != "" { c.MoveX = 0 c.MoveZ = 0 c.PendingCast = nil } return nil } func (d *DB) applyHouse(ctx context.Context, tx *sql.Tx, w *game.World, m *houseMutation) error { r := m.Request c := w.ForAccount(m.Account) if c == nil || !c.Online || c.Sheltered || c.View.RemainingSeconds <= 0 || w.Phase == "lost" { return houseError("active character required") } var current, world, state string if e := tx.QueryRowContext(ctx, d.q(`SELECT character_id,world_id,state FROM character_records WHERE account_id=? AND state IN ('alive','eligible','transit')`), m.Account).Scan(¤t, &world, &state); e != nil { return e } if current != c.View.Entity.ID || world != w.ID || state == "transit" { return houseError("character has moved") } raw, _ := json.Marshal(r) var previous string e := tx.QueryRowContext(ctx, d.q(`SELECT request FROM house_receipts WHERE account_id=? AND id=?`), m.Account, r.RequestID).Scan(&previous) if e == nil { if previous != string(raw) { return houseError("request already used") } return nil } if !errors.Is(e, sql.ErrNoRows) { return e } if e = d.mutateHouse(ctx, tx, w, c, r); e != nil { return e } w.RefreshStats(c) _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_receipts(account_id,id,request) VALUES(?,?,?)`), m.Account, r.RequestID, string(raw)) return e } func (d *DB) mutateHouse(ctx context.Context, tx *sql.Tx, w *game.World, c *game.Character, r HouseRequest) error { rules := w.Balance.Housing if r.Op == "cancel-key" { c.View.DestroyKey = nil return nil } if r.Op == "destroy-key" { if c.View.DestroyKey != nil { return houseError("already destroying a key") } for _, i := range c.View.Items { if i.ID == r.Item && i.HouseID != nil { h, e := d.readHouse(ctx, tx, *i.HouseID, true) if e != nil { return e } var n int if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), i.ID, h.View.ID).Scan(&n); e != nil { return e } if n != 1 { return houseError("key is invalid") } c.View.DestroyKey = &p.KeyDestruction{KeyID: i.ID, FinishesAt: w.NowSeconds() + rules.KeySeconds} return nil } } return houseError("carried key required") } if !w.IsHub() { return houseError("housing is accessed from a hub") } if r.Op == "leave" { game.LeaveHouse(c) return nil } if r.Op == "create" { if c.WorldsSurvived < 1 || game.HouseID(c) != "" { return houseError("survive a world and return to the hub before creating a house") } var count int if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM houses WHERE creator_account=? AND state<>'purged'`), c.Account).Scan(&count); e != nil { return e } if count > 0 { return houseError("you already created a recoverable house") } name := strings.TrimSpace(r.Name) if name == "" { return houseError("house name required") } h := &houseRecord{CreatorAccount: c.Account, CreatorCharacter: c.View.Entity.ID, View: p.House{ID: game.ID(), Name: name, State: "active", Size: rules.RoomSize, Permissions: map[string]bool{}, Overrides: map[string]map[string]bool{}, Roles: map[string]string{}, Furniture: map[string]p.HouseFurniture{}, Floor: game.EmptyHouseInventory()}} raw, _ := json.Marshal(h.View) if _, e := tx.ExecContext(ctx, d.q(`INSERT INTO houses(id,creator_account,creator_character,death_world,death_id,state,document) VALUES(?,?,?,'','','active',?)`), h.View.ID, c.Account, c.View.Entity.ID, string(raw)); e != nil { return e } if e := d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil { return e } return d.writeHouse(ctx, tx, h) } h, e := d.readHouse(ctx, tx, r.HouseID, true) if e != nil { return e } ended, e := d.recoveryEnded(ctx, tx, h) if e != nil { return e } if r.Op == "recover" { if h.CreatorAccount != c.Account || c.WorldsSurvived < 1 || h.DeathID == "" || h.DeathWorld == "" || ended || h.View.State == "purged" { return houseError("creator recovery unavailable") } var known int if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM worlds WHERE id=?`), h.DeathWorld).Scan(&known); e != nil { return e } if known != 1 { return houseError("recovery world unavailable") } if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil { return e } h.View.State = "active" return d.writeHouse(ctx, tx, h) } if h.View.State != "active" { return houseError("house is unavailable") } role, e := d.houseRole(ctx, tx, h, c) if e != nil { return e } if role == "" { return houseError("a carried key or invitation is required") } if r.Op == "enter" { if !w.NearEntrance(c, w.HousingEntrancePosition()) { return houseError("stand next to the housing entrance in this hub") } if r.Item != "" { // Explicit key use must name a carried, active key for this exact house; // an invitation cannot make a wrong or destroyed key usable. carried := slices.ContainsFunc(c.View.Items, func(i p.ItemInstance) bool { return i.ID == r.Item && i.HouseID != nil && *i.HouseID == h.View.ID }) var active int if e := tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM house_keys WHERE id=? AND house_id=? AND state='active'`), r.Item, h.View.ID).Scan(&active); e != nil { return e } if !carried || active != 1 { return houseError("use a carried key for this house") } } if c.WorldsSurvived < 1 { return houseError("survive a world before entering housing") } if game.HouseID(c) != "" { return houseError("leave the current house first") } id := h.View.ID pos, ok := w.HouseSpawn(w.HouseScene(h.View)) if !ok { return houseError("no clear space to enter this house") } c.View.HouseID = &id c.View.HousePosition = &pos c.JumpVelocity = 0 c.View.DestroyKey = nil c.View.Casting = nil return nil } if game.HouseID(c) != h.View.ID { return houseError("enter this house first") } if r.Revision > 0 && r.Revision != h.View.Revision { return houseError("house changed; refresh before editing") } allowed := housePermissions(h, c, role) manager := role == "owner" || role == "co-owner" switch r.Op { case "issue-key": if role != "owner" { return houseError("only key holders issue keys") } if e = d.issueKey(ctx, tx, h, c, rules.MaxItems); e != nil { return e } case "invite": if !manager || (!slices.Contains([]string{"guest", "co-owner", "remove"}, r.Role)) || (role != "owner" && (r.Role == "co-owner" || h.View.Roles[r.Target] == "co-owner")) { return houseError("invitation role not allowed") } if r.Target == c.View.Entity.ID { return houseError("cannot change your own invitation") } if r.Role == "remove" { delete(h.View.Roles, r.Target) delete(h.View.Overrides, r.Target) if _, e = tx.ExecContext(ctx, d.q(`DELETE FROM house_invites WHERE house_id=? AND character_id=?`), h.View.ID, r.Target); e != nil { return e } } else { var n int if e = tx.QueryRowContext(ctx, d.q(`SELECT COUNT(*) FROM character_records WHERE character_id=? AND state IN ('alive','eligible')`), r.Target).Scan(&n); e != nil { return e } if n != 1 { return houseError("living guest not found") } if h.View.Roles[r.Target] == "" && len(h.View.Roles) >= rules.MaxGuests { return houseError("guest limit") } h.View.Roles[r.Target] = r.Role if _, e = tx.ExecContext(ctx, d.q(`INSERT INTO house_invites(house_id,character_id) VALUES(?,?) ON CONFLICT(house_id,character_id) DO NOTHING`), h.View.ID, r.Target); e != nil { return e } } case "permissions": if !manager { return houseError("only owners and co-owners manage guest permissions") } for key := range r.Permissions { if !slices.Contains(game.HousePermissions, key) { return houseError("unknown guest permission") } } if r.Target == "" { for k, v := range r.Permissions { h.View.Permissions[k] = v } } else { if h.View.Roles[r.Target] == "" { return houseError("invite this person first") } h.View.Overrides[r.Target] = r.Permissions } default: if e = houseItemAction(w, c, h, r, allowed); e != nil { return e } } return d.writeHouse(ctx, tx, h) }