85 lines
2.6 KiB
Go
85 lines
2.6 KiB
Go
package store
|
|
|
|
import (
|
|
"aeternalis/server/internal/game"
|
|
p "aeternalis/server/internal/protocol"
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
)
|
|
|
|
var ErrItemAction = errors.New("item action rejected")
|
|
|
|
// Namespaced IDs share the existing durable action receipt transaction without
|
|
// colliding with crafting attempts. Store full requests to reject changed retries.
|
|
func (l *Lease) ItemAction(ctx context.Context, live *game.World, account string, req p.ItemActionRequest) (p.ItemActionResult, error) {
|
|
fail := func(message string) (p.ItemActionResult, error) {
|
|
return p.ItemActionResult{}, fmt.Errorf("%w: %s", ErrItemAction, message)
|
|
}
|
|
if !game.ValidItemAction(req) {
|
|
return fail("invalid request")
|
|
}
|
|
id := "item:" + req.ID
|
|
request, _ := json.Marshal(req)
|
|
var previous, resultJSON string
|
|
err := l.DB.sql.QueryRowContext(ctx, l.DB.q(`SELECT request_json,result_json FROM craft_receipts WHERE account_id=? AND id=?`), account, id).Scan(&previous, &resultJSON)
|
|
if err == nil {
|
|
if previous != string(request) {
|
|
return fail("request ID already used for another action")
|
|
}
|
|
var result p.ItemActionResult
|
|
err = json.Unmarshal([]byte(resultJSON), &result)
|
|
return result, err
|
|
}
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
return p.ItemActionResult{}, err
|
|
}
|
|
active, err := l.DB.ActiveCharacter(ctx, account)
|
|
if err != nil {
|
|
return p.ItemActionResult{}, err
|
|
}
|
|
if active == nil || active.ID != req.CharacterID || active.WorldID != live.ID || active.State != "alive" {
|
|
return fail("character is not active in this world")
|
|
}
|
|
original := live.Characters[req.CharacterID]
|
|
if original == nil || original.Account != account {
|
|
return fail("character unavailable")
|
|
}
|
|
staged := stageTitleWorld(live)
|
|
for _, c := range staged.Characters {
|
|
raw, err := json.Marshal(c.View)
|
|
if err != nil {
|
|
return p.ItemActionResult{}, err
|
|
}
|
|
var view p.Character
|
|
if err = json.Unmarshal(raw, &view); err != nil {
|
|
return p.ItemActionResult{}, err
|
|
}
|
|
c.View = view
|
|
}
|
|
staged.Mobs = make(map[string]*game.Mob, len(live.Mobs))
|
|
for id, m := range live.Mobs {
|
|
copy := *m
|
|
staged.Mobs[id] = ©
|
|
}
|
|
result, err := staged.ItemAction(staged.Characters[req.CharacterID], req)
|
|
if err != nil {
|
|
return fail(err.Error())
|
|
}
|
|
raw, _ := json.Marshal(result)
|
|
receipt := &craftReceipt{id, account, req.CharacterID, string(request), string(raw)}
|
|
if err = l.save(ctx, staged, "", nil, "", receipt, nil, nil); err != nil {
|
|
return p.ItemActionResult{}, err
|
|
}
|
|
for id, c := range staged.Characters {
|
|
*live.Characters[id] = *c
|
|
}
|
|
live.Mobs = staged.Mobs
|
|
live.RandomCounter = staged.RandomCounter
|
|
live.PendingTitles = nil
|
|
live.Saved()
|
|
return result, nil
|
|
}
|