Prism-Step-SRV / src-server-go /api_dynamic.go
TQHYG's picture
Prism Step offline workspace snapshot (part 4)
13ca229 verified
Raw History Blame Contribute Delete
16.5 kB
package main
// Dynamic API handlers.
//
// These run BEFORE the api-stub lookup and take over the endpoints whose answer is
// derived from player state or masterdata. Everything else still falls through to
// the canned JSON, which keeps iteration cheap while the state machine grows.
//
// Rule of thumb: if the client can observe a change (jewels, stamina, exp, claimed
// days), the answer must be computed — replaying a captured body would be wrong.
import (
"encoding/json"
"fmt"
"math/rand"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
// gameNow is the clock used for every masterdata date-window decision.
// It is pinned by config.game_now so the server and the (possibly frozen) device
// agree on what "today" is; see Config.GameNow.
var gameNow = time.Now
// SetGameNow pins the server clock. An empty or unparsable value keeps host time.
func SetGameNow(s string) (time.Time, bool) {
const layout = "2006-01-02 15:04:05"
t, err := time.ParseInLocation(layout, s, time.Local)
if err != nil {
return time.Time{}, false
}
gameNow = func() time.Time { return t }
return t, true
}
// templates holds captured payloads used purely as shape skeletons
// (collections we do not simulate yet, e.g. story / live_stage).
type templates struct {
userModel map[string]any
finish map[string]any
gachaPlay map[string]any
shopBuy map[string]any
accountInf map[string]any
}
func (a *ApiStub) loadTemplates() *templates {
load := func(name string) map[string]any {
raw, err := os.ReadFile(filepath.Join(a.dir, name))
if err != nil {
return nil
}
var obj map[string]any
if json.Unmarshal(raw, &obj) != nil {
return nil
}
data, _ := obj["data"].(map[string]any)
return data
}
return &templates{
userModel: load("post_account_login2nd.json"),
finish: load("post_livestage_finishpractice.json"),
gachaPlay: load("post_gacha_play.json"),
shopBuy: load("post_shop_buy.json"),
accountInf: load("post_account_info.json"),
}
}
// respond writes a full success envelope.
func (a *ApiStub) respond(w http.ResponseWriter, path string, data any) {
out := map[string]any{
"code": 200,
"message": "",
"data": data,
"token": localToken,
"day_token": localDayToken,
}
b, _ := json.Marshal(out)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Content-Length", itoa(len(b)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(b)
a.logger.Infof("api: %s %s -> 200 dynamic (%d bytes)", "POST", path, len(b))
a.logger.Infof(" resp: %s", truncate(string(b), 300))
}
const (
localToken = "prismstep-local-token-0000000000000000000000000001"
localDayToken = "prismstep-local-daytoken-0000000000000002"
)
// handleDynamic returns true when it produced the response.
func (a *ApiStub) handleDynamic(w http.ResponseWriter, r *http.Request, body []byte) bool {
if a.players == nil || a.md == nil {
return false
}
path := strings.TrimSuffix(r.URL.Path, "/")
form, _ := url.ParseQuery(string(body))
usr := a.users.Player()
if v := r.Header.Get("UUID"); v != "" {
a.users.BindUUID(usr, v)
}
if v := form.Get("uuid"); v != "" {
a.users.BindUUID(usr, v)
}
st := a.players.Get(usr)
now := gameNow()
switch path {
case "/loginbonus/get":
entries := a.claimLoginBonuses(usr, st, now)
a.respond(w, path, map[string]any{
"achievement": []any{},
"loginbonus": entries,
})
return true
case "/account/login1st", "/account/login2nd", "/account/login3rd", "/account/login":
a.players.DayRollover(st, now)
// Settle the login bonus BEFORE rendering the UserModel. The client asks for it
// right after login and expects the jewels to already be in its player object;
// granting later would leave the UI showing the pre-bonus balance.
a.claimLoginBonuses(usr, st, now)
base := map[string]any{}
for k, v := range a.tpl().userModel {
base[k] = v
}
if usr.Name != "" {
base["name"] = usr.Name
}
base["tutorial"] = a.users.EffectiveTutorial(usr)
data := a.players.Render(st, base)
a.users.SetToken(usr, localToken)
a.players.Save(usr)
a.respond(w, path, data)
return true
case "/account/info":
data := map[string]any{}
for k, v := range a.tpl().accountInf {
data[k] = v
}
data["present_num"] = st.CountPresentBox
data["achieve_num"] = st.CountAchievement
a.respond(w, path, data)
return true
case "/gacha/list":
// Generated from OUR masterdata table. The captured private-server list uses
// v300 ids that do not exist here, and the client silently renders nothing
// when an id has no masterdata row.
a.respond(w, path, a.gachaList(st, now))
return true
case "/livestage/playgame", "/livestage/retrygame", "/event/playgame", "/maker/playgame":
// ResponseLivestagePlaygame (dump.cs:64128) is
// bool status; int power; int stamina; string stamina_updated_at;
// `status` is a BOOL. Sending 0 makes the client treat the call as failed,
// abort the live scene and re-run the whole boot — which looks like a
// "データ取得に失敗" then a kick back to the title screen.
cost := 1
if st.Stamina < cost {
a.logger.Infof("state: user %d playgame refused, stamina %d < %d", usr.ID, st.Stamina, cost)
a.respond(w, path, map[string]any{
"status": false, "power": a.teamPower(),
"stamina": st.Stamina, "stamina_updated_at": st.StaminaUpdatedAt,
})
return true
}
st.Stamina -= cost
st.StaminaUpdatedAt = now.Format("2006-01-02 15:04:05")
a.players.Save(usr)
a.logger.Infof("state: user %d stamina -%d -> %d", usr.ID, cost, st.Stamina)
a.respond(w, path, map[string]any{
"status": true, "power": a.teamPower(),
"stamina": st.Stamina, "stamina_updated_at": st.StaminaUpdatedAt,
})
return true
case "/livestage/gameover", "/event/gameover", "/maker/gameover":
// ResponseLivestageGameover declares no fields of its own (BaseResponse only),
// so an empty object is the correct payload.
st.StaminaUpdatedAt = now.Format("2006-01-02 15:04:05")
a.players.Save(usr)
a.respond(w, path, map[string]any{})
return true
case "/livestage/finishgame", "/livestage/finishpractice", "/event/finishgame", "/event/battle_finish", "/maker/finishgame":
score, _ := strconv.Atoi(form.Get("total_score"))
if score < 0 {
score = 0
}
// Experience/coin scale with score. Coefficients are deliberately modest so a
// normal stage does not jump dozens of levels.
expGain := score / 100
coinGain := score / 10
if expGain > 0 || coinGain > 0 {
a.players.AddExp(st, expGain)
st.Money += coinGain
}
// Our v279 ResponseLivestageFinishgame has ONLY these four members
// (dump.cs:64052): rewards, eventRewards, eventPoint, characterCollectionBefore.
// The captured private-server payload is the v300 shape (player/characters/...),
// so it is kept as extra keys but the v279 members are what actually matter.
data := map[string]any{}
for k, v := range a.tpl().finish {
data[k] = v
}
data["rewards"] = []any{}
data["eventRewards"] = []any{}
data["eventPoint"] = map[string]any{}
data["characterCollectionBefore"] = map[string]any{"characters": []any{}}
data["player"] = a.playerSnapshot(st)
data["event_bonus_item_num"] = 0
a.players.Save(usr)
a.logger.Infof("state: user %d finish score=%d exp+%d money+%d -> lv%d", usr.ID, score, expGain, coinGain, st.Lv)
a.respond(w, path, data)
return true
case "/gacha/play", "/gacha/execute":
gachaID, _ := strconv.Atoi(form.Get("id"))
count, _ := strconv.Atoi(form.Get("count"))
if count == 0 {
count, _ = strconv.Atoi(form.Get("gacha_count"))
}
if count == 0 {
count = 1
}
data, ok := a.doGacha(w, usr, st, gachaID, count)
if !ok {
return true
}
a.players.Save(usr)
a.respond(w, path, data)
return true
case "/shop/buy":
data, ok := a.doShopBuy(w, usr, st, form)
if !ok {
return true
}
a.players.Save(usr)
a.respond(w, path, data)
return true
}
return false
}
// teamPower returns the team's displayed power. Team composition is not modelled
// yet, so this sums masterdata card stats for the cards in the base template.
// A card has three stat lines (power1/2/3), so the card's power is their max sum.
func (a *ApiStub) teamPower() int {
byID := map[int]int{}
for _, r := range a.md.Tables["card"] {
byID[r.Int("id")] = r.Int("power1_max") + r.Int("power2_max") + r.Int("power3_max")
}
power := 0
cards, _ := a.tpl().userModel["player_cards"].([]any)
for _, c := range cards {
m, _ := c.(map[string]any)
if m == nil {
continue
}
if cid, ok := m["card_id"].(float64); ok {
power += byID[int(cid)]
}
}
return power
}
func (a *ApiStub) tpl() *templates {
a.tplOnce.Do(func() { a.templates = a.loadTemplates() })
if a.templates == nil {
a.templates = &templates{}
}
return a.templates
}
func (a *ApiStub) playerSnapshot(st *PlayerState) map[string]any {
return map[string]any{
"exp": st.Exp,
"lv": st.Lv,
"money": st.Money,
"stamina": st.Stamina,
"stamina_max": st.StaminaMax,
"stamina_updated_at": st.StaminaUpdatedAt,
"point_free": st.PointFree,
"point_purchased": st.PointPurchased,
"chara_box_length": a.md.Config("max_card", 150),
"acce_box_length": a.md.Config("max_acce", 250),
"characters": []any{},
"count_achievement": st.CountAchievement,
"count_present_box": st.CountPresentBox,
}
}
// claimLoginBonuses claims any day not yet claimed today, grants its rewards into
// the player state and returns the entries the client renders as stamps.
//
// It is called from login (so the UserModel already carries the new balance) and
// from /loginbonus/get (so a mid-session open still works); the LastClaimDay guard
// makes it idempotent per game-day.
func (a *ApiStub) claimLoginBonuses(usr *User, st *PlayerState, now time.Time) []map[string]any {
day := a.md.GameDay(now)
entries := []map[string]any{}
for _, b := range a.md.ActiveLoginBonuses(now) {
key := fmt.Sprintf("%d:%d", b.Kind, b.ID)
bs := st.Bonuses[key]
if bs == nil {
bs = &BonusState{}
st.Bonuses[key] = bs
}
if bs.LastClaimDay != day && len(bs.History) < len(b.Rows) {
next := len(bs.History) + 1
var row masterRow
for _, r := range b.Rows {
if r.Int("days") == next {
row = r
break
}
}
if row != nil {
rw := Reward{Kind: row.Int("item_kind"), ID: row.Int("item_id"), Num: row.Int("num")}
what := a.players.Grant(st, rw)
bs.History = append(bs.History, next)
bs.LastClaimDay = day
a.logger.Infof("loginbonus: user %d kind=%d id=%d day=%d grant %s (%s)",
usr.ID, b.Kind, b.ID, next, what, a.md.ItemKindName(rw.Kind))
}
}
// One stamp per claimed day; the value itself is just "claimed".
hist := make([]int, len(bs.History))
for i := range hist {
hist[i] = 1
}
entries = append(entries, map[string]any{
"loginbonus_kind": b.Kind,
"loginbonus_id": b.ID,
"history": hist,
})
}
return entries
}
// gachaList builds the list from masterdata so every id is one the client knows.
func (a *ApiStub) gachaList(st *PlayerState, now time.Time) []map[string]any {
type row struct {
order int
item map[string]any
}
rows := []row{}
for _, g := range a.md.Tables["gacha"] {
if g.Int("is_hide") != 0 {
continue
}
if !a.md.InWindow(g, now) {
continue
}
id := g.Int("id")
free := g.Int("day_free_count")
if free > 0 {
free -= st.FreeUsed[itoa(id)]
if free < 0 {
free = 0
}
}
rows = append(rows, row{order: g.Int("order"), item: map[string]any{
"gacha_id": id,
"day_free_count": free,
"quantity_limit_count": g.Int("quantity_limit_count"),
}})
}
sort.SliceStable(rows, func(i, j int) bool { return rows[i].order < rows[j].order })
out := make([]map[string]any, 0, len(rows))
for _, r := range rows {
out = append(out, r.item)
}
return out
}
// doGacha charges the cost from masterdata gachaDetail and returns a drawn card.
// gachaFreeLeft returns the remaining free draws for today.
func (a *ApiStub) gachaFreeLeft(gachaID int, st *PlayerState) int {
for _, g := range a.md.Tables["gacha"] {
if g.Int("id") != gachaID {
continue
}
left := g.Int("day_free_count") - st.FreeUsed[itoa(gachaID)]
if left < 0 {
left = 0
}
return left
}
return 0
}
func (a *ApiStub) doGacha(w http.ResponseWriter, usr *User, st *PlayerState, gachaID, count int) (map[string]any, bool) {
// Free draws come first, then the masterdata price.
if free := a.gachaFreeLeft(gachaID, st); free >= count {
st.FreeUsed[itoa(gachaID)] += count
a.logger.Infof("state: user %d gacha %d x%d free (%d left)", usr.ID, gachaID, count, free-count)
} else {
cost, costItem := a.gachaCost(gachaID, count)
if costItem == 2 && cost > 0 { // item_id 2 == jewels
if st.PointFree+st.PointPurchased < cost {
a.respondErr(w, "/gacha/play", 700, "ポイントが足りません")
return nil, false
}
// Spend free jewels first, like the retail server.
use := cost
if st.PointFree >= use {
st.PointFree -= use
} else {
use -= st.PointFree
st.PointFree = 0
st.PointPurchased -= use
}
a.logger.Infof("state: user %d gacha %d x%d cost %d jewels -> free=%d paid=%d",
usr.ID, gachaID, count, cost, st.PointFree, st.PointPurchased)
}
}
data := map[string]any{}
for k, v := range a.tpl().gachaPlay {
data[k] = v
}
card := a.drawCard(gachaID)
if card != 0 {
data["player_card"] = map[string]any{
"id": 0,
"card_id": card,
"lv": 1,
"exp": 0,
"acce_skill_pos": 0,
"favorite": false,
"created_at": time.Now().Format("2006-01-02 15:04:05"),
"break_limit_count": 0,
}
}
data["gacha_id"] = gachaID
data["point_free"] = st.PointFree
data["point_purchased"] = st.PointPurchased
return data, true
}
// gachaCost finds the price row for (gacha_id, count) in masterdata gachaDetail.
func (a *ApiStub) gachaCost(gachaID, count int) (num, itemID int) {
for _, r := range a.md.Tables["gachaDetail"] {
if r.Int("gacha_id") != gachaID || r.Int("gacha_count") != count {
continue
}
return r.Int("item_num"), r.Int("item_id_1")
}
// Fall back to the documented retail prices (notes/12).
if count >= 10 {
return 2500, 2
}
return 250, 2
}
// drawCard picks a card id from the gacha's pool.
func (a *ApiStub) drawCard(gachaID int) int {
block := 0
for _, r := range a.md.Tables["gacha"] {
if r.Int("id") == gachaID {
block = r.Int("group_id")
break
}
}
if block == 0 {
return 0
}
pool := []int{}
for _, r := range a.md.Tables["gachaBlockDetail"] {
if r.Int("gacha_block_id") == block {
pool = append(pool, r.Int("card_id"))
}
}
if len(pool) == 0 {
return 0
}
return pool[rand.Intn(len(pool))]
}
// doShopBuy charges a pack and records the granted items.
func (a *ApiStub) doShopBuy(w http.ResponseWriter, usr *User, st *PlayerState, form url.Values) (map[string]any, bool) {
packID, _ := strconv.Atoi(form.Get("pack_id"))
var pack masterRow
for _, r := range a.md.Tables["shopItemPack"] {
if r.Int("id") == packID {
pack = r
break
}
}
data := map[string]any{}
for k, v := range a.tpl().shopBuy {
data[k] = v
}
if pack == nil {
a.logger.Infof("shop: unknown pack %d, echoing template", packID)
return data, true
}
price := pack.Int("point")
if price > 0 {
if st.PointFree+st.PointPurchased < price {
a.respondErr(w, "/shop/buy", 700, "ポイントが足りません")
return nil, false
}
use := price
if st.PointFree >= use {
st.PointFree -= use
} else {
use -= st.PointFree
st.PointFree = 0
st.PointPurchased -= use
}
}
a.logger.Infof("state: user %d shop pack %d price %d -> free=%d paid=%d", usr.ID, packID, price, st.PointFree, st.PointPurchased)
data["point_free"] = st.PointFree
data["point_purchased"] = st.PointPurchased
return data, true
}
func (a *ApiStub) respondErr(w http.ResponseWriter, path string, code int, msg string) {
out := map[string]any{"code": code, "message": msg, "data": nil, "token": localToken, "day_token": localDayToken}
b, _ := json.Marshal(out)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(b)
a.logger.Infof("api: %s %s -> code %d (%s)", "POST", path, code, msg)
}