feat(all): add server gameplay systems, one-step launcher installation, clearer update logs and shared file utilities

Server:
- Add castle and total war battles, IB battles, roguelike runs with castle and roguelike rankings, cafeteria and dating, life content, spine interactions and recordings, popularity rankings, gacha history and selection draws, map exploration, quest previews and completion, passes, rhythm events, quick battles, achievement progress, resource items, prestige illustrations and community notices.
- Report structured request errors from the gateway, validate avatars, and extend settlement evidence and existing domain handlers.
- Let bd2-host.sh deploy from a source directory or a prebuilt image and update the deployment docs and Docker ignore list.

Launcher:
- Prepare a new installation directly from the launcher (download, BepInEx, catalog, patch, plugins) through a shared preparation package also used by bd2client prepare.
- Launching and preparing now wait for a running background update instead of failing with "Another update operation is in progress"; manual update checks wait as well, and launch downloads no longer use the 12-second resource-policy timeout.
- Log what each update check found, every downloaded file, the server requirement, the game resource decision and installed plugins; skip warnings caused by closing the launcher.

Shared:
- Move file hashing and atomic replacement into common/util and use it from the build, release, launcher and server code.
This commit is contained in:
Flechazo committed 2026-10-19 00:04:02 +08:00
1 parent cbb7e12483
commit 6da2d9b89c
265 files changed
+23870 -1143

No files matched your search

+2
View File
@@ -1,6 +1,8 @@
*
!go/
!go/**
go/.cache/
go/config.json
!versions.json
!CHANGELOG.md*
!UPDATE_FINGERPRINT.json
+8 -5
View File
@@ -84,21 +84,24 @@ BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系
### 在 Linux 服务器上用 Docker 部署
[`tools/server/bd2-host.sh`](tools/server/bd2-host.sh) 负责 Docker 主机上的全部工作:准备目录、生成认证主密钥、检出源码、安装更新交接单元,并从已发布的提交构建镜像、切换容器、等待就绪。需要 Docker(含 Compose 插件)、git、jq、curl、flock、nsenter 和 openssl,以 root 运行。一键安装并部署 `main` 的最新提交:
[`tools/server/bd2-host.sh`](tools/server/bd2-host.sh) 负责 Docker 主机上的目录与密钥初始化、更新交接单元安装、镜像构建、容器切换和就绪检查。手动部署直接使用指定目录的当前源码(包括未提交的改动),或指定的 Docker 镜像,与 Git 提交、推送无关。需要 Docker(含 Compose 插件)、jq、curl、flock、nsenter、realpath 和 openssl,以 root 运行。从源码目录安装并部署:
```bash
curl -fsSL https://raw.githubusercontent.com/Flechazo098/bd2/main/tools/server/bd2-host.sh -o bd2-host.sh && sudo sh bd2-host.sh setup
sudo sh tools/server/bd2-host.sh setup "$PWD"
```
脚本安装到 `/opt/bd2/bd2-host.sh`,数据在 `/opt/bd2/data`,Compose 文件首次从 [模板](tools/server/compose.yaml) 生成为 `/opt/bd2/compose.yaml`(默认只在本机 `8080` 端口提供服务,请放在 HTTPS 反向代理之后)。之后:
```bash
sudo /opt/bd2/bd2-host.sh deploy # 部署 main 的最新提交,或指定完整提交号
sudo /opt/bd2/bd2-host.sh deploy /path/to/bd2 # 构建该目录当前源码
sudo /opt/bd2/bd2-host.sh deploy --image bd2server:my-build
sudo /opt/bd2/bd2-host.sh status
sudo /opt/bd2/bd2-host.sh rollback # 换回上次切换前的镜像;存档不回滚
sudo /opt/bd2/bd2-host.sh rollback # 换回上次切换前的镜像;存档不会回滚
```
在管理台应用的服务端更新也由同一脚本完成交接。路径、源码地址和 Compose 文件可在 `/etc/bd2/host.conf` 中以 `BD2_DIR=`、`SOURCE_URL=`、`COMPOSE_FILE=`、`SERVICE=`、`READY_PORT=`、`SEED_CONFIG_DIR=` 修改。不用 Docker 时,可使用 [systemd 单元模板](tools/server/bd2server.service)。
省略源码路径时,`deploy` 使用 `/opt/bd2/source` 中已有的源码。指定镜像时,优先使用本机镜像,不存在则拉取,并以解析出的不可变镜像 ID 切换。首次安装若没有相邻的 Compose 模板和本地源码,脚本会用 Git 从 `SOURCE_URL` 获取初始源码。
在管理台应用的服务端更新也由同一脚本完成交接,继续使用经过验证的发布请求;发布提供固定摘要的镜像时无需 Git,按源码更新时才获取对应提交。路径、源码地址和 Compose 文件可在 `/etc/bd2/host.conf` 中以 `BD2_DIR=`、`SOURCE_URL=`、`COMPOSE_FILE=`、`SERVICE=`、`READY_PORT=`、`SEED_CONFIG_DIR=` 修改。不用 Docker 时,可使用 [systemd 单元模板](tools/server/bd2server.service)。
服务端日志默认输出 INFO 及以上级别,仅终端启用颜色:TRACE 灰、DEBUG 青、INFO 绿、WARN 黄、ERROR 红。可用 `serve --log-level debug --log-color auto` 调整。级别支持 `trace/debug/info/warn/error`,颜色支持 `auto/always/never`。`auto` 下文件和重定向保持纯文本,`NO_COLOR` 或 `TERM=dumb` 也会关闭颜色;如需在 Docker 日志流中显示颜色,可显式选择 `always`。
+7 -2
View File
@@ -63,9 +63,14 @@ func (t task) runClient2(args []string) error {
return fmt.Errorf("load second client's connection settings: %w", err)
}
}
if _, err := clientsetup.SaveSettings(instance.GameDirectory, settings, versions); err != nil {
if _, err := clientsetup.SaveSettings(instance.GameDirectory, settings); err != nil {
return fmt.Errorf("prepare second client's resources: %w", err)
}
if settings.CDNMode == clientconfig.CDNLocal {
if err := clientsetup.InstallLocalCatalog(instance.GameDirectory, settings.LocalResourceDirectory, versions.BundleVersion); err != nil {
return fmt.Errorf("prepare second client's catalog: %w", err)
}
}
return nil
}},
taskgraph.Task{Name: "instance:plugins", DependsOn: []string{"instance:prepare"}, Run: func(ctx context.Context) error {
@@ -78,7 +83,7 @@ func (t task) runClient2(args []string) error {
plugins := func(name string) string {
return filepath.Join(t.root, "plugins", name, "bin", "Release", "netstandard2.1", "BD2"+name+".dll")
}
_, err := clientsetup.InstallPlugins(instance.GameDirectory, settings, versions, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat"))
_, err := clientsetup.InstallPlugins(instance.GameDirectory, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat"))
return err
}},
taskgraph.Task{Name: "instance:launcher", DependsOn: []string{"instance:plugins"}, Run: func(context.Context) error {
+2 -1
View File
@@ -1,6 +1,7 @@
package main
import (
"bd2server/internal/common/util"
"bytes"
"context"
"encoding/json"
@@ -240,7 +241,7 @@ func (r *release) writePluginStore() error {
byID := versions.Plugins.ByID()
store := clientupdate.Store{Version: versions.ClientVersion}
for _, spec := range clientplugin.Shipped {
sum, err := releasepkg.HashFile(filepath.Join(r.client, "plugins", spec.FileName()))
sum, err := util.SHA256File(filepath.Join(r.client, "plugins", spec.FileName()))
if err != nil {
return err
}
+2 -1
View File
@@ -2,6 +2,7 @@ package main
import (
"archive/zip"
"bd2server/internal/common/util"
"bytes"
"encoding/json"
"errors"
@@ -279,7 +280,7 @@ func (t task) releasePublish(args []string) error {
return err
}
publish := func(source, name, platform, id, version string) (releasepkg.File, error) {
sum, err := releasepkg.HashFile(source)
sum, err := util.SHA256File(source)
if err != nil {
return releasepkg.File{}, err
}
+2 -1
View File
@@ -1,6 +1,7 @@
package main
import (
"bd2server/internal/common/util"
"encoding/json"
"fmt"
"os"
@@ -83,7 +84,7 @@ func (t task) stageSchedules(output string, versions versionconfig.Config) (*rel
}
for _, entry := range entries {
file := filepath.Join(source, entry.Name())
sum, err := releasepkg.HashFile(file)
sum, err := util.SHA256File(file)
if err != nil {
return nil, err
}
+8
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"os/signal"
"path/filepath"
clientapp "bd2server/internal/client/app"
clientconfig "bd2server/internal/client/config"
@@ -110,12 +111,19 @@ func runClient(args []string, options clientRunOptions) error {
*gameDir = preferences.GameDirectory
}
}
var packageDirectory, downloadManifest string
if options.versionConfigPath != "" {
packageDirectory = filepath.Dir(options.versionConfigPath)
downloadManifest = filepath.Join(packageDirectory, "tools", "client", "client-download.json")
}
if err := clientapp.Run(clientapp.Options{
InitialGameDir: *gameDir,
Logger: logger,
LogPath: logPath,
Versions: versions,
Development: options.versionConfigPath != "",
PackageDirectory: packageDirectory,
DownloadManifest: downloadManifest,
LocalIdentityPlugin: options.localIdentityPlugin,
LoginUIPlugin: options.loginUIPlugin,
CashShopPlugin: options.cashShopPlugin,
+12 -122
View File
@@ -7,16 +7,10 @@ import (
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"time"
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/download"
clientsetup "bd2server/internal/client/setup"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/taskgraph"
"bd2server/internal/common/versionconfig"
"bd2server/internal/client/preparation"
)
func prepareClient(args []string) error {
@@ -41,126 +35,22 @@ func prepareClient(args []string) error {
if fs.NArg() != 0 || *workers < 1 || *workers > 16 {
return errors.New("prepare accepts named options and workers must be 1-16")
}
if *downloadOnly && *baseOnly {
return errors.New("--download and --base select separate stages; omit both to run all stages")
}
if *baseOnly && *probeOnly {
return errors.New("--probe-only cannot be used with --base")
}
if *packageDir == "" {
executable, err := os.Executable()
if err != nil {
return err
}
*packageDir = filepath.Dir(executable)
}
var err error
*packageDir, err = filepath.Abs(*packageDir)
if err != nil {
return err
}
if *versionPath == "" {
*versionPath = filepath.Join(*packageDir, versionconfig.FileName)
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
var versions, downloaded versionconfig.Config
var settings clientconfig.Settings
graph, err := taskgraph.New(
taskgraph.Task{Name: "download", Run: func(ctx context.Context) error {
installed, err := download.Client(ctx, download.Options{
PackageDir: *packageDir, Manifest: *manifest,
GameDir: *gameDir, ResourceDir: *resources, ServerOrigin: *origin,
Workers: *workers, ProbeOnly: *probeOnly,
}, os.Stdout)
if err != nil {
return err
}
*gameDir, *resources, *origin = installed.GameDir, installed.ResourceDir, installed.ServerOrigin
downloaded = installed.Versions
return nil
}},
taskgraph.Task{Name: "base:configuration", Run: func(context.Context) error {
if *gameDir == "" {
*gameDir = filepath.Join(*packageDir, "game")
}
if *resources == "" {
*resources = filepath.Join(*packageDir, "resources")
}
if *origin == "" {
manifestPath := *manifest
if manifestPath == "" {
manifestPath = filepath.Join(*packageDir, "client-download.json")
}
defaults, err := commonconfig.Load(manifestPath, struct {
ServerOrigin string `json:"server_origin"`
}{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true})
if err != nil {
return err
}
*origin = defaults.ServerOrigin
}
var err error
versions, err = versionconfig.Load(*versionPath)
if err != nil {
return err
}
if !*baseOnly && (versions.GameVersion != downloaded.GameVersion || versions.GameDataVersion != downloaded.GameDataVersion || versions.BundleVersion != downloaded.BundleVersion) {
return errors.New("client package and download manifest versions differ")
}
return nil
}},
taskgraph.Task{Name: "base:settings", DependsOn: []string{"base:configuration"}, Run: func(context.Context) error {
var err error
settings, err = clientconfig.Normalize(clientconfig.Settings{ServerOrigin: *origin, CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: *resources})
return err
}},
taskgraph.Task{Name: "base:resources", DependsOn: []string{"base:settings"}, Run: func(ctx context.Context) error {
policyContext, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
_, err := clientsetup.FetchResourcePolicy(policyContext, nil, settings, versions)
return err
}},
taskgraph.Task{Name: "base:bepinex", DependsOn: []string{"base:resources"}, Run: func(context.Context) error {
return download.InstallBepInEx(*packageDir, *gameDir)
}},
taskgraph.Task{Name: "base:patch", DependsOn: []string{"base:bepinex"}, Run: func(context.Context) error {
_, err := clientsetup.Patch(*gameDir, settings, versions)
return err
}},
taskgraph.Task{Name: "base:plugins", DependsOn: []string{"base:patch"}, Run: func(context.Context) error {
plugins := filepath.Join(*packageDir, "plugins")
_, err := clientsetup.InstallPlugins(*gameDir, settings, versions,
filepath.Join(plugins, "BD2LocalIdentity.dll"), filepath.Join(plugins, "BD2LoginUI.dll"),
filepath.Join(plugins, "BD2CashShop.dll"), filepath.Join(plugins, "BD2FChat.dll"))
return err
}},
taskgraph.Task{Name: "base:preferences", DependsOn: []string{"base:plugins"}, Run: func(context.Context) error {
return clientconfig.SavePreferences(*gameDir)
}},
taskgraph.Task{Name: "base", DependsOn: []string{"base:preferences"}, Run: func(context.Context) error {
fmt.Println("Client prepared:", versions.GameVersion)
fmt.Println("Server:", settings.ServerOrigin)
return nil
}},
taskgraph.Task{Name: "prepare", DependsOn: []string{"download", "base"}},
)
result, err := preparation.Run(ctx, preparation.Options{
PackageDirectory: *packageDir, DownloadManifest: *manifest, VersionConfig: *versionPath,
GameDirectory: *gameDir, ResourceDirectory: *resources,
Settings: clientconfig.Settings{ServerOrigin: *origin, CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: *resources},
Workers: *workers, DownloadOnly: *downloadOnly, BaseOnly: *baseOnly, ProbeOnly: *probeOnly, PlanOnly: *planOnly,
}, os.Stdout)
if err != nil {
return err
}
target := "prepare"
if *downloadOnly || *probeOnly {
target = "download"
} else if *baseOnly {
target = "base"
}
if *planOnly {
plan, err := graph.Plan(target)
if err != nil {
return err
}
fmt.Println(strings.Join(plan, " -> "))
return nil
fmt.Println(strings.Join(result.Plan, " -> "))
} else if !*downloadOnly && !*probeOnly {
fmt.Println("Client prepared:", result.Versions.GameVersion)
fmt.Println("Server:", result.Settings.ServerOrigin)
}
return graph.Run(ctx, target)
return nil
}
+30 -50
View File
@@ -14,7 +14,6 @@ import (
"time"
clientconfig "bd2server/internal/client/config"
clientdownload "bd2server/internal/client/download"
clientlayout "bd2server/internal/client/layout"
clientplugin "bd2server/internal/client/plugin"
clientsetup "bd2server/internal/client/setup"
@@ -33,6 +32,8 @@ type Options struct {
LogPath string
Versions versionconfig.Config
Development bool
PackageDirectory string
DownloadManifest string
LocalIdentityPlugin string
LoginUIPlugin string
CashShopPlugin string
@@ -85,7 +86,7 @@ type Studio struct {
cancel context.CancelFunc
mu sync.Mutex
quitOnce sync.Once
launch func(string, string) error
launch func(string, string, *slog.Logger) error
savePreferences func(string) error
updates *clientupdate.Manager
}
@@ -153,7 +154,8 @@ func (s *Studio) Initialize() InitialState {
s.mu.Lock()
defer s.mu.Unlock()
state := InitialState{Platform: runtime.GOOS, ClientVersion: s.options.Versions.ClientVersion, GameVersion: s.options.Versions.GameVersion, LogPath: s.options.LogPath, GameDirectory: s.options.InitialGameDir, ServerOrigin: "http://127.0.0.1:8080", CDNMode: clientconfig.CDNOfficial}
if state.GameDirectory == "" {
s.installationDefaults(&state)
if s.options.InitialGameDir == "" {
return state
}
if _, err := clientsetup.Inspect(state.GameDirectory, s.versions(state.GameDirectory)); err != nil {
@@ -220,8 +222,7 @@ func (s *Studio) Browse(input Request) (Response, error) {
if dir == "" {
return success("Selection cancelled", nil), nil
}
status, err := clientsetup.Inspect(dir, s.versions(dir))
return success("Game client found", status), err
return success("Installation directory selected", clientsetup.GameStatus{GameDirectory: dir}), nil
})
}
@@ -263,7 +264,7 @@ func (s *Studio) Resources(input Request) (Response, error) {
func (s *Studio) Save(input Request) (Response, error) {
return s.perform("save settings", func() (Response, error) {
settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings(), s.versions(input.GameDirectory))
settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings())
if err != nil {
return Response{}, err
}
@@ -276,7 +277,10 @@ func (s *Studio) Save(input Request) (Response, error) {
func (s *Studio) Patch(input Request) (Response, error) {
return s.perform("patch client", func() (Response, error) {
result, err := clientsetup.Patch(input.GameDirectory, input.settings(), s.versions(input.GameDirectory))
if _, err := clientsetup.SaveSettings(input.GameDirectory, input.settings()); err != nil {
return Response{}, err
}
result, err := clientsetup.Patch(input.GameDirectory)
if err != nil {
return Response{}, err
}
@@ -293,7 +297,10 @@ func (s *Studio) Patch(input Request) (Response, error) {
func (s *Studio) Install(input Request) (Response, error) {
return s.perform("install plugins", func() (Response, error) {
result, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), s.versions(input.GameDirectory), s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
if _, err := clientsetup.SaveSettings(input.GameDirectory, input.settings()); err != nil {
return Response{}, err
}
result, err := clientsetup.InstallPlugins(input.GameDirectory, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
if err != nil {
return Response{}, err
}
@@ -326,9 +333,10 @@ func (s *Studio) Launch(input Request) (Response, error) {
if !status.BepInEx {
return Response{}, errors.New("install BepInEx before launching the game")
}
ctx, cancel := context.WithTimeout(s.context(), 12*time.Second)
defer cancel()
if _, err := clientsetup.FetchResourcePolicy(ctx, nil, input.settings(), versions); err != nil {
policyCtx, cancel := context.WithTimeout(s.context(), 12*time.Second)
_, err = clientsetup.FetchResourcePolicy(policyCtx, nil, input.settings(), versions)
cancel()
if err != nil {
return Response{}, err
}
@@ -337,10 +345,15 @@ func (s *Studio) Launch(input Request) (Response, error) {
if s.updates != nil {
configured.Runtime = s.updates.Runtime(input.GameDirectory)
}
settings, err := clientsetup.SaveSettings(input.GameDirectory, configured, versions)
settings, err := clientsetup.SaveSettings(input.GameDirectory, configured)
if err != nil {
return Response{}, err
}
if settings.CDNMode == clientconfig.CDNLocal {
if err := clientsetup.InstallLocalCatalog(input.GameDirectory, settings.LocalResourceDirectory, versions.BundleVersion); err != nil {
return Response{}, err
}
}
if err := s.savePreferences(input.GameDirectory); err != nil {
return Response{}, err
}
@@ -357,7 +370,7 @@ func (s *Studio) Launch(input Request) (Response, error) {
return Response{}, fmt.Errorf("install or update the client plugins before launching; %s is missing", name)
}
}
if err := s.launch(installation.LaunchTarget(), settings.ProxyURL); err != nil {
if err := s.launch(installation.LaunchTarget(), settings.ProxyURL, s.log()); err != nil {
if errors.Is(err, errGameAlreadyRunning) {
return success("Brown Dust II is already running", nil), nil
}
@@ -370,7 +383,7 @@ func (s *Studio) Launch(input Request) (Response, error) {
return launch()
}
var response Response
err = s.updates.WithLaunch(ctx, nil, status.GameDirectory, input.ServerOrigin, func() error {
err = s.updates.WithLaunch(s.context(), nil, status.GameDirectory, input.ServerOrigin, func() error {
var err error
response, err = launch()
return err
@@ -394,6 +407,9 @@ func (s *Studio) CheckUpdates() (Response, error) {
return Response{}, errors.New("update service is unavailable")
}
ctx := s.context()
if err := s.updates.WaitIdle(ctx); err != nil {
return Response{}, err
}
if err := s.updates.Check(ctx); err != nil {
return Response{}, err
}
@@ -443,39 +459,3 @@ func (s *Studio) Quit() {
}
})
}
// Prepare readies an installation in one step: the required game and resource
// update, BepInEx from the launcher package, the client patch and the plugins.
func (s *Studio) Prepare(input Request) (Response, error) {
return s.perform("prepare client", func() (Response, error) {
if s.updates != nil {
if err := s.updates.PrepareGame(s.context(), input.GameDirectory, input.ServerOrigin); err != nil {
return Response{}, err
}
}
versions := s.versions(input.GameDirectory)
status, err := clientsetup.Inspect(input.GameDirectory, versions)
if err != nil {
return Response{}, err
}
if !status.BepInEx {
executable, err := os.Executable()
if err != nil {
return Response{}, err
}
if err := clientdownload.InstallBepInEx(filepath.Dir(executable), status.GameDirectory); err != nil {
return Response{}, err
}
}
if _, err := clientsetup.Patch(input.GameDirectory, input.settings(), versions); err != nil {
return Response{}, err
}
if _, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), versions, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin); err != nil {
return Response{}, err
}
if err := s.savePreferences(input.GameDirectory); err != nil {
return Response{}, err
}
return success("Client prepared", nil), nil
})
}
+2 -1
View File
@@ -4,6 +4,7 @@ package app
import (
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
@@ -16,7 +17,7 @@ func ShowFatalError(err error) {
}
}
func launchGame(target, proxyURL string) error {
func launchGame(target, proxyURL string, _ *slog.Logger) error {
info, err := os.Stat(target)
if err != nil || !info.IsDir() || !strings.EqualFold(filepath.Ext(target), ".app") {
return fmt.Errorf("invalid macOS application bundle %q", target)
+2 -1
View File
@@ -5,6 +5,7 @@ package app
import (
"errors"
"fmt"
"log/slog"
"os"
)
@@ -14,6 +15,6 @@ func ShowFatalError(err error) {
}
}
func launchGame(string, string) error {
func launchGame(string, string, *slog.Logger) error {
return errors.New("the Brown Dust II client is not supported on Linux")
}
+28 -5
View File
@@ -5,6 +5,7 @@ package app
import (
"fmt"
"log"
"log/slog"
"os"
"os/exec"
"path/filepath"
@@ -62,7 +63,7 @@ func visibleCommand(name string, args ...string) *exec.Cmd {
return command
}
func launchGame(target, proxyURL string) error {
func launchGame(target, proxyURL string, logger *slog.Logger) error {
if processID, running, err := windowsExecutableProcessID(filepath.Base(target)); err != nil {
return err
} else if running {
@@ -77,10 +78,32 @@ func launchGame(target, proxyURL string) error {
if err := command.Start(); err != nil {
return err
}
// Unity creates the top-level window asynchronously. Best-effort foreground
// activation prevents the new window from opening behind BD2 Launcher.
activateProcessWindow(uint32(command.Process.Pid), 15*time.Second)
return nil
pid := command.Process.Pid
logger.Info("game process started", "pid", pid, "executable", target)
finished := make(chan error, 1)
go func() {
err := command.Wait()
logger.Info("game process exited", "pid", pid, "exit_code", command.ProcessState.ExitCode(), "error", err)
finished <- err
}()
deadline := time.NewTimer(30 * time.Second)
defer deadline.Stop()
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case err := <-finished:
return fmt.Errorf("game exited before showing a window: pid=%d exit_code=%d error=%v; see Player.log", pid, command.ProcessState.ExitCode(), err)
case <-deadline.C:
return fmt.Errorf("game process is running without a visible window after 30 seconds: pid=%d; see Player.log", pid)
case <-ticker.C:
if topLevelWindowForProcess(uint32(pid)) != 0 {
activateProcessWindow(uint32(pid), 0)
logger.Info("game window ready", "pid", pid)
return nil
}
}
}
}
func windowsExecutableProcessID(name string) (uint32, bool, error) {
+78
View File
@@ -0,0 +1,78 @@
package app
import (
"context"
"io"
"os"
"path/filepath"
"runtime"
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/preparation"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/versionconfig"
)
func (s *Studio) packageDirectory() (string, error) {
if s.options.PackageDirectory != "" {
return filepath.Abs(s.options.PackageDirectory)
}
executable, err := os.Executable()
return filepath.Dir(executable), err
}
func (s *Studio) downloadManifest(directory string) string {
if s.options.DownloadManifest != "" {
return s.options.DownloadManifest
}
return filepath.Join(directory, "client-download.json")
}
func (s *Studio) installationDefaults(state *InitialState) {
directory, err := s.packageDirectory()
if err != nil {
return
}
defaults, err := commonconfig.Load(s.downloadManifest(directory), struct {
ServerOrigin string `json:"server_origin"`
}{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true})
if err == nil {
if origin, err := clientconfig.NormalizeOrigin(defaults.ServerOrigin); err == nil {
state.ServerOrigin = origin
}
}
if runtime.GOOS == "windows" && state.GameDirectory == "" {
state.GameDirectory = filepath.Join(directory, "game")
state.CDNMode = clientconfig.CDNLocal
}
state.LocalResourceDirectory = filepath.Join(directory, "resources")
}
func (s *Studio) Prepare(input Request) (Response, error) {
return s.perform("prepare client", func() (Response, error) {
directory, err := s.packageDirectory()
if err != nil {
return Response{}, err
}
result, err := preparation.Run(s.context(), preparation.Options{
PackageDirectory: directory, DownloadManifest: s.downloadManifest(directory),
GameDirectory: input.GameDirectory, Settings: input.settings(), Versions: s.versions(input.GameDirectory),
Workers: 8, DownloadIfMissing: true,
LocalIdentityPlugin: s.options.LocalIdentityPlugin, LoginUIPlugin: s.options.LoginUIPlugin,
CashShopPlugin: s.options.CashShopPlugin, FChatPlugin: s.options.FChatPlugin,
SavePreferences: s.savePreferences,
PrepareGame: func(ctx context.Context, game string, settings clientconfig.Settings) (versionconfig.Config, error) {
if s.updates != nil {
if err := s.updates.PrepareGame(ctx, game, settings.ServerOrigin); err != nil {
return versionconfig.Config{}, err
}
}
return s.versions(game), nil
},
}, io.Discard)
if err != nil {
return Response{}, err
}
return success("Client prepared", result.Status), nil
})
}
+9 -9
View File
@@ -12,14 +12,14 @@
*{box-sizing:border-box}body{margin:0;background:#e7dcc7;color:var(--ink);font:14px/1.65 var(--sans);overflow-x:hidden}button,input{font:inherit}button{cursor:pointer}button:disabled{cursor:wait;opacity:.5}button,input,a{-webkit-tap-highlight-color:transparent}button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--rust);outline-offset:5px}[hidden]{display:none!important}::selection{background:#b9764c;color:#fff9ef}
.landscape{position:fixed;inset:0;z-index:-3;background:linear-gradient(130deg,#f1e9d9 0%,#e7d5b6 42%,#bc8665 100%);overflow:hidden}.landscape svg{position:absolute;width:100%;height:100%;transition:transform 2s var(--ease),opacity 1.6s;transform:scale(1.04);opacity:.87}.landscape:after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,rgba(244,237,222,.8),rgba(240,228,207,.2) 65%,transparent),linear-gradient(0deg,rgba(73,48,31,.14),transparent 48%)}body[data-scene=server] .landscape svg{transform:scale(1.14) translateX(-2%)}body[data-scene=desk] .landscape svg{transform:scale(1.2) translateY(-3%);opacity:.27}body[data-scene=desk] .landscape:after{background:rgba(240,234,221,.55)}
.grain{position:fixed;inset:0;pointer-events:none;z-index:20;opacity:.038;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='grain'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.82' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Cpath fill='%23000' filter='url(%23grain)' d='M0 0h180v180H0z'/%3E%3C/svg%3E")}.sunlight{position:fixed;inset:-40%;pointer-events:none;z-index:-2;background:radial-gradient(ellipse at 70% 23%,#fff7d777,transparent 38%);animation:drift 18s ease-in-out infinite alternate}
.topbar{height:94px;max-width:1440px;margin:auto;padding:0 58px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:24px}.brand{display:flex;gap:13px;align-items:center;flex-shrink:0}.emblem{display:block;width:40px;height:40px;flex-shrink:0}.brand-name{font-size:13px;letter-spacing:.19em;line-height:1.4}.brand-name small{display:block;font-size:9px;letter-spacing:.28em;color:var(--muted);margin-top:4px}.top-note{font-size:11px;color:var(--muted);letter-spacing:.07em}.text-btn{background:none;border:0;color:var(--muted);padding:8px 0;border-bottom:1px solid transparent}.text-btn:hover{color:var(--rust);border-bottom-color:var(--rust)}
main{max-width:1324px;margin:auto;padding:0 58px}.scene{position:relative}.intro-scene{min-height:calc(100svh - 178px);display:grid;grid-template-columns:1.1fr .9fr;align-items:center;gap:8%;padding:66px 0 82px}.eyebrow{font-size:10px;letter-spacing:.22em;text-transform:uppercase;display:flex;align-items:center;gap:12px;color:#81634c;margin-bottom:24px}.eyebrow:before{content:'';height:1px;width:32px;background:currentColor}h1,h2,h3,p{margin:0}h1{font:400 clamp(42px,4.8vw,68px)/1.28 var(--serif);letter-spacing:.035em}.lead{max-width:380px;font-size:14px;color:var(--muted);line-height:1.95;margin-top:26px}.intro-label{display:flex;gap:14px;align-items:center;margin-top:44px;font-size:11px;color:#8a7059}.intro-label i{height:1px;width:30px;background:#987759}.form-card{position:relative;background:linear-gradient(135deg,rgba(250,246,237,.89),rgba(238,225,203,.7));border:1px solid rgba(255,255,255,.6);box-shadow:0 24px 70px -35px #65472c77,inset 0 0 0 1px rgba(116,89,55,.035);backdrop-filter:blur(24px);border-radius:4px;padding:34px 32px}.card-number{font:italic 46px/1 var(--serif);color:#b2997e;opacity:.6;margin-bottom:30px}.form-card h2{font:400 23px var(--serif);margin-bottom:9px}.description{font-size:12px;line-height:1.8;color:var(--muted);margin-bottom:26px}code{font:11px/1.8 Consolas,monospace;overflow-wrap:anywhere}label.field-label{display:block;font-size:11px;margin-bottom:9px;color:#6f5c49}.input-row{display:flex;gap:8px}input[type=text]{width:100%;min-width:0;border:1px solid #aa927755;border-radius:3px;padding:13px 12px;background:#fffcf57d;color:var(--ink);outline:none;transition:background .2s,border-color .2s;font-size:12px}input[type=text]:focus{border-color:var(--rust);background:#fffaf0}.btn{border:1px solid #81664a55;border-radius:3px;padding:11px 18px;display:inline-flex;align-items:center;justify-content:center;gap:12px;min-height:43px;background:#fffcf533;color:var(--ink);transition:background .25s,box-shadow .25s,transform .25s;white-space:nowrap;font-size:12px}.btn:hover:not(:disabled){background:#fff9eb99;transform:translateY(-2px)}.btn.primary{background:#4b3a2c;color:#fff5e4;border-color:#4b3a2c}.btn.primary:hover:not(:disabled){background:#654932;box-shadow:0 6px 17px #4b3a2c24}.btn.rust{background:#985e40;color:#fff6e8;border-color:#985e40}.btn.rust:hover:not(:disabled){background:#ad6c49}.arrow{font-size:20px;font-weight:300;line-height:1}.wide{width:100%;justify-content:space-between;margin-top:28px;padding:14px 18px}.small-note{font-size:11px;color:#877460;margin-top:12px;line-height:1.8}.inline-result{font-size:11px;min-height:22px;margin-top:10px;color:var(--muted)}.inline-result.error{color:var(--bad)}.form-tools{display:flex;align-items:center;justify-content:space-between;margin-top:4px;gap:8px;font-size:11px}.server-back{margin-top:14px;text-align:center}.server-back .text-btn{font-size:11px}.bottom-bar{max-width:1324px;margin:auto;padding:0 58px 28px;display:flex;justify-content:space-between;align-items:center;gap:24px}.steps{display:flex;list-style:none;padding:0;margin:0;gap:26px;font-size:11px;color:#8f7d69}.steps li{display:flex;gap:8px;align-items:center}.steps .num{font:italic 14px var(--serif)}.steps li.active{color:#503b2b}.steps li.active:after{content:'';width:19px;height:1px;background:#86573b}.bottom-note{font-size:10px;color:#897963;letter-spacing:.04em}
.topbar{height:94px;max-width:1440px;margin:auto;padding:0 58px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:24px}.brand{display:flex;gap:13px;align-items:center;flex-shrink:0}.emblem{display:block;width:40px;height:40px;flex-shrink:0}.brand-name{font-size:13px;letter-spacing:.19em;line-height:1.4}.brand-name small{display:block;font-size:9px;letter-spacing:.28em;color:var(--muted);margin-top:4px}.text-btn{background:none;border:0;color:var(--muted);padding:8px 0;border-bottom:1px solid transparent}.text-btn:hover{color:var(--rust);border-bottom-color:var(--rust)}
main{max-width:1324px;margin:auto;padding:0 58px}.scene{position:relative}.intro-scene{min-height:calc(100svh - 178px);display:grid;grid-template-columns:1.1fr .9fr;align-items:center;gap:8%;padding:66px 0 82px}.eyebrow{font-size:10px;letter-spacing:.22em;text-transform:uppercase;display:flex;align-items:center;gap:12px;color:#81634c;margin-bottom:24px}.eyebrow:before{content:'';height:1px;width:32px;background:currentColor}h1,h2,h3,p{margin:0}h1{font:400 clamp(42px,4.8vw,68px)/1.28 var(--serif);letter-spacing:.035em}.lead{max-width:380px;font-size:14px;color:var(--muted);line-height:1.95;margin-top:26px}.intro-label{display:flex;gap:14px;align-items:center;margin-top:44px;font-size:11px;color:#8a7059}.intro-label i{height:1px;width:30px;background:#987759}.form-card{position:relative;background:linear-gradient(135deg,rgba(250,246,237,.89),rgba(238,225,203,.7));border:1px solid rgba(255,255,255,.6);box-shadow:0 24px 70px -35px #65472c77,inset 0 0 0 1px rgba(116,89,55,.035);backdrop-filter:blur(24px);border-radius:4px;padding:34px 32px}.card-number{font:italic 46px/1 var(--serif);color:#b2997e;opacity:.6;margin-bottom:30px}.form-card h2{font:400 23px var(--serif);margin-bottom:9px}.description{font-size:12px;line-height:1.8;color:var(--muted);margin-bottom:26px}code{font:11px/1.8 Consolas,monospace;overflow-wrap:anywhere}label.field-label{display:block;font-size:11px;margin-bottom:9px;color:#6f5c49}.input-row{display:flex;gap:8px}.input-row>.btn{flex-shrink:0}input[type=text]{width:100%;min-width:0;border:1px solid #aa927755;border-radius:3px;padding:13px 12px;background:#fffcf57d;color:var(--ink);outline:none;transition:background .2s,border-color .2s;font-size:12px}input[type=text]:focus{border-color:var(--rust);background:#fffaf0}.btn{border:1px solid #81664a55;border-radius:3px;padding:11px 18px;display:inline-flex;align-items:center;justify-content:center;gap:12px;min-height:43px;background:#fffcf533;color:var(--ink);transition:background .25s,box-shadow .25s,transform .25s;white-space:nowrap;font-size:12px}.btn:hover:not(:disabled){background:#fff9eb99;transform:translateY(-2px)}.btn.primary{background:#4b3a2c;color:#fff5e4;border-color:#4b3a2c}.btn.primary:hover:not(:disabled){background:#654932;box-shadow:0 6px 17px #4b3a2c24}.btn.rust{background:#985e40;color:#fff6e8;border-color:#985e40}.btn.rust:hover:not(:disabled){background:#ad6c49}.arrow{font-size:20px;font-weight:300;line-height:1}.wide{width:100%;justify-content:space-between;margin-top:28px;padding:14px 18px}.small-note{font-size:11px;color:#877460;margin-top:12px;line-height:1.8}.inline-result{font-size:11px;min-height:22px;margin-top:10px;color:var(--muted)}.inline-result.error{color:var(--bad)}.form-tools{display:flex;align-items:center;justify-content:space-between;margin-top:4px;gap:8px;font-size:11px}.server-back{margin-top:14px;text-align:center}.server-back .text-btn{font-size:11px}.bottom-bar{max-width:1324px;margin:auto;padding:0 58px 28px;display:flex;justify-content:space-between;align-items:center;gap:24px}.steps{display:flex;list-style:none;padding:0;margin:0;gap:26px;font-size:11px;color:#8f7d69}.steps li{display:flex;gap:8px;align-items:center}.steps .num{font:italic 14px var(--serif)}.steps li.active{color:#503b2b}.steps li.active:after{content:'';width:19px;height:1px;background:#86573b}.bottom-note{font-size:10px;color:#897963;letter-spacing:.04em}
.scene.is-entering .reveal{animation:reveal 1.3s var(--ease) both;animation-delay:calc(var(--i,0)*110ms)}.scene.is-leaving{animation:leave .55s cubic-bezier(.4,0,.6,1) both;pointer-events:none}.transition-veil{position:fixed;inset:0;background:linear-gradient(115deg,#eee4d4ed,#dfc7a8e8);z-index:30;pointer-events:none;opacity:0;backdrop-filter:blur(8px)}.transition-veil.play{animation:veil 1.25s ease-in-out both}.opening-curtain{position:fixed;inset:0;background:#e8decc;pointer-events:none;z-index:40;animation:opening 1.65s ease forwards}
.desk-scene{padding:46px 0 34px}.desk-header{display:flex;justify-content:space-between;align-items:end;gap:24px;margin-bottom:30px}.desk-header .eyebrow{margin-bottom:13px}.desk-header h1{font-size:42px}.desk-header p{margin-top:12px;font-size:12px;color:var(--muted)}.connection-chip{display:flex;align-items:center;gap:9px;font-size:11px;color:#74634f;border:1px solid var(--line);padding:8px 13px;border-radius:30px}.dot{width:6px;height:6px;border-radius:50%;background:#a99b85;display:inline-block;flex-shrink:0}.dot.good{background:var(--olive);box-shadow:0 0 0 4px #68744912}.dot.bad{background:var(--bad)}.desk-grid{display:grid;grid-template-columns:minmax(0,1fr) 298px;gap:24px}.main-panel{background:#f9f5ec94;border:1px solid #fff9;border-radius:4px;box-shadow:0 12px 50px -40px #5c412c55}.panel-section{padding:25px 28px;border-bottom:1px solid var(--line)}.panel-section:last-child{border-bottom:0}.section-title{display:flex;align-items:center;gap:11px;margin-bottom:22px}.section-title .index{font:italic 14px var(--serif);color:#a08569}.section-title h2{font-size:15px;font-weight:500}.section-title .end{margin-left:auto;font-size:10px;color:var(--muted)}.setting-row{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-top:18px}.setting-name{font-size:10px;color:var(--muted);margin-bottom:4px}.setting-value{font-size:12px;overflow-wrap:anywhere}.setting-row>div{min-width:0}.setting-row .text-btn{font-size:11px;flex-shrink:0;color:var(--rust)}.route-options{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.route{position:relative;cursor:pointer}.route input{position:absolute;opacity:0;inset:0;width:100%;height:100%;margin:0}.route-content{display:block;position:relative;pointer-events:none;min-height:139px;padding:15px 14px;border:1px solid var(--line);border-radius:3px;transition:.25s;background:#f8f3e83d}.route-content .route-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.route-code{font:10px var(--serif);letter-spacing:.08em;color:#98826b}.radio-dot{width:11px;height:11px;border-radius:50%;border:1px solid #aa9680;display:block}.route-content strong{font-size:12px;font-weight:500;display:block;margin-bottom:5px}.route-content small{font-size:10px;line-height:1.75;display:block;color:var(--muted)}.route input:checked+.route-content{border-color:#9e7551;background:#b9986920;box-shadow:inset 0 0 0 1px #9e755118}.route input:checked+.route-content .radio-dot{background:#916c4a;border:3px solid #e8d9c3;box-shadow:0 0 0 1px #916c4a}.route input:focus-visible+.route-content{outline:2px solid var(--rust);outline-offset:4px}.route input:disabled+.route-content{opacity:.55}.route-actions{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:18px}.route-actions .text-btn{font-size:11px}.route-hint{font-size:10px;color:#927d64;margin-top:13px}.policy{font:11px/1.9 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#dfd2bc50;border-left:2px solid #a3835e;padding:13px;margin-top:16px}.prepare-note{font-size:11px;color:var(--muted);margin:-8px 0 19px;line-height:1.8}.prepare-actions{display:flex;gap:10px;flex-wrap:wrap}.prepare-actions .btn{flex:1}.status-panel{align-self:start;padding:25px 23px;background:#dfd1ba66;border:1px solid #9875501c;border-radius:4px}.status-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px}.status-title h2{font:400 19px var(--serif)}.status-title span{font-size:9px;color:#927d65;letter-spacing:.1em}.check{display:flex;align-items:center;justify-content:space-between;padding:14px 0;border-bottom:1px solid var(--line);font-size:11px;gap:8px}.check span:last-child{color:#948471;font-size:10px}.check span.ok{color:var(--olive)}.check span.warn{color:var(--bad)}.status-foot{font-size:10px;color:#8d7a63;margin-top:14px;line-height:1.8}.log-wrap{border-top:1px solid var(--line);margin-top:24px;padding-top:19px}.log-heading{font-size:10px;color:#8d745b;display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.log{font-size:11px;color:#7e6c56;line-height:1.8;overflow-wrap:anywhere;min-height:65px}.log strong{display:block;color:var(--ink);font-size:12px;font-weight:500;margin-bottom:5px}.history{margin-top:14px;border-top:1px solid var(--line);padding-top:12px;font-size:10px;color:#806e59}.history summary{cursor:pointer}.history ol{list-style:none;padding:0;margin:10px 0 0;max-height:180px;overflow:auto}.history li{padding:7px 0;border-top:1px solid #a487651a;overflow-wrap:anywhere}.history time{display:block;color:#9a876f;font-size:9px}.history li.error{color:var(--bad)}.unsaved{font-size:10px;color:var(--rust);margin-top:12px}.desk-footer{display:flex;justify-content:space-between;gap:20px;margin-top:24px;color:#8a765e;font-size:10px}
.desk-actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:flex-end}.desk-actions .btn{min-height:38px;padding:8px 16px}.local-resource{margin-top:14px;padding:14px;border:1px solid var(--line);background:#f8f3e83d;border-radius:3px}.local-resource[hidden]{display:none}.local-resource .small-note{margin:8px 0 0}
.update-box{display:grid;gap:4px;margin-top:12px;padding:10px 12px;border:1px solid #c9ac8288;border-radius:3px;background:#fff8ec80;font-size:12px}.update-box span{white-space:pre-line;max-height:120px;overflow:auto;color:#6d5a47}.update-box .text-btn{justify-self:start}.toast{position:fixed;bottom:28px;left:50%;transform:translate(-50%,18px);max-width:min(590px,calc(100% - 32px));width:max-content;padding:13px 21px;background:#483a2e;color:#fff4e0;box-shadow:0 10px 40px #483a2e26;border:1px solid #c9ac82;border-radius:3px;font-size:12px;opacity:0;pointer-events:none;transition:.35s var(--ease);z-index:70}.toast.show{opacity:1;transform:translate(-50%,0)}.toast.error{background:#793e30;color:#fff0e3}dialog{width:min(490px,calc(100% - 32px));padding:30px;border:1px solid #fff9;border-radius:5px;background:#f0e7d7;color:var(--ink);box-shadow:0 30px 140px #37271955}dialog::backdrop{background:#40322266;backdrop-filter:blur(9px)}dialog[open]{animation:reveal .55s var(--ease)}.dialog-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:25px}.dialog-head h2{font:24px var(--serif)}.dialog-close{background:none;border:0;font-size:23px;color:var(--muted);padding:0 7px}.dialog-actions{display:flex;justify-content:flex-end;margin-top:20px}.quit-scene{min-height:65svh;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center}.quit-scene h1{font-size:44px}.quit-scene p{color:var(--muted);margin-top:20px;font-size:13px}
@keyframes reveal{from{opacity:0;filter:blur(10px);transform:translateY(24px) scale(.986)}to{opacity:1;filter:blur(0);transform:none}}@keyframes leave{to{opacity:0;filter:blur(8px);transform:translateY(-15px) scale(1.014)}}@keyframes veil{0%,100%{opacity:0}45%,58%{opacity:1}}@keyframes opening{0%,15%{opacity:1}100%{opacity:0}}@keyframes drift{to{transform:translate(-4%,3%) scale(1.05)}}
@media(min-width:1500px){.intro-scene{gap:13%}.form-card{padding:40px}.intro-scene h1{font-size:72px}}@media(max-width:1050px){.topbar{padding:0 30px}main,.bottom-bar{padding-left:30px;padding-right:30px}.intro-scene{gap:5%}.form-card{padding:27px 23px}.desk-grid{grid-template-columns:minmax(0,1fr) 250px;gap:16px}.panel-section{padding:23px 20px}.status-panel{padding:23px 18px}.route-content{padding:12px 10px}.top-note{display:none}}@media(max-width:760px){.topbar{height:77px;padding:0 22px}main,.bottom-bar{padding-left:22px;padding-right:22px}.intro-scene{grid-template-columns:1fr;gap:32px;padding:42px 0;min-height:auto}.intro-scene h1{font-size:43px}.eyebrow{margin-bottom:17px}.lead{margin-top:18px;max-width:100%}.intro-label{display:none}.form-card{padding:25px}.card-number{position:absolute;right:25px;top:25px;font-size:31px}.form-card h2{padding-right:45px}.bottom-bar{align-items:start;flex-direction:column;gap:15px}.steps{gap:21px}.desk-scene{padding-top:31px}.desk-header{align-items:start}.desk-header h1{font-size:34px}.connection-chip{font-size:10px;padding:6px 10px;margin-top:4px}.desk-grid{grid-template-columns:1fr}.status-panel{display:grid;grid-template-columns:1fr 1fr;gap:0 30px}.status-title{grid-column:1/-1}.log-wrap{margin-top:10px;border-top:0}.status-foot{margin-bottom:14px}.desk-footer{flex-direction:column;gap:7px}.bottom-note{font-size:9px}.landscape svg{width:180%;left:-60%}.desk-header p{max-width:240px}.route-content{min-height:145px}}@media(max-width:400px){main,.bottom-bar{padding-left:16px;padding-right:16px}.form-card{padding:23px 18px}.route-options{grid-template-columns:1fr}.route-content{min-height:0;padding:12px 14px}.route-content .route-top{float:right;margin:0 0 10px 20px;gap:12px}.route-content small{max-width:90%}.status-panel{display:block}.desk-header{flex-direction:column;gap:14px}.panel-section{padding:22px 16px}.btn{padding-left:13px;padding-right:13px}.steps{gap:15px}.route-actions{align-items:stretch}.prepare-actions{flex-direction:column}}
@media(min-width:1500px){.intro-scene{gap:13%}.form-card{padding:40px}.intro-scene h1{font-size:72px}}@media(max-width:1050px){.topbar{padding:0 30px}main,.bottom-bar{padding-left:30px;padding-right:30px}.intro-scene{gap:5%}.form-card{padding:27px 23px}.desk-grid{grid-template-columns:minmax(0,1fr) 250px;gap:16px}.panel-section{padding:23px 20px}.status-panel{padding:23px 18px}.route-content{padding:12px 10px}}@media(max-width:760px){.topbar{height:77px;padding:0 22px}main,.bottom-bar{padding-left:22px;padding-right:22px}.intro-scene{grid-template-columns:1fr;gap:32px;padding:42px 0;min-height:auto}.intro-scene h1{font-size:43px}.eyebrow{margin-bottom:17px}.lead{margin-top:18px;max-width:100%}.intro-label{display:none}.form-card{padding:25px}.card-number{position:absolute;right:25px;top:25px;font-size:31px}.form-card h2{padding-right:45px}.bottom-bar{align-items:start;flex-direction:column;gap:15px}.steps{gap:21px}.desk-scene{padding-top:31px}.desk-header{align-items:start}.desk-header h1{font-size:34px}.connection-chip{font-size:10px;padding:6px 10px;margin-top:4px}.desk-grid{grid-template-columns:1fr}.status-panel{display:grid;grid-template-columns:1fr 1fr;gap:0 30px}.status-title{grid-column:1/-1}.log-wrap{margin-top:10px;border-top:0}.status-foot{margin-bottom:14px}.desk-footer{flex-direction:column;gap:7px}.bottom-note{font-size:9px}.landscape svg{width:180%;left:-60%}.desk-header p{max-width:240px}.route-content{min-height:145px}}@media(max-width:400px){main,.bottom-bar{padding-left:16px;padding-right:16px}.form-card{padding:23px 18px}.route-options{grid-template-columns:1fr}.route-content{min-height:0;padding:12px 14px}.route-content .route-top{float:right;margin:0 0 10px 20px;gap:12px}.route-content small{max-width:90%}.status-panel{display:block}.desk-header{flex-direction:column;gap:14px}.panel-section{padding:22px 16px}.btn{padding-left:13px;padding-right:13px}.steps{gap:15px}.route-actions{align-items:stretch}.prepare-actions{flex-direction:column}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}.opening-curtain{display:none}}
.proxy-select{width:100%;padding:12px 14px;border:1px solid var(--line);border-radius:3px;background:#f8f3e8;color:var(--ink);font:inherit}#proxyURL{width:100%}/* Window chrome belongs to the page; keep scrolling without a visible gutter. */
html,body{scrollbar-width:none}html::-webkit-scrollbar,body::-webkit-scrollbar{display:none}
@@ -38,11 +38,11 @@ html:lang(ja){--sans:'Segoe UI','Yu Gothic UI',Meiryo,sans-serif;--serif:Georgia
<svg viewBox="0 0 1600 1000" preserveAspectRatio="xMidYMid slice" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="sky" x2="0" y2="1"><stop stop-color="#f3e6c9"/><stop offset=".7" stop-color="#dab88e"/><stop offset="1" stop-color="#b98560"/></linearGradient><linearGradient id="mesa" x2="0.2" y2="1"><stop stop-color="#b48360"/><stop offset="1" stop-color="#8f624b"/></linearGradient><linearGradient id="sand" x2=".6" y2="1"><stop stop-color="#b8946e"/><stop offset="1" stop-color="#674b39"/></linearGradient><filter id="soft"><feGaussianBlur stdDeviation="18"/></filter></defs><path fill="url(#sky)" d="M0 0h1600v1000H0z"/><circle cx="1150" cy="270" r="91" fill="#fff4ce" opacity=".4" filter="url(#soft)"/><circle cx="1150" cy="270" r="68" fill="#fff0c7" opacity=".8"/><path d="M0 640 240 590 370 610 520 558 670 580 820 510 950 560 1120 492 1280 560 1420 482 1600 530V1000H0Z" fill="#bea17f" opacity=".6"/><path d="m835 710 60-133 43-18 17-104 32-8 17-45 130-2 18 48 32 6 15 112 35 14 36 114 58 38 212 18V1000H790Z" fill="url(#mesa)" opacity=".65"/><path d="m1004 400 15 162 24 39-12 110 75 112 18-203-23-111 33-109z" fill="#d3a079" opacity=".38"/><path d="m1280 760 81-113 24-160 47-12 13-59 122 3 14 67 19 18v496h-320Z" fill="#9a6b4f" opacity=".6"/><path d="M0 746Q260 652 525 746T1030 775 1600 724V1000H0Z" fill="#c8aa80"/><path d="M0 869Q300 687 660 860T1300 814 1600 830V1000H0Z" fill="url(#sand)" opacity=".65"/><path d="M860 1000q185-97 375-124t365-13v137Z" fill="#826045" opacity=".7"/><path d="M870 998q146-128 235-165t69-90" fill="none" stroke="#e1c397" stroke-width="3" opacity=".24"/></svg>
</div>
<div class="sunlight" aria-hidden="true"></div><div class="grain" aria-hidden="true"></div><div class="opening-curtain" aria-hidden="true"></div><div id="veil" class="transition-veil" aria-hidden="true"></div>
<header class="topbar"><div class="brand"><img class="emblem" src="/icon.svg" width="40" height="40" alt=""><div class="brand-name"><span data-i18n="launcher.brand.title"></span><small data-i18n="launcher.brand.subtitle"></small></div></div><div class="top-note" data-i18n="launcher.top_note"></div><select class="lang-select" id="language" data-i18n-attr="aria-label:launcher.language;title:launcher.language"><option value="en_us" lang="en">English</option><option value="ko_kr" lang="ko">한국어</option><option value="ja_jp" lang="ja">日本語</option><option value="zh_tw" lang="zh-TW">繁體中文</option><option value="zh_cn" lang="zh-CN">简体中文</option></select><div class="window-controls" role="group" data-i18n-attr="aria-label:launcher.window.controls"><button class="window-control" id="windowMinimise" data-i18n-attr="aria-label:launcher.window.minimize;title:launcher.window.minimize"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 9h10"/></svg></button><button class="window-control" id="windowMaximise" data-i18n-attr="aria-label:launcher.window.maximize;title:launcher.window.maximize"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="1.5" y="1.5" width="9" height="9"/></svg></button><button class="window-control window-close" id="windowClose" data-i18n-attr="aria-label:launcher.window.close;title:launcher.window.close"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></header>
<header class="topbar"><div class="brand"><img class="emblem" src="/icon.svg" width="40" height="40" alt=""><div class="brand-name"><span data-i18n="launcher.brand.title"></span><small data-i18n="launcher.brand.subtitle"></small></div></div><select class="lang-select" id="language" data-i18n-attr="aria-label:launcher.language;title:launcher.language"><option value="en_us" lang="en">English</option><option value="ko_kr" lang="ko">한국어</option><option value="ja_jp" lang="ja">日本語</option><option value="zh_tw" lang="zh-TW">繁體中文</option><option value="zh_cn" lang="zh-CN">简体中文</option></select><div class="window-controls" role="group" data-i18n-attr="aria-label:launcher.window.controls"><button class="window-control" id="windowMinimise" data-i18n-attr="aria-label:launcher.window.minimize;title:launcher.window.minimize"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 9h10"/></svg></button><button class="window-control" id="windowMaximise" data-i18n-attr="aria-label:launcher.window.maximize;title:launcher.window.maximize"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="1.5" y="1.5" width="9" height="9"/></svg></button><button class="window-control window-close" id="windowClose" data-i18n-attr="aria-label:launcher.window.close;title:launcher.window.close"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></header>
<main>
<section class="scene intro-scene is-entering" id="directoryScene" aria-labelledby="directoryTitle">
<div><div class="eyebrow reveal" style="--i:1" data-i18n="launcher.directory.step"></div><h1 class="reveal" style="--i:2" id="directoryTitle" tabindex="-1" data-i18n="launcher.directory.heading"></h1><p class="lead reveal" style="--i:3" data-i18n="launcher.directory.lead"></p><div class="intro-label reveal" style="--i:4"><i></i><span data-i18n="launcher.directory.label"></span></div></div>
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">01</div><h2 data-i18n="launcher.directory.title"></h2><p class="description" id="directoryDescription" data-i18n="launcher.directory.description" data-i18n-code="BrownDust II.exe"></p><div id="directoryHome"><div id="directoryFields"><label class="field-label" for="gameDir" data-i18n="launcher.directory.field"></label><div class="input-row"><input id="gameDir" type="text" value="" data-i18n-attr="placeholder:launcher.directory.placeholder" autocomplete="off" spellcheck="false"><button class="btn" id="browse" data-i18n="launcher.browse"></button></div><div class="form-tools"><span id="directoryHint" data-i18n="launcher.directory.hint"></span><button class="text-btn" id="inspect" data-i18n="launcher.directory.inspect"></button></div><p class="inline-result" id="directoryResult" role="status"></p></div></div><button class="btn primary wide" id="directoryNext"><span data-i18n="launcher.directory.next"></span><span class="arrow" aria-hidden="true">→</span></button><p class="small-note" data-i18n="launcher.directory.note"></p></div>
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">01</div><h2 data-i18n="launcher.directory.title"></h2><p class="description" id="directoryDescription" data-i18n="launcher.directory.description" data-i18n-code="BrownDust II.exe"></p><div id="directoryHome"><div id="directoryFields"><label class="field-label" for="gameDir" data-i18n="launcher.directory.field"></label><div class="input-row"><input id="gameDir" type="text" value="" data-i18n-attr="placeholder:launcher.directory.placeholder" autocomplete="off" spellcheck="false"><button class="btn" id="browse" data-i18n="launcher.browse"></button></div><div class="form-tools"><span id="directoryHint" data-i18n="launcher.directory.hint"></span><button class="text-btn" id="inspect" data-i18n="launcher.directory.inspect"></button></div><p class="inline-result" id="directoryResult" role="status"></p></div></div><button class="btn primary wide" id="directoryNext"><span data-i18n="launcher.directory.next"></span><span class="arrow" aria-hidden="true">→</span></button></div>
</section>
<section class="scene intro-scene" id="serverScene" hidden aria-labelledby="serverTitle">
<div><div class="eyebrow reveal" style="--i:1" data-i18n="launcher.server.step"></div><h1 class="reveal" style="--i:2" id="serverTitle" tabindex="-1" data-i18n="launcher.server.heading"></h1><p class="lead reveal" style="--i:3" data-i18n="launcher.server.lead"></p><div class="intro-label reveal" style="--i:4"><i></i><span data-i18n="launcher.server.label"></span></div></div>
@@ -99,7 +99,7 @@ let scene='directory',busy=false,transitioning=false,toastTimer,editorKind=null,
const status={executable:null,resources:null,bepinex:null,config:null};
function payload(){const mode=document.querySelector('input[name="cdn"]:checked').value;return{game_directory:$('gameDir').value.trim(),server_origin:$('origin').value.trim(),cdn_mode:mode,local_resource_directory:mode==='local'?$('localResourceDir').value.trim():'',proxy_url:$('proxyMode').value==='manual'?$('proxyURL').value.trim():''}}
function signature(){return JSON.stringify({...payload(),proxy_mode:$('proxyMode').value})}
const backendKeys={'Update check completed':'backend.update_checked','Launcher is restarting to finish the update':'backend.launcher_restarting','update service is unavailable':'backend.update_unavailable','Another update operation is in progress':'backend.update_busy','No launcher update is available':'backend.no_launcher_update','The launcher update has not finished downloading':'backend.launcher_update_incomplete','The launcher is updating; start the game after it finishes':'backend.launcher_updating','The game is running; its plugins update after it exits':'backend.game_running_plugins','The server is updating; try again after it finishes':'backend.server_maintenance','Selection cancelled':'backend.selection_cancelled','Game client found':'backend.game_found','Local resource directory found':'backend.local_resources_found','Game directory is valid':'backend.directory_valid','The client will use the release-locked official CDN':'backend.official_cdn','Local resources verified':'backend.local_verified','Server resource policy verified':'backend.server_policy_verified','Connection settings saved':'backend.settings_saved','Client prepared':'backend.prepared','Client entry point patched; the original backup was retained':'backend.patched','Client patch is already complete; no asset file was rewritten':'backend.patch_current','BD2 client plugins installed or updated':'backend.plugins_installed','BD2 client plugins are already up to date; no DLL was rewritten':'backend.plugins_current','Brown Dust II started':'backend.game_started','Brown Dust II is already running':'backend.game_running','Client tool exited':'backend.tool_exited'};
const backendKeys={'Update check completed':'backend.update_checked','Launcher is restarting to finish the update':'backend.launcher_restarting','update service is unavailable':'backend.update_unavailable','Another update operation is in progress':'backend.update_busy','No launcher update is available':'backend.no_launcher_update','The launcher update has not finished downloading':'backend.launcher_update_incomplete','The launcher is updating; start the game after it finishes':'backend.launcher_updating','The game is running; its plugins update after it exits':'backend.game_running_plugins','The server is updating; try again after it finishes':'backend.server_maintenance','Selection cancelled':'backend.selection_cancelled','Game client found':'backend.game_found','Installation directory selected':'backend.directory_selected','Local resource directory found':'backend.local_resources_found','Game directory is valid':'backend.directory_valid','The client will use the release-locked official CDN':'backend.official_cdn','Local resources verified':'backend.local_verified','Server resource policy verified':'backend.server_policy_verified','Connection settings saved':'backend.settings_saved','Client prepared':'backend.prepared','Client entry point patched; the original backup was retained':'backend.patched','Client patch is already complete; no asset file was rewritten':'backend.patch_current','BD2 client plugins installed or updated':'backend.plugins_installed','BD2 client plugins are already up to date; no DLL was rewritten':'backend.plugins_current','Brown Dust II started':'backend.game_started','Brown Dust II is already running':'backend.game_running','Client tool exited':'backend.tool_exited'};
const PLUGINS_REJECTED=/^Server (\S+) no longer accepts these plugins: (.+)\. Update the plugins in the launcher first$/;
const pluginList=list=>({getString:async ()=>(await Promise.all(list.split(', ').map(async item=>{const m=/^(.+) (\S+) \(needs (\S+)\)$/.exec(item);return m?await dynamicText('backend.plugin_requirement',m[1],m[2],m[3]):item}))).join(t('common.list_separator'))});
const GAME_MISMATCH=/^Server game version (\S+) does not match client game version (\S+)$/;
@@ -137,13 +137,13 @@ $('gameDir').addEventListener('input',async ()=>await invalidate(true));$('origi
$('browse').onclick=async ()=>await action('browse',async()=>{const previous=payload().game_directory;const r=await api('browse',{...payload(),dialog_title:t('launcher.dialog.game_directory')});if(r.data){await applyStatus(r.data);if(payload().game_directory!==previous)$('policy').hidden=true}await show(r.text)});
$('browseResources').onclick=async ()=>await action('browseResources',async()=>{const r=await api('browseResources',{...payload(),dialog_title:t('launcher.dialog.resource_directory')});if(r.data){$('localResourceDir').value=r.data.local_directory||'';await invalidate()}await show(r.text)});
$('inspect').onclick=async ()=>await action('inspect',inspect);$('refresh').onclick=async ()=>await action('refresh',inspect);
$('directoryNext').onclick=async ()=>await action('directoryNext',async()=>{await inspect();await sync();await navigateScene('server')});
$('directoryNext').onclick=async ()=>await action('directoryNext',async()=>{requireDirectory();await sync();await navigateScene('server')});
$('serverBack').onclick=async ()=>{if(!busy)await navigateScene('directory')};
$('serverNext').onclick=async ()=>await action('serverNext',async()=>{await requireOrigin();await sync();await navigateScene('desk')});
$('checkResources').onclick=async ()=>await action('checkResources',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('resources',payload()),p=r.data||{},local=payload().local_resource_directory,v=value=>value||t('launcher.resources.missing');$('policy').hidden=false;await put('policy',{getString:()=>p.mode==='official'?`${t('launcher.resources.official.code')} · ${t('launcher.resources.policy_official')}`:p.mode==='local'?`${t('launcher.resources.local.code')} · ${p.local_directory||local}\nServerData · ${v(p.server_data_url)}\nGameData · ${v(p.game_data_url)}`:`${t('launcher.resources.server.code')} · ${t('launcher.resources.policy_server')}\nServerData · ${v(p.server_data_url)}\nGameData · ${v(p.game_data_url)}\nBundle · ${v(p.bundle_version)}\nGameData · ${v(p.game_data_version)}`});await show(r.text)});
async function saved(){savedSignature=signature();status.config=true;await sync()}
$('save').onclick=async ()=>await action('save',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('save',payload());await saved();await show(r.text)});
$('prepare').onclick=async ()=>await action('prepare',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('prepare',payload());status.bepinex=true;await saved();await show(r.text)});
$('prepare').onclick=async ()=>await action('prepare',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('prepare',payload());await applyStatus(r.data);await saved();await show(r.text)});
$('patch').onclick=async ()=>await action('patch',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('patch',payload());await saved();await show(r.text)});
$('install').onclick=async ()=>await action('install',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('install',payload());status.bepinex=true;await saved();await show(r.text)});
$('launch').onclick=async ()=>await action('launch',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('launch',payload());await saved();await show(r.text)});
@@ -153,7 +153,7 @@ $('windowMaximise').onclick=()=>window.runtime?.WindowToggleMaximise();
document.querySelector('.topbar').ondblclick=e=>{if(!e.target.closest('.window-controls,.lang-select'))window.runtime?.WindowToggleMaximise()};
$('windowClose').onclick=async ()=>{clearTimeout(toastTimer);try{bridge().Quit().catch(async error=>await show(problemText(error),true))}catch(error){await show(problemText(error),true)}};
$('gameDir').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();(editorKind?$('inspect'):$('directoryNext')).click()}});$('origin').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();(editorKind?$('doneEditor'):$('serverNext')).click()}});
async function initialize(){setBusy(true);try{const initial=await bridge().Initialize();HOST_PLATFORM=initial.platform;INITIAL_CDN=initial.cdn_mode;AUTO_OPEN=initial.auto_open;$('gameDir').value=initial.game_directory||'';$('origin').value=initial.server_origin||'http://127.0.0.1:8080';$('localResourceDir').value=initial.local_resource_directory||'';$('proxyURL').value=initial.proxy_url||'';$('proxyMode').value=initial.proxy_url?'manual':'direct';$('clientReleaseVersion').textContent=initial.client_version||'';$('gameReleaseVersion').textContent=initial.game_version||'';$('persistentLogPath').textContent=initial.log_path||'';const initialRadio=document.querySelector(`input[name="cdn"][value="${CSS.escape(INITIAL_CDN)}"]`);if(initialRadio)initialRadio.checked=true;if(HOST_PLATFORM==='darwin'){const description=$('directoryDescription');$('gameDir').dataset.i18nAttr='placeholder:launcher.directory.placeholder_mac';description.dataset.i18n='launcher.directory.description_mac';description.dataset.i18nCode='BrownDust II.app';await applyStatic()}await sync();if($('gameDir').value.trim()){await inspect();if(AUTO_OPEN){await saved();await navigateScene('desk')}}}catch(error){await show(problemText(error),true)}finally{setBusy(false)}}
async function initialize(){setBusy(true);try{const initial=await bridge().Initialize();HOST_PLATFORM=initial.platform;INITIAL_CDN=initial.cdn_mode;AUTO_OPEN=initial.auto_open;$('gameDir').value=initial.game_directory||'';$('origin').value=initial.server_origin||'http://127.0.0.1:8080';$('localResourceDir').value=initial.local_resource_directory||'';$('proxyURL').value=initial.proxy_url||'';$('proxyMode').value=initial.proxy_url?'manual':'direct';$('clientReleaseVersion').textContent=initial.client_version||'';$('gameReleaseVersion').textContent=initial.game_version||'';$('persistentLogPath').textContent=initial.log_path||'';const initialRadio=document.querySelector(`input[name="cdn"][value="${CSS.escape(INITIAL_CDN)}"]`);if(initialRadio)initialRadio.checked=true;if(HOST_PLATFORM==='darwin'){const description=$('directoryDescription');$('gameDir').dataset.i18nAttr='placeholder:launcher.directory.placeholder_mac';description.dataset.i18n='launcher.directory.description_mac';description.dataset.i18nCode='BrownDust II.app';await applyStatic()}await sync();if(AUTO_OPEN){await inspect();await saved();await navigateScene('desk')}}catch(error){await show(problemText(error),true)}finally{setBusy(false)}}
const updateNotes=notes=>!notes?'':typeof notes==='string'?notes:notes[locale]||notes.en_us||Object.values(notes).find(Boolean)||'';
function formatBytes(bytes){const mb=bytes>=1048576,value=bytes/(mb?1048576:1024);try{return new Intl.NumberFormat(HTML_LANG[locale],{style:'unit',unit:mb?'megabyte':'kilobyte',maximumFractionDigits:1}).format(value)}catch{return value.toFixed(1)+(mb?' MB':' KB')}}
function formatDate(value){const date=new Date(value+'T00:00:00Z');if(!/^\d{4}-\d{2}-\d{2}$/.test(value)||isNaN(date))return value;try{return date.toLocaleDateString(HTML_LANG[locale],{year:'numeric',month:'long',day:'numeric',timeZone:'UTC'})}catch{return value}}
+9 -10
View File
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 Launcher",
"launcher.top_note": "BD2 Launcher · Settings stay on this computer",
"launcher.language": "Language",
"launcher.window.controls": "Window controls",
"launcher.window.minimize": "Minimize",
"launcher.window.maximize": "Maximize or restore",
"launcher.window.close": "Close",
"launcher.browse": "Browse",
"launcher.directory.heading": "Start with the\ngame directory.",
"launcher.directory.lead": "Select the installed game folder.\nWe will check the game executable and asset files before setting up the connection.",
"launcher.directory.heading": "Choose where\nto install.",
"launcher.directory.lead": "No game installed? Choose a location, continue setup, then select Prepare client.\nYou can also select an existing game folder.",
"launcher.directory.label": "BrownDust II · Client setup",
"launcher.directory.title": "Select game directory",
"launcher.directory.description": "Select the folder that contains %[1]s.",
"launcher.directory.title": "Game installation location",
"launcher.directory.description": "Choose a new installation directory or an existing folder containing %[1]s.",
"launcher.directory.description_mac": "Select %[1]s or the folder that contains it.",
"launcher.directory.field": "Game installation directory",
"launcher.directory.placeholder": "Example: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "Example: /Applications/BrownDust II.app",
"launcher.directory.hint": "Enter a path directly or browse for a folder.",
"launcher.directory.hint": "Enter a new path or browse existing folders.",
"launcher.directory.inspect": "Check directory",
"launcher.directory.next": "Continue to server setup",
"launcher.directory.note": "This step only checks files; it does not modify game assets.",
"launcher.directory.found": "Game executable and asset file found.",
"launcher.directory.incomplete": "Check complete; review the missing items in the launcher.",
"launcher.directory.changed": "The directory changed; check it again.",
"launcher.server.heading": "Next, set up\nthe server.",
"launcher.server.lead": "Enter the address of the server to connect to.\nIn the launcher you can then choose a resource source, apply the patch, and install plugins.",
"launcher.server.lead": "Enter the server address you want to connect to.\nThen select Prepare client in the launcher to download and install the missing game.",
"launcher.server.label": "Directory selected · You can still change it later",
"launcher.server.title": "Server address",
"launcher.server.description": "Enter the full address; a port may be included.",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "Resource URLs supplied by the server",
"launcher.save": "Save connection settings",
"launcher.unsaved": "Current settings have not been saved.",
"launcher.prepare.title": "Patch and plugins",
"launcher.prepare.title": "Installation and preparation",
"launcher.prepare.note": "Close the game first. One-click prepare also downloads required game files and installs BepInEx from the launcher package. The patch only changes the built-in Intro address and keeps a %[1]s backup.",
"launcher.prepare.patch": "Apply client patch",
"launcher.prepare.install": "Install / update plugins",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "LOCAL STATUS",
"launcher.resources.official.code": "OFFICIAL",
"launcher.resources.local.code": "LOCAL",
"launcher.resources.server.code": "SERVER"
"launcher.resources.server.code": "SERVER",
"backend.directory_selected": "Installation location selected"
}
+9 -10
View File
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 ランチャー",
"launcher.top_note": "BD2 ランチャー · 設定はこの PC に保存されます",
"launcher.language": "言語",
"launcher.window.controls": "ウィンドウ操作",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化 / 元に戻す",
"launcher.window.close": "閉じる",
"launcher.browse": "参照",
"launcher.directory.heading": "まずは\nフォルダー選択から。",
"launcher.directory.lead": "インストール済みのゲームフォルダーを選択してください。\nゲーム本体とリソースファイルを確認してから、接続設定に進みます。",
"launcher.directory.heading": "まずはゲームの\nインストール先を。",
"launcher.directory.lead": "未インストールの場合は保存先を選び、設定後に一括準備を実行してください。\n既存のゲームフォルダーも選択できます。",
"launcher.directory.label": "BrownDust II · クライアント設定",
"launcher.directory.title": "ゲームフォルダーを選択",
"launcher.directory.description": "%[1]s があるフォルダーを選択してください。",
"launcher.directory.title": "ゲームのインストール先",
"launcher.directory.description": "新しいインストール先、または %[1]s を含む既存のフォルダーを選択してください。",
"launcher.directory.description_mac": "%[1]s またはそれがあるフォルダーを選択してください。",
"launcher.directory.field": "ゲームのインストール先",
"launcher.directory.placeholder": "例: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例: /Applications/BrownDust II.app",
"launcher.directory.hint": "パスを直接入力するか、参照して選択できます。",
"launcher.directory.hint": "新しいパスの入力、または既存のフォルダーの選択ができます。",
"launcher.directory.inspect": "フォルダーを確認",
"launcher.directory.next": "サーバー設定へ進む",
"launcher.directory.note": "この手順ではファイルを確認するだけで、ゲームのリソースは変更しません。",
"launcher.directory.found": "ゲーム本体とリソースファイルが見つかりました。",
"launcher.directory.incomplete": "確認が完了しました。不足している項目はランチャーで確認してください。",
"launcher.directory.changed": "フォルダーが変更されました。もう一度確認してください。",
"launcher.server.heading": "次に、\nサーバーを設定します。",
"launcher.server.lead": "接続先のサーバーアドレスを入力してください。\nランチャーでは、リソースの取得元の選択、パッチの適用、プラグインのインストールができます。",
"launcher.server.lead": "接続するサーバーのアドレスを入力してください。\nその後、ランチャーの一括準備で未インストールのゲームをダウンロードできます。",
"launcher.server.label": "フォルダー選択済み · 後から変更できます",
"launcher.server.title": "サーバーアドレス",
"launcher.server.description": "完全なアドレスを入力してください。ポート番号も指定できます。",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "リソースのアドレスはサーバーが提供します",
"launcher.save": "接続設定を保存",
"launcher.unsaved": "現在の設定はまだ保存されていません。",
"launcher.prepare.title": "パッチとプラグイン",
"launcher.prepare.title": "インストールと準備",
"launcher.prepare.note": "操作の前にゲームを終了してください。まとめて準備は、必要なゲームファイルをダウンロードし、ランチャー同梱のパッケージから BepInEx をインストールします。パッチは内蔵の Intro アドレスのみを変更し、%[1]s のバックアップを残します。",
"launcher.prepare.patch": "クライアントパッチを適用",
"launcher.prepare.install": "プラグインをインストール / 更新",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "ローカル状態",
"launcher.resources.official.code": "公式",
"launcher.resources.local.code": "ローカル",
"launcher.resources.server.code": "サーバー"
"launcher.resources.server.code": "サーバー",
"backend.directory_selected": "インストール先を選択しました"
}
+9 -10
View File
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 런처",
"launcher.top_note": "BD2 런처 · 설정은 이 컴퓨터에 저장됩니다",
"launcher.language": "언어",
"launcher.window.controls": "창 제어",
"launcher.window.minimize": "최소화",
"launcher.window.maximize": "최대화 또는 이전 크기로 복원",
"launcher.window.close": "닫기",
"launcher.browse": "찾아보기",
"launcher.directory.heading": "게임 폴더부터\n시작하세요.",
"launcher.directory.lead": "설치된 게임 폴더를 선택하세요.\n게임 실행 파일과 리소스 파일을 확인한 뒤 연결 설정으로 넘어갑니다.",
"launcher.directory.heading": "게임을 설치할\n위치를 선택하세요.",
"launcher.directory.lead": "게임이 없나요? 설치 위치를 선택하고 설정을 마친 뒤 한 번에 준비를 실행하세요.\n이미 설치된 게임 폴더를 선택해도 됩니다.",
"launcher.directory.label": "BrownDust II · 클라이언트 설정",
"launcher.directory.title": "게임 폴더 선택",
"launcher.directory.description": "%[1]s 파일이 있는 폴더를 선택하세요.",
"launcher.directory.title": "게임 설치 위치",
"launcher.directory.description": "새 설치 경로 또는 %[1]s 파일이 있는 기존 게임 폴더를 선택하세요.",
"launcher.directory.description_mac": "%[1]s 또는 이 앱이 있는 폴더를 선택하세요.",
"launcher.directory.field": "게임 설치 폴더",
"launcher.directory.placeholder": "예: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "예: /Applications/BrownDust II.app",
"launcher.directory.hint": "경로를 직접 입력하거나 폴더를 찾아볼 수 있습니다.",
"launcher.directory.hint": "새 경로를 입력하거나 기존 폴더를 찾아볼 수 있습니다.",
"launcher.directory.inspect": "폴더 확인",
"launcher.directory.next": "서버 설정으로 계속",
"launcher.directory.note": "이 단계에서는 파일만 확인하며 게임 리소스를 수정하지 않습니다.",
"launcher.directory.found": "게임 실행 파일과 리소스 파일을 찾았습니다.",
"launcher.directory.incomplete": "확인을 마쳤습니다. 누락된 항목은 런처에서 확인하세요.",
"launcher.directory.changed": "폴더가 변경되었습니다. 다시 확인하세요.",
"launcher.server.heading": "이제\n서버를 설정하세요.",
"launcher.server.lead": "연결할 서버 주소를 입력하세요.\n런처에서 리소스 출처를 선택하고, 패치를 적용하고, 플러그인을 설치할 수 있습니다.",
"launcher.server.lead": "연결할 서버 주소를 입력하세요.\n이후 런처에서 한 번에 준비를 실행하면 없는 게임을 다운로드하고 설치합니다.",
"launcher.server.label": "폴더 선택 완료 · 나중에 변경할 수 있습니다",
"launcher.server.title": "서버 주소",
"launcher.server.description": "전체 주소를 입력하세요. 포트를 포함할 수 있습니다.",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "서버가 리소스 주소를 제공합니다",
"launcher.save": "연결 설정 저장",
"launcher.unsaved": "현재 설정이 아직 저장되지 않았습니다.",
"launcher.prepare.title": "패치 및 플러그인",
"launcher.prepare.title": "설치 및 준비",
"launcher.prepare.note": "작업 전에 게임을 종료하세요. 한 번에 준비는 필요한 게임 파일을 내려받고 런처 패키지에서 BepInEx를 설치합니다. 패치는 내장된 Intro 주소만 변경하며 %[1]s 백업을 남깁니다.",
"launcher.prepare.patch": "클라이언트 패치 적용",
"launcher.prepare.install": "플러그인 설치 / 업데이트",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "로컬 상태",
"launcher.resources.official.code": "공식",
"launcher.resources.local.code": "로컬",
"launcher.resources.server.code": "서버"
"launcher.resources.server.code": "서버",
"backend.directory_selected": "설치 위치를 선택했습니다"
}
+9 -10
View File
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 启动器",
"launcher.top_note": "BD2 启动器 · 配置保存在本机",
"launcher.language": "语言",
"launcher.window.controls": "窗口控制",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化或还原",
"launcher.window.close": "关闭",
"launcher.browse": "浏览",
"launcher.directory.heading": "先从游戏目录\n开始。",
"launcher.directory.lead": "选择已安装的游戏文件夹。\n我们会检查游戏程序和资源文件,再继续设置连接。",
"launcher.directory.heading": "先选好游戏\n安装位置。",
"launcher.directory.lead": "还没安装?选择一个安装位置,继续设置后点击一键准备。\n已有游戏也可以直接选择原来的文件夹。",
"launcher.directory.label": "BrownDust II · 客户端配置",
"launcher.directory.title": "选择游戏目录",
"launcher.directory.description": "请选择包含 %[1]s 的文件夹。",
"launcher.directory.title": "游戏安装位置",
"launcher.directory.description": "选择新的安装目录,或包含 %[1]s 的已有游戏文件夹。",
"launcher.directory.description_mac": "请选择 %[1]s 或它所在的文件夹。",
"launcher.directory.field": "游戏安装目录",
"launcher.directory.placeholder": "例如 E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例如 /Applications/BrownDust II.app",
"launcher.directory.hint": "可直接填写路径,也可以浏览目录。",
"launcher.directory.hint": "可以填写新路径,也可以浏览已有目录。",
"launcher.directory.inspect": "检查目录",
"launcher.directory.next": "继续设置服务器",
"launcher.directory.note": "此步骤只检查文件,不会修改游戏资源。",
"launcher.directory.found": "游戏程序和资源文件已检测到。",
"launcher.directory.incomplete": "检查已完成,请在启动器查看缺失项。",
"launcher.directory.changed": "目录已修改,请重新检查。",
"launcher.server.heading": "接下来,\n设置服务器。",
"launcher.server.lead": "填写要连接的服务端地址。\n进入启动器后,你可以选择资源来源、应用补丁和安装插件。",
"launcher.server.lead": "填写要连接的服务端地址。\n进入启动器后,点击一键准备即可下载并安装缺失的游戏。",
"launcher.server.label": "目录已选择 · 之后仍可修改",
"launcher.server.title": "服务器地址",
"launcher.server.description": "填写完整地址,可以包含端口。",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "由服务器提供资源地址",
"launcher.save": "保存连接设置",
"launcher.unsaved": "当前设置尚未保存。",
"launcher.prepare.title": "补丁与插件",
"launcher.prepare.title": "安装与准备",
"launcher.prepare.note": "操作前请先关闭游戏。一键准备会按需下载游戏文件,并从启动器自带包安装 BepInEx。补丁只修改内置 Intro 地址,并保留 %[1]s 备份。",
"launcher.prepare.patch": "应用客户端补丁",
"launcher.prepare.install": "安装 / 更新插件",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "本机状态",
"launcher.resources.official.code": "官方",
"launcher.resources.local.code": "本地",
"launcher.resources.server.code": "服务器"
"launcher.resources.server.code": "服务器",
"backend.directory_selected": "已选择安装位置"
}
+9 -10
View File
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 啟動器",
"launcher.top_note": "BD2 啟動器 · 設定儲存在本機",
"launcher.language": "語言",
"launcher.window.controls": "視窗控制項",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化或還原",
"launcher.window.close": "關閉",
"launcher.browse": "瀏覽",
"launcher.directory.heading": "先從遊戲目錄\n開始。",
"launcher.directory.lead": "選擇已安裝的遊戲資料夾。\n我們會先檢查遊戲程式和資源檔案,再繼續設定連線。",
"launcher.directory.heading": "先選好遊戲\n安裝位置。",
"launcher.directory.lead": "尚未安裝?選擇安裝位置,繼續設定後點擊一鍵準備。\n已有遊戲也可以直接選擇原來的資料夾。",
"launcher.directory.label": "BrownDust II · 用戶端設定",
"launcher.directory.title": "選擇遊戲目錄",
"launcher.directory.description": "請選擇包含 %[1]s 的資料夾。",
"launcher.directory.title": "遊戲安裝位置",
"launcher.directory.description": "選擇新的安裝目錄,或包含 %[1]s 的現有遊戲資料夾。",
"launcher.directory.description_mac": "請選擇 %[1]s 或其所在的資料夾。",
"launcher.directory.field": "遊戲安裝目錄",
"launcher.directory.placeholder": "例如 E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例如 /Applications/BrownDust II.app",
"launcher.directory.hint": "可直接輸入路徑,也可以瀏覽資料夾。",
"launcher.directory.hint": "可以填寫新路徑,也可以瀏覽現有目錄。",
"launcher.directory.inspect": "檢查目錄",
"launcher.directory.next": "繼續設定伺服器",
"launcher.directory.note": "此步驟只會檢查檔案,不會修改遊戲資源。",
"launcher.directory.found": "已偵測到遊戲程式和資源檔案。",
"launcher.directory.incomplete": "檢查完成,請在啟動器中查看缺少的項目。",
"launcher.directory.changed": "目錄已變更,請重新檢查。",
"launcher.server.heading": "接下來,\n設定伺服器。",
"launcher.server.lead": "輸入要連線的伺服器位址。\n進入啟動器後,即可選擇資源來源、套用修補程式並安裝插件。",
"launcher.server.lead": "填寫要連線的伺服器位址。\n進入啟動器後,點擊一鍵準備即可下載並安裝缺少的遊戲。",
"launcher.server.label": "已選擇目錄 · 之後仍可修改",
"launcher.server.title": "伺服器位址",
"launcher.server.description": "請輸入完整位址,可包含連接埠。",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "由伺服器提供資源位址",
"launcher.save": "儲存連線設定",
"launcher.unsaved": "目前的設定尚未儲存。",
"launcher.prepare.title": "修補程式與插件",
"launcher.prepare.title": "安裝與準備",
"launcher.prepare.note": "操作前請先關閉遊戲。一鍵準備會視需要下載遊戲檔案,並從啟動器內建包安裝 BepInEx。修補程式只會修改內建的 Intro 位址,並保留 %[1]s 備份。",
"launcher.prepare.patch": "套用用戶端修補程式",
"launcher.prepare.install": "安裝 / 更新插件",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "本機狀態",
"launcher.resources.official.code": "官方",
"launcher.resources.local.code": "本機",
"launcher.resources.server.code": "伺服器"
"launcher.resources.server.code": "伺服器",
"backend.directory_selected": "已選擇安裝位置"
}
+4
View File
@@ -8,6 +8,7 @@ import (
"net"
"net/url"
"path/filepath"
"reflect"
"strconv"
"strings"
@@ -158,6 +159,9 @@ func Save(gameDir string, in Settings) (Settings, error) {
if err != nil {
return Settings{}, err
}
if current, err := Load(gameDir); err == nil && reflect.DeepEqual(current, settings) {
return settings, nil
}
path := Path(gameDir)
if err := commonconfig.Save(path, settings, commonconfig.WriteOptions{}); err != nil {
return Settings{}, fmt.Errorf("client config: save: %w", err)
+3
View File
@@ -54,6 +54,9 @@ func SavePreferences(gameDirectory string) error {
return err
}
preferences := Preferences{SchemaVersion: preferencesSchemaVersion, GameDirectory: abs}
if current, err := LoadPreferences(); err == nil && current == preferences {
return nil
}
if err := commonconfig.Save(path, preferences, commonconfig.WriteOptions{DirectoryMode: 0o700}); err != nil {
return fmt.Errorf("save client preferences: %w", err)
}
+1 -31
View File
@@ -6,7 +6,6 @@ import (
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
@@ -192,43 +191,14 @@ func extractArchive(path, root string, game bool, digest string) error {
return err
}
}
marker := filepath.Join(root, ".bd2-official-game-version")
if game {
value, err := os.ReadFile(marker)
ready := err == nil && strings.TrimSpace(string(value)) == digest
for _, entry := range entries {
info, err := os.Stat(entry.target)
if err != nil || info.IsDir() != entry.file.FileInfo().IsDir() || (!info.IsDir() && uint64(info.Size()) != entry.file.UncompressedSize64) {
ready = false
break
}
if !info.IsDir() {
installed, err := os.Open(entry.target)
if err != nil {
ready = false
break
}
hash := crc32.NewIEEE()
_, readErr := io.Copy(hash, installed)
closeErr := installed.Close()
if readErr != nil || closeErr != nil || hash.Sum32() != entry.file.CRC32 {
ready = false
break
}
}
}
if ready {
return nil
}
return extractGame(entries, root, digest)
}
for _, entry := range entries {
if err := extractEntry(entry); err != nil {
return fmt.Errorf("extract %s: %w", entry.file.Name, err)
}
}
if game {
return atomicWrite(marker, []byte(digest+"\n"))
}
return nil
}
+19 -14
View File
@@ -89,31 +89,36 @@ func Client(ctx context.Context, options Options, out io.Writer) (Installation,
return result, err
}
defer d.client.CloseIdleConnections()
builds, err := d.fastest(ctx, m.BuildOrigins, m.GamePath, "Game ZIP")
if err != nil {
return result, err
}
dataPath := "/GameData/" + m.GameDataVersion
serverPath := "/ServerData/" + m.Platform + "/HD/" + m.BundleVersion
dataOrigins, err := d.fastest(ctx, m.ResourceOrigins, dataPath+"/release/common-dbdata.bin", "GameData")
if err != nil {
return result, err
}
bundleOrigins, err := d.fastest(ctx, m.ResourceOrigins, serverPath+"/catalog_alpha.json", "ServerData")
if err != nil {
return result, err
}
if options.ProbeOnly {
for _, probe := range []struct {
origins []string
path, label string
}{{m.BuildOrigins, m.GamePath, "Game ZIP"}, {m.ResourceOrigins, dataPath + "/release/common-dbdata.bin", "GameData"}, {m.ResourceOrigins, serverPath + "/catalog_alpha.json", "ServerData"}} {
if _, err := d.fastest(ctx, probe.origins, probe.path, probe.label); err != nil {
return result, err
}
}
return result, nil
}
d.measureOrigins = true
archive := filepath.Join(packageDir, "downloads", "BrownDust-II-"+m.GameVersion+".zip")
if err := d.receiveAll(ctx, []file{{remote: m.GamePath, target: archive, digest: m.GameSHA256, size: m.GameBytes}}, builds, 1); err != nil {
gameFile := file{remote: m.GamePath, target: archive, digest: m.GameSHA256, size: m.GameBytes}
builds := m.BuildOrigins
if !d.verified(gameFile) {
builds, err = d.fastest(ctx, m.BuildOrigins, m.GamePath, "Game ZIP")
if err != nil {
return result, err
}
}
if err := d.receiveAll(ctx, []file{gameFile}, builds, 1); err != nil {
return result, err
}
if err := extractArchive(archive, result.GameDir, true, m.GameSHA256); err != nil {
return result, err
}
if err := d.resources(ctx, result.ResourceDir, m, serverPath, dataPath, bundleOrigins, dataOrigins, options.Workers); err != nil {
if err := d.resources(ctx, result.ResourceDir, m, serverPath, dataPath, m.ResourceOrigins, m.ResourceOrigins, options.Workers); err != nil {
return result, err
}
d.log("Downloaded: game=%s resources=%s", result.GameDir, result.ResourceDir)
+159 -2
View File
@@ -11,8 +11,11 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
commonconfig "bd2server/internal/common/config"
)
@@ -38,10 +41,17 @@ func TestClientProbeAndDownloadOnlyDoNotRequirePreparationPackage(t *testing.T)
}
return raw.Bytes()
}
game := makeArchive(requiredGameFiles)
gameNames := append(slices.Clone(requiredGameFiles), "BrownDust II_Data/resources.assets", "BrownDust II_Data/StreamingAssets/aa/catalog.json")
game := makeArchive(gameNames)
data := makeArchive([]string{"common.db"})
catalog := []byte(`{"m_InternalIds":["{BDNetwork.CdnInfo.Info}/StandaloneWindows64/HD/` + bundleVersion + `/scene.bundle"]}` + strings.Repeat(" ", 256<<10))
bundleData := []byte{'U', 'n', 'i', 't', 'y', 'F', 'S', 0, 0, 0, 0, 6, 'v', 0, 'r', 0, 0, 0, 0, 0, 0, 0, 0, 28, 'd', 'a', 't', 'a'}
var mu sync.Mutex
var requested []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
requested = append(requested, r.URL.Path)
mu.Unlock()
switch {
case strings.HasPrefix(r.URL.Path, "/Build/"):
_, _ = w.Write(game)
@@ -56,7 +66,7 @@ func TestClientProbeAndDownloadOnlyDoNotRequirePreparationPackage(t *testing.T)
case strings.HasSuffix(r.URL.Path, "/catalog_alpha.hash"):
_, _ = io.WriteString(w, "0f90a94601be05737f86a4ec7a1c889f")
case strings.HasSuffix(r.URL.Path, "/scene.bundle"):
_, _ = w.Write([]byte{'U', 'n', 'i', 't', 'y', 'F', 'S', 0, 0, 0, 0, 6, 'v', 0, 'r', 0, 0, 0, 0, 0, 0, 0, 0, 24})
_, _ = w.Write(bundleData)
default:
http.NotFound(w, r)
}
@@ -106,4 +116,151 @@ func TestClientProbeAndDownloadOnlyDoNotRequirePreparationPackage(t *testing.T)
if _, err := os.Stat(filepath.Join(installed.ResourceDir, "resource-fetch-manifest.json")); err != nil {
t.Fatal("resource installation did not complete", err)
}
resetRequests := func() { mu.Lock(); requested = nil; mu.Unlock() }
requests := func() []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(requested) }
run := func() {
t.Helper()
if _, err := Client(context.Background(), Options{PackageDir: root, Workers: 2}, io.Discard); err != nil {
t.Fatal(err)
}
}
snapshot := func() map[string]time.Time {
t.Helper()
out := map[string]time.Time{}
if err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
info, err := entry.Info()
if err == nil {
out[path] = info.ModTime()
}
return err
}); err != nil {
t.Fatal(err)
}
return out
}
assertUnchanged := func(before map[string]time.Time, except ...string) {
t.Helper()
after := snapshot()
if len(before) != len(after) {
t.Fatal("repeat changed the installation file set")
}
for path, stamp := range before {
if !slices.Contains(except, path) && after[path] != stamp {
t.Fatalf("repeat rewrote %s", path)
}
}
}
before := snapshot()
resetRequests()
run()
if got := requests(); len(got) != 0 {
t.Fatalf("complete installation still contacted download origins: %v", got)
}
assertUnchanged(before)
prepared := []string{"BrownDust II_Data/resources.assets", "BrownDust II_Data/StreamingAssets/aa/catalog.json"}
patched := []byte("launcher-prepared-content")
for _, relative := range prepared {
if err := os.WriteFile(filepath.Join(installed.GameDir, filepath.FromSlash(relative)), patched, 0600); err != nil {
t.Fatal(err)
}
}
if err := RecordPreparedGame(installed.GameDir, prepared...); err != nil {
t.Fatal(err)
}
if err := RecordPreparedGame(installed.GameDir, "UnityPlayer.dll"); err == nil {
t.Fatal("unrecognized game change was accepted as launcher output")
}
before = snapshot()
resetRequests()
run()
if got := requests(); len(got) != 0 {
t.Fatalf("registered launcher output forced an official download: %v", got)
}
assertUnchanged(before)
player := filepath.Join(installed.GameDir, "UnityPlayer.dll")
bundle := filepath.Join(installed.ResourceDir, "ServerData", "StandaloneWindows64", "HD", bundleVersion, "scene.bundle")
for _, path := range []string{player, bundle} {
if err := os.Remove(path); err != nil {
t.Fatal(err)
}
}
resetRequests()
run()
got := requests()
if len(got) == 0 {
t.Fatal("missing resource was not downloaded")
}
for _, path := range got {
if !strings.HasSuffix(path, "/scene.bundle") {
t.Fatalf("repair fetched an already complete file: %s", path)
}
}
if actual, err := os.ReadFile(player); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
t.Fatal("missing game file was not repaired from cached official archive")
}
for _, relative := range prepared {
if actual, err := os.ReadFile(filepath.Join(installed.GameDir, filepath.FromSlash(relative))); err != nil || !bytes.Equal(actual, patched) {
t.Fatal("single-file repair overwrote registered launcher output")
}
}
for _, path := range []string{player, bundle} {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
body[len(body)-1] ^= 1
if err := os.WriteFile(path, body, 0600); err != nil {
t.Fatal(err)
}
stamp := time.Now().Add(2 * time.Second)
if err := os.Chtimes(path, stamp, stamp); err != nil {
t.Fatal(err)
}
}
resetRequests()
run()
got = requests()
if len(got) == 0 {
t.Fatal("same-size damaged resource was trusted")
}
for _, path := range got {
if !strings.HasSuffix(path, "/scene.bundle") {
t.Fatalf("damaged-file repair fetched unaffected content: %s", path)
}
}
if actual, err := os.ReadFile(player); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
t.Fatal("same-size game corruption survived cached installation receipt")
}
if actual, err := os.ReadFile(bundle); err != nil || !bytes.Equal(actual, bundleData) {
t.Fatal("same-size bundle payload corruption survived its valid header")
}
unknown := filepath.Join(installed.GameDir, filepath.FromSlash(prepared[0]))
if err := os.WriteFile(unknown, []byte("unregistered modification"), 0600); err != nil {
t.Fatal(err)
}
resetRequests()
run()
if actual, err := os.ReadFile(unknown); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
t.Fatal("unregistered launcher-file change was silently trusted")
}
if got := requests(); len(got) != 0 {
t.Fatalf("game-file repair unnecessarily contacted the network: %v", got)
}
catalogTarget := filepath.Join(installed.GameDir, filepath.FromSlash(prepared[1]))
if err := os.WriteFile(catalogTarget, []byte("unregistered catalog change"), 0600); err != nil {
t.Fatal(err)
}
if err := RecordPreparedGame(installed.GameDir, prepared[0]); err != nil {
t.Fatal(err)
}
run()
if actual, err := os.ReadFile(catalogTarget); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
t.Fatal("registering one prepared file also trusted another modified file")
}
}
+186
View File
@@ -0,0 +1,186 @@
package download
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
"path/filepath"
"slices"
commonconfig "bd2server/internal/common/config"
)
const gameReceiptName = ".bd2-game-install.json"
type installedFile struct {
SourceBytes uint64 `json:"source_bytes"`
SourceCRC32 uint32 `json:"source_crc32"`
Verified receipt `json:"verified"`
}
type gameInstallation struct {
SchemaVersion int `json:"schema_version"`
ArchiveSHA256 string `json:"archive_sha256"`
Files map[string]installedFile `json:"files"`
}
func readInstallation(root string) (gameInstallation, error) {
return commonconfig.Load(filepath.Join(root, gameReceiptName), gameInstallation{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, RejectNull: true})
}
func fileHashes(path string) (receipt, uint32, error) {
in, err := os.Open(path)
if err != nil {
return receipt{}, 0, err
}
defer func() { _ = in.Close() }()
info, err := in.Stat()
if err != nil {
return receipt{}, 0, err
}
if !info.Mode().IsRegular() {
return receipt{}, 0, errors.New("installed game file is not regular")
}
sha, crc := sha256.New(), crc32.NewIEEE()
n, err := io.Copy(io.MultiWriter(sha, crc), in)
if err != nil {
return receipt{}, 0, err
}
after, err := os.Stat(path)
if err != nil {
return receipt{}, 0, err
}
if n != info.Size() || after.Size() != info.Size() || after.ModTime() != info.ModTime() {
return receipt{}, 0, errors.New("installed game file changed during verification")
}
return receipt{Bytes: n, Modified: after.ModTime().UnixNano(), SHA256: hex.EncodeToString(sha.Sum(nil))}, crc.Sum32(), nil
}
func installedMatches(entry archiveEntry, previous installedFile) (installedFile, bool, error) {
info, err := os.Stat(entry.target)
if errors.Is(err, os.ErrNotExist) {
return installedFile{}, false, nil
}
if err != nil {
return installedFile{}, false, err
}
if !info.Mode().IsRegular() {
return installedFile{}, false, fmt.Errorf("installed game output is not a regular file: %s", entry.target)
}
bound := previous.SourceBytes == entry.file.UncompressedSize64 && previous.SourceCRC32 == entry.file.CRC32 && sha256Pattern.MatchString(previous.Verified.SHA256)
if bound && previous.Verified.Bytes == info.Size() && previous.Verified.Modified == info.ModTime().UnixNano() {
return previous, true, nil
}
verified, crc, err := fileHashes(entry.target)
if err != nil {
return installedFile{}, false, err
}
if bound && verified.SHA256 == previous.Verified.SHA256 || uint64(verified.Bytes) == entry.file.UncompressedSize64 && crc == entry.file.CRC32 {
return installedFile{SourceBytes: entry.file.UncompressedSize64, SourceCRC32: entry.file.CRC32, Verified: verified}, true, nil
}
return installedFile{}, false, nil
}
func extractGame(entries []archiveEntry, root, digest string) error {
previous, err := readInstallation(root)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if previous.SchemaVersion != 1 || previous.ArchiveSHA256 != digest {
previous = gameInstallation{}
}
next := gameInstallation{SchemaVersion: 1, ArchiveSHA256: digest, Files: map[string]installedFile{}}
changed := previous.Files == nil
for _, entry := range entries {
if entry.file.FileInfo().IsDir() {
if err := os.MkdirAll(entry.target, 0755); err != nil {
return err
}
continue
}
relative, err := filepath.Rel(root, entry.target)
if err != nil {
return err
}
relative = filepath.ToSlash(relative)
verified, ready, err := installedMatches(entry, previous.Files[relative])
if err != nil {
return err
}
if !ready {
if err := extractEntry(entry); err != nil {
return fmt.Errorf("extract %s: %w", entry.file.Name, err)
}
verified, ready, err = installedMatches(entry, installedFile{})
if err != nil {
return err
}
if !ready {
return fmt.Errorf("extracted game file failed verification: %s", relative)
}
}
next.Files[relative] = verified
if previous.Files[relative] != verified {
changed = true
}
}
if len(previous.Files) != len(next.Files) {
changed = true
}
if !changed {
return nil
}
return commonconfig.Save(filepath.Join(root, gameReceiptName), next, commonconfig.WriteOptions{FileMode: 0644})
}
func RecordPreparedGame(gameDir string, relativePaths ...string) error {
for _, relative := range relativePaths {
if !slices.Contains([]string{"BrownDust II_Data/resources.assets", "BrownDust II_Data/StreamingAssets/aa/catalog.json"}, relative) {
return fmt.Errorf("cannot register unrecognized prepared game file: %s", relative)
}
}
record, err := readInstallation(gameDir)
if errors.Is(err, os.ErrNotExist) {
return nil
}
if err != nil {
return err
}
if record.SchemaVersion != 1 || record.Files == nil {
return errors.New("unsupported game installation receipt")
}
changed := false
for _, relative := range relativePaths {
entry, ok := record.Files[relative]
if !ok {
return fmt.Errorf("prepared game file is absent from official archive: %s", relative)
}
path, err := safeTarget(gameDir, relative)
if err != nil {
return err
}
info, err := os.Stat(path)
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return fmt.Errorf("prepared game output is not regular: %s", relative)
}
if info.Size() == entry.Verified.Bytes && info.ModTime().UnixNano() == entry.Verified.Modified {
continue
}
entry.Verified, _, err = fileHashes(path)
if err != nil {
return err
}
record.Files[relative] = entry
changed = true
}
if !changed {
return nil
}
return commonconfig.Save(filepath.Join(gameDir, gameReceiptName), record, commonconfig.WriteOptions{FileMode: 0644})
}
+76 -5
View File
@@ -12,7 +12,6 @@ import (
"strconv"
"strings"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
"bd2server/internal/common/resourcecatalog"
)
@@ -23,6 +22,7 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
for _, pin := range m.ResourceFiles {
pins[pin.Path] = pin
}
serverRanked, dataRanked := false, false
receive := func(files []file, origins []string, workers int) error {
if len(pins) != 0 {
for i := range files {
@@ -38,7 +38,39 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
usedPins[pin.Path] = true
}
}
return d.receiveAll(ctx, files, origins, workers)
var missing []file
for _, item := range files {
if !d.verified(item) {
missing = append(missing, item)
}
}
if len(missing) == 0 {
return d.saveRecords()
}
if d.measureOrigins {
if strings.HasPrefix(missing[0].remote, dataPath+"/") {
if !dataRanked {
var err error
dataOrigins, err = d.fastest(ctx, origins, missing[0].remote, "GameData")
if err != nil {
return err
}
dataRanked = true
}
origins = dataOrigins
} else {
if !serverRanked {
var err error
serverOrigins, err = d.fastest(ctx, origins, missing[0].remote, "ServerData")
if err != nil {
return err
}
serverRanked = true
}
origins = serverOrigins
}
}
return d.receiveAll(ctx, missing, origins, workers)
}
serverDir := filepath.Join(root, "ServerData", m.Platform, "HD", m.BundleVersion)
dataDir := filepath.Join(root, "GameData", m.GameDataVersion)
@@ -107,7 +139,7 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
if size != stat.Size() {
return errors.New("GameData size metadata mismatch")
}
entries, err := validateDataArchive(filepath.Join(dataDir, "release", "common-dbdata.bin"))
entries, err := d.dataArchiveEntries(filepath.Join(dataDir, "release", "common-dbdata.bin"))
if err != nil {
return err
}
@@ -144,9 +176,48 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
}
total += info.Size()
}
return commonconfig.Save(filepath.Join(root, "resource-fetch-manifest.json"), map[string]any{
metadata := map[string]any{
"bundle_version": m.BundleVersion, "game_data_version": m.GameDataVersion, "platform": m.Platform,
"server_data": map[string]any{"catalog_hash": strings.ToLower(actualHash), "bundles": len(files), "bytes": total},
"game_data": map[string]any{"version": m.GameDataVersion, "entry_count": entries, "bytes": size},
}, commonconfig.WriteOptions{FileMode: 0644})
}
raw, err = json.MarshalIndent(metadata, "", " ")
if err != nil {
return err
}
raw = append(raw, '\n')
path := filepath.Join(root, "resource-fetch-manifest.json")
if current, err := os.ReadFile(path); err == nil && bytes.Equal(current, raw) {
return nil
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return atomicWrite(path, raw)
}
func (d *downloader) dataArchiveEntries(path string) (int, error) {
d.mu.Lock()
r := d.records[d.receiptKey(path)]
d.mu.Unlock()
info, err := os.Stat(path)
if err != nil {
return 0, err
}
if r.Bytes == info.Size() && r.Modified == info.ModTime().UnixNano() && r.ArchiveEntries > 0 {
return r.ArchiveEntries, nil
}
entries, err := validateDataArchive(path)
if err != nil {
return 0, err
}
after, err := os.Stat(path)
if err != nil {
return 0, err
}
if after.Size() != info.Size() || after.ModTime() != info.ModTime() {
return 0, errors.New("GameData changed during archive validation")
}
r.ArchiveEntries = entries
d.remember(path, r)
return entries, d.saveRecords()
}
+62 -37
View File
@@ -1,6 +1,7 @@
package download
import (
"bd2server/internal/common/util"
"context"
"crypto/sha256"
"encoding/hex"
@@ -26,8 +27,10 @@ type file struct {
}
type receipt struct {
Bytes int64 `json:"bytes"`
SHA256 string `json:"sha256"`
Bytes int64 `json:"bytes"`
Modified int64 `json:"modified"`
SHA256 string `json:"sha256"`
ArchiveEntries int `json:"archive_entries,omitempty"`
}
type downloader struct {
@@ -36,6 +39,8 @@ type downloader struct {
out io.Writer
mu sync.Mutex
records map[string]receipt
dirty bool
measureOrigins bool
}
func newDownloader(root string, out io.Writer) (*downloader, error) {
@@ -52,10 +57,7 @@ func newDownloader(root string, out io.Writer) (*downloader, error) {
return nil, err
}
if err == nil {
if saved.SchemaVersion != 1 {
return nil, errors.New("unsupported download checkpoint")
}
if saved.Files != nil {
if saved.SchemaVersion == 2 && saved.Files != nil {
d.records = saved.Files
}
}
@@ -68,27 +70,11 @@ func (d *downloader) log(format string, args ...any) {
_, _ = fmt.Fprintf(d.out, format+"\n", args...)
}
func hashFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer func() { _ = f.Close() }()
h := sha256.New()
if _, err = io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func (d *downloader) verified(item file) bool {
info, err := os.Stat(item.target)
if err != nil || !info.Mode().IsRegular() || info.Size() == 0 || (item.size > 0 && item.size != info.Size()) {
return false
}
if item.bundle && !validBundle(item.target, info.Size()) {
return false
}
key := d.receiptKey(item.target)
d.mu.Lock()
previous := d.records[key]
@@ -100,8 +86,52 @@ func (d *downloader) verified(item file) bool {
if expected == "" {
return false
}
actual, err := hashFile(item.target)
return err == nil && actual == expected
if previous.Bytes == info.Size() && previous.Modified == info.ModTime().UnixNano() && previous.SHA256 == expected {
return true
}
if item.bundle && !validBundle(item.target, info.Size()) {
return false
}
actual, err := util.SHA256File(item.target)
if err != nil || actual != expected {
return false
}
after, err := os.Stat(item.target)
if err != nil || after.Size() != info.Size() || after.ModTime() != info.ModTime() {
return false
}
entries := 0
if actual == previous.SHA256 {
entries = previous.ArchiveEntries
}
d.remember(item.target, receipt{Bytes: info.Size(), Modified: info.ModTime().UnixNano(), SHA256: actual, ArchiveEntries: entries})
return true
}
func (d *downloader) remember(target string, r receipt) {
d.mu.Lock()
defer d.mu.Unlock()
key := d.receiptKey(target)
if d.records[key] != r {
d.records[key] = r
d.dirty = true
}
}
func (d *downloader) saveRecords() error {
d.mu.Lock()
defer d.mu.Unlock()
if !d.dirty {
return nil
}
err := commonconfig.Save(d.checkpoint, struct {
SchemaVersion int `json:"schema_version"`
Files map[string]receipt `json:"files"`
}{2, d.records}, commonconfig.WriteOptions{FileMode: 0644})
if err == nil {
d.dirty = false
}
return err
}
func (d *downloader) receive(ctx context.Context, item file, origins []string) error {
@@ -171,14 +201,12 @@ func (d *downloader) receiveOnce(ctx context.Context, item file, origin string)
if err := os.Rename(temporary.Name(), item.target); err != nil {
return err
}
key := d.receiptKey(item.target)
d.mu.Lock()
defer d.mu.Unlock()
d.records[key] = receipt{Bytes: written, SHA256: actual}
return commonconfig.Save(d.checkpoint, struct {
SchemaVersion int `json:"schema_version"`
Files map[string]receipt `json:"files"`
}{1, d.records}, commonconfig.WriteOptions{FileMode: 0644})
info, err := os.Stat(item.target)
if err != nil {
return err
}
d.remember(item.target, receipt{Bytes: written, Modified: info.ModTime().UnixNano(), SHA256: actual})
return nil
}
func (d *downloader) receiptKey(target string) string {
@@ -223,10 +251,7 @@ feed:
}
close(jobs)
wg.Wait()
if first != nil {
return first
}
return ctx.Err()
return errors.Join(first, ctx.Err(), d.saveRecords())
}
func (d *downloader) fastest(ctx context.Context, origins []string, relative, label string) ([]string, error) {
@@ -260,7 +285,7 @@ func (d *downloader) fastest(ctx context.Context, origins []string, relative, la
}
n, err := io.Copy(io.Discard, io.LimitReader(response.Body, 4<<20))
speed := float64(0)
if n >= 256<<10 {
if n > 0 {
speed = float64(n) / time.Since(start).Seconds()
}
results[i] = result{origin: origin, speed: speed, err: err}
+5 -20
View File
@@ -1,20 +1,18 @@
package plugin
import (
"bd2server/internal/common/util"
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
commonconfig "bd2server/internal/common/config"
)
type buildManifest struct {
@@ -44,7 +42,7 @@ func (cache fileDigestCache) digest(path string) (string, error) {
return "", err
}
if info.Size() < 1024*1024 {
return fileDigest(path)
return util.SHA256File(path)
}
stamp, reliable := fileChangeStamp(path, info)
if reliable {
@@ -52,7 +50,7 @@ func (cache fileDigestCache) digest(path string) (string, error) {
return previous.Hash, nil
}
}
sum, err := fileDigest(path)
sum, err := util.SHA256File(path)
if err == nil && reliable {
cache[path] = cachedFileDigest{Stamp: stamp, Hash: sum}
}
@@ -108,7 +106,7 @@ func projectFingerprint(root string, inputs map[string]string, project, versionS
}
relevant[file] = sum
}
sum, err := fileDigest(versionSource)
sum, err := util.SHA256File(versionSource)
if err != nil {
return "", err
}
@@ -210,19 +208,6 @@ func writeBuildInput(path, fingerprint string) error {
return os.WriteFile(path, content, 0o644)
}
func fileDigest(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer func() { _ = file.Close() }()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
func currentBuild(path, fingerprint string, cache fileDigestCache) bool {
raw, err := os.ReadFile(path)
if err != nil {
@@ -262,5 +247,5 @@ func saveBuildJSON(path string, raw []byte) error {
if err := temporary.Close(); err != nil {
return err
}
return commonconfig.ReplaceFile(temporary.Name(), path)
return util.ReplaceFile(temporary.Name(), path)
}
+2 -1
View File
@@ -1,6 +1,7 @@
package plugin
import (
"bd2server/internal/common/util"
"bytes"
"context"
"os"
@@ -54,7 +55,7 @@ func TestVerifiedPluginCacheSkipsSDKVersionAndCompilationStages(t *testing.T) {
}
write("plugins/LocalIdentity/bin/Release/netstandard2.1/BD2LocalIdentity.dll", "verified-output")
output := filepath.Join(root, "plugins", "LocalIdentity", "bin", "Release", "netstandard2.1", "BD2LocalIdentity.dll")
digest, err := fileDigest(output)
digest, err := util.SHA256File(output)
if err != nil {
t.Fatal(err)
}
+6 -2
View File
@@ -1,6 +1,7 @@
package plugin
import (
"bd2server/internal/common/util"
"bytes"
"encoding/json"
"errors"
@@ -148,6 +149,9 @@ func InstallSet(gameDir string, sources []string) (SetResult, error) {
dropped = append(dropped, name)
}
}
if len(changed) == 0 && len(dropped) == 0 && slices.Equal(previous, names) {
return result, nil
}
defer func() {
for _, f := range changed {
if f.temporary != "" {
@@ -171,7 +175,7 @@ func InstallSet(gameDir string, sources []string) (SetResult, error) {
var failures []error
for _, f := range slices.Backward(replaced) {
if f.backup != "" {
if err := commonconfig.ReplaceFile(f.backup, f.destination); err != nil {
if err := util.ReplaceFile(f.backup, f.destination); err != nil {
failures = append(failures, fmt.Errorf("restore %s: %w", f.name, err))
}
} else if err := os.Remove(f.destination); err != nil && !errors.Is(err, os.ErrNotExist) {
@@ -199,7 +203,7 @@ func InstallSet(gameDir string, sources []string) (SetResult, error) {
}
replaced = append(replaced, f)
if f.temporary != "" {
if err := commonconfig.ReplaceFile(f.temporary, f.destination); err != nil {
if err := util.ReplaceFile(f.temporary, f.destination); err != nil {
return err
}
f.temporary = ""
+250
View File
@@ -0,0 +1,250 @@
package preparation
import (
"context"
"errors"
"io"
"os"
"path/filepath"
"runtime"
"time"
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/download"
"bd2server/internal/client/layout"
"bd2server/internal/client/setup"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/taskgraph"
"bd2server/internal/common/versionconfig"
)
type Options struct {
PackageDirectory, DownloadManifest, VersionConfig string
GameDirectory, ResourceDirectory string
Settings clientconfig.Settings
Versions versionconfig.Config
Workers int
DownloadOnly, BaseOnly, ProbeOnly, PlanOnly bool
DownloadIfMissing bool
LocalIdentityPlugin, LoginUIPlugin string
CashShopPlugin, FChatPlugin string
PrepareGame func(context.Context, string, clientconfig.Settings) (versionconfig.Config, error)
SavePreferences func(string) error
}
type Result struct {
GameDirectory, ResourceDirectory string
Settings clientconfig.Settings
Versions versionconfig.Config
Status setup.GameStatus
Plan []string
}
func Run(ctx context.Context, options Options, out io.Writer) (Result, error) {
var result Result
if options.Workers < 1 || options.Workers > 16 {
return result, errors.New("prepare workers must be 1-16")
}
if options.DownloadOnly && options.BaseOnly {
return result, errors.New("--download and --base select separate stages; omit both to run all stages")
}
if options.BaseOnly && options.ProbeOnly {
return result, errors.New("--probe-only cannot be used with --base")
}
if options.PackageDirectory == "" {
executable, err := os.Executable()
if err != nil {
return result, err
}
options.PackageDirectory = filepath.Dir(executable)
}
directory, err := filepath.Abs(options.PackageDirectory)
if err != nil {
return result, err
}
if out == nil {
out = io.Discard
}
result.GameDirectory, result.ResourceDirectory = options.GameDirectory, options.ResourceDirectory
if result.GameDirectory == "" {
result.GameDirectory = filepath.Join(directory, "game")
}
if result.ResourceDirectory == "" {
result.ResourceDirectory = options.Settings.LocalResourceDirectory
}
if result.ResourceDirectory == "" {
result.ResourceDirectory = filepath.Join(directory, "resources")
}
result.Settings, result.Versions = options.Settings, options.Versions
var downloaded versionconfig.Config
didDownload := false
graph, err := taskgraph.New(
taskgraph.Task{Name: "download", Run: func(ctx context.Context) error {
if options.DownloadIfMissing && !options.ProbeOnly {
if installation, err := layout.Resolve(result.GameDirectory); err == nil &&
(result.Settings.CDNMode != clientconfig.CDNLocal || installation.Kind == layout.MacOS) {
result.GameDirectory = installation.Root
return nil
}
if runtime.GOOS != "windows" {
return errors.New("automatic game installation is available only on Windows; select an installed game")
}
}
installed, err := download.Client(ctx, download.Options{
PackageDir: directory, Manifest: options.DownloadManifest,
GameDir: result.GameDirectory, ResourceDir: result.ResourceDirectory, ServerOrigin: result.Settings.ServerOrigin,
Workers: options.Workers, ProbeOnly: options.ProbeOnly,
}, out)
if err != nil {
return err
}
result.GameDirectory, result.ResourceDirectory = installed.GameDir, installed.ResourceDir
result.Settings.ServerOrigin = installed.ServerOrigin
downloaded, didDownload = installed.Versions, true
if options.DownloadOnly || options.ProbeOnly {
result.Versions = installed.Versions
}
return nil
}},
taskgraph.Task{Name: "base:configuration", Run: func(context.Context) error {
if result.Settings.ServerOrigin == "" {
manifest := options.DownloadManifest
if manifest == "" {
manifest = filepath.Join(directory, "client-download.json")
}
defaults, err := commonconfig.Load(manifest, struct {
ServerOrigin string `json:"server_origin"`
}{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true})
if err != nil {
return err
}
result.Settings.ServerOrigin = defaults.ServerOrigin
}
if result.Versions.GameVersion == "" {
path := options.VersionConfig
if path == "" {
path = filepath.Join(directory, versionconfig.FileName)
}
var err error
result.Versions, err = versionconfig.Load(path)
if err != nil {
return err
}
}
if didDownload && (result.Versions.GameVersion != downloaded.GameVersion || result.Versions.GameDataVersion != downloaded.GameDataVersion || result.Versions.BundleVersion != downloaded.BundleVersion) {
return errors.New("client package and download manifest versions differ")
}
return nil
}},
taskgraph.Task{Name: "base:settings", DependsOn: []string{"base:configuration"}, Run: func(context.Context) error {
if result.Settings.CDNMode == clientconfig.CDNLocal && result.Settings.LocalResourceDirectory == "" {
result.Settings.LocalResourceDirectory = result.ResourceDirectory
}
var err error
result.Settings, err = clientconfig.Normalize(result.Settings)
return err
}},
taskgraph.Task{Name: "base:update", DependsOn: []string{"base:settings"}, Run: func(ctx context.Context) error {
if options.PrepareGame == nil {
return nil
}
if saved, err := clientconfig.Load(result.GameDirectory); err == nil {
result.Settings.Runtime = saved.Runtime
} else if !errors.Is(err, os.ErrNotExist) {
return err
}
if _, err := clientconfig.Save(result.GameDirectory, result.Settings); err != nil {
return err
}
versions, err := options.PrepareGame(ctx, result.GameDirectory, result.Settings)
if err != nil {
return err
}
result.Versions = versions
saved, err := clientconfig.Load(result.GameDirectory)
if err != nil {
return err
}
result.Settings.Runtime = saved.Runtime
return nil
}},
taskgraph.Task{Name: "base:resources", DependsOn: []string{"base:update"}, Run: func(ctx context.Context) error {
policyContext, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
_, err := setup.FetchResourcePolicy(policyContext, nil, result.Settings, result.Versions)
return err
}},
taskgraph.Task{Name: "base:bepinex", DependsOn: []string{"base:resources"}, Run: func(context.Context) error {
installation, err := layout.Resolve(result.GameDirectory)
if err != nil {
return err
}
complete := regularFile(filepath.Join(installation.BepInEx, "core", "BepInEx.dll"))
if installation.Kind == layout.Windows {
complete = complete && regularFile(filepath.Join(installation.Root, "winhttp.dll")) && regularFile(filepath.Join(installation.Root, "doorstop_config.ini"))
}
if complete {
return nil
}
if installation.Kind != layout.Windows {
return errors.New("install BepInEx for the selected macOS game before preparing the client")
}
return download.InstallBepInEx(directory, installation.Root)
}},
taskgraph.Task{Name: "base:patch", DependsOn: []string{"base:bepinex"}, Run: func(context.Context) error {
if _, err := setup.SaveSettings(result.GameDirectory, result.Settings); err != nil {
return err
}
if result.Settings.CDNMode == clientconfig.CDNLocal {
if err := setup.InstallLocalCatalog(result.GameDirectory, result.Settings.LocalResourceDirectory, result.Versions.BundleVersion); err != nil {
return err
}
}
_, err := setup.Patch(result.GameDirectory)
return err
}},
taskgraph.Task{Name: "base:plugins", DependsOn: []string{"base:patch"}, Run: func(context.Context) error {
sources := []*string{&options.LocalIdentityPlugin, &options.LoginUIPlugin, &options.CashShopPlugin, &options.FChatPlugin}
for n, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll", "BD2FChat.dll"} {
if *sources[n] == "" {
*sources[n] = filepath.Join(directory, "plugins", name)
}
}
_, err := setup.InstallPlugins(result.GameDirectory, options.LocalIdentityPlugin, options.LoginUIPlugin, options.CashShopPlugin, options.FChatPlugin)
return err
}},
taskgraph.Task{Name: "base:preferences", DependsOn: []string{"base:plugins"}, Run: func(context.Context) error {
save := options.SavePreferences
if save == nil {
save = clientconfig.SavePreferences
}
return save(result.GameDirectory)
}},
taskgraph.Task{Name: "base", DependsOn: []string{"base:preferences"}, Run: func(context.Context) error {
var err error
result.Status, err = setup.Inspect(result.GameDirectory, result.Versions)
return err
}},
taskgraph.Task{Name: "prepare", DependsOn: []string{"download", "base"}},
)
if err != nil {
return result, err
}
target := "prepare"
if options.DownloadOnly || options.ProbeOnly {
target = "download"
} else if options.BaseOnly {
target = "base"
}
result.Plan, err = graph.Plan(target)
if err != nil || options.PlanOnly {
return result, err
}
err = graph.Run(ctx, target)
return result, err
}
func regularFile(path string) bool {
info, err := os.Stat(path)
return err == nil && info.Mode().IsRegular()
}
+107
View File
@@ -0,0 +1,107 @@
package setup
import (
"fmt"
"os"
"path/filepath"
"strings"
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/resourcecatalog"
)
const localCatalogReceipt = ".bd2-local-catalog.json"
type catalogFile struct {
Path string `json:"path"`
Size int64 `json:"size"`
Modified int64 `json:"modified"`
}
type catalogReceipt struct {
Schema int `json:"schema"`
Release string `json:"release"`
Cache string `json:"cache"`
Files []catalogFile `json:"files"`
}
func catalogStamp(path string) (catalogFile, error) {
info, err := os.Stat(path)
if err != nil {
return catalogFile{}, err
}
if !info.Mode().IsRegular() {
return catalogFile{}, fmt.Errorf("local catalog requires a regular file: %s", path)
}
return catalogFile{Path: path, Size: info.Size(), Modified: info.ModTime().UnixNano()}, nil
}
func catalogStateFiles(release, aa, cache string) []string {
return []string{
filepath.Join(release, "catalog_alpha.json"), filepath.Join(release, "catalog_alpha.hash"),
filepath.Join(aa, "catalog.json"), filepath.Join(aa, localBundleManifest),
filepath.Join(cache, "catalog_alpha.json"), filepath.Join(cache, "catalog_alpha.hash"),
}
}
func localCatalogCurrent(release, aa, cache string) bool {
receipt, err := commonconfig.Load(filepath.Join(aa, localCatalogReceipt), catalogReceipt{}, commonconfig.DecodeOptions{RejectTrailing: true})
paths := catalogStateFiles(release, aa, cache)
if err != nil || receipt.Schema != 1 || receipt.Release != release || receipt.Cache != cache || len(receipt.Files) < len(paths) {
return false
}
for i, file := range receipt.Files {
if i < len(paths) && file.Path != paths[i] {
return false
}
current, err := catalogStamp(file.Path)
if err != nil || current != file {
return false
}
}
managed, err := managedCatalogBundles(aa)
if err != nil || len(managed) == 0 {
return false
}
for relative, record := range managed {
for _, file := range []catalogFile{
{Path: filepath.Join(release, filepath.FromSlash(relative)), Size: record.SourceSize, Modified: record.SourceModified},
{Path: filepath.Join(aa, filepath.FromSlash(relative)), Size: record.TargetSize, Modified: record.TargetModified},
} {
current, err := catalogStamp(file.Path)
if err != nil || current != file {
return false
}
}
}
return true
}
func recordLocalCatalog(release, aa, cache string, raw []byte) error {
managed, err := managedCatalogBundles(aa)
if err != nil {
return err
}
_, ids, err := resourcecatalog.Decode(raw)
if err != nil {
return err
}
paths := catalogStateFiles(release, aa, cache)
for _, id := range ids {
if relative, ok := strings.CutPrefix(id, localCatalogPrefix); ok {
relative = strings.ReplaceAll(relative, "\\", "/")
if _, exists := managed[relative]; !exists {
paths = append(paths, filepath.Join(aa, filepath.FromSlash(relative)))
}
}
}
receipt := catalogReceipt{Schema: 1, Release: release, Cache: cache}
for _, path := range paths {
file, err := catalogStamp(path)
if err != nil {
return err
}
receipt.Files = append(receipt.Files, file)
}
return commonconfig.Save(filepath.Join(aa, localCatalogReceipt), receipt, commonconfig.WriteOptions{})
}
+176 -31
View File
@@ -9,10 +9,13 @@ import (
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"bd2server/internal/client/download"
clientlayout "bd2server/internal/client/layout"
"bd2server/internal/common/resourcecatalog"
"bd2server/internal/common/util"
)
const (
@@ -28,30 +31,63 @@ func InstallLocalCatalog(gameDir, localRoot, bundleVersion string) error {
return err
}
release := filepath.Join(filepath.Clean(localRoot), "ServerData", "StandaloneWindows64", "HD", bundleVersion)
source := filepath.Join(release, "catalog_alpha.json")
sourceHash := filepath.Join(release, "catalog_alpha.hash")
raw, err := readCatalog(source)
aa := filepath.Join(installation.Data, "StreamingAssets", "aa")
cache, err := addressablesCacheDirectory(installation)
if err != nil {
return err
}
aa := filepath.Join(installation.Data, "StreamingAssets", "aa")
if err := separateCatalogDirectories(release, aa, cache); err != nil {
return err
}
for _, entry := range []struct{ root, relative string }{
{release, "catalog_alpha.json"}, {release, "catalog_alpha.hash"},
{aa, "catalog.json"}, {aa, localCatalogBackup}, {aa, localBundleManifest}, {aa, localCatalogReceipt},
{cache, "catalog_alpha.json"}, {cache, "catalog_alpha.hash"},
} {
if _, err := catalogFilePath(entry.root, entry.relative); err != nil {
return err
}
}
managed, err := managedCatalogBundles(aa)
if err != nil {
return err
}
for relative := range managed {
for _, root := range []string{release, aa} {
if _, err := catalogFilePath(root, relative); err != nil {
return err
}
}
}
if localCatalogCurrent(release, aa, cache) {
return nil
}
source := filepath.Join(release, "catalog_alpha.json")
sourceHash := filepath.Join(release, "catalog_alpha.hash")
raw, err := readCatalog(source)
if err != nil {
return err
}
paths, err := resourcecatalog.BundlePaths(raw)
if err != nil {
return err
}
raw, err = localizeCatalog(raw, release, aa, managed)
if err != nil {
return err
}
target := filepath.Join(aa, "catalog.json")
current, err := os.ReadFile(target)
if err != nil {
return fmt.Errorf("read built-in Addressables catalog: %w", err)
}
hash, err := os.ReadFile(sourceHash)
if err != nil {
return fmt.Errorf("read local ServerData catalog hash: %w", err)
}
if len(hash) == 0 || len(hash) > 1024 {
return errors.New("local ServerData catalog hash has an invalid size")
}
raw, err = localizeCatalog(raw, release, aa, managed)
if err != nil {
return err
}
if !bytes.Equal(current, raw) {
backup := filepath.Join(aa, localCatalogBackup)
if _, err := os.Stat(backup); errors.Is(err, os.ErrNotExist) {
@@ -81,21 +117,18 @@ func InstallLocalCatalog(gameDir, localRoot, bundleVersion string) error {
if err != nil {
return err
}
if err := synchronizePersistentCatalog(cache, raw, hash); err != nil {
return err
}
if installation.Kind == clientlayout.Windows {
if err := download.RecordPreparedGame(gameDir, "BrownDust II_Data/StreamingAssets/aa/catalog.json"); err != nil {
return err
}
}
if err := replaceCatalog(filepath.Join(aa, localBundleManifest), managedRaw); err != nil {
return fmt.Errorf("record managed Addressables bundles: %w", err)
}
hash, err := os.ReadFile(sourceHash)
if err != nil {
return fmt.Errorf("read local ServerData catalog hash: %w", err)
}
if len(hash) == 0 || len(hash) > 1024 {
return errors.New("local ServerData catalog hash has an invalid size")
}
cache, err := addressablesCacheDirectory(installation)
if err != nil {
return err
}
return synchronizePersistentCatalog(cache, raw, hash)
return recordLocalCatalog(release, aa, cache, raw)
}
func addressablesCacheDirectory(installation clientlayout.Installation) (string, error) {
@@ -222,24 +255,38 @@ func localizeCatalog(raw []byte, release, aa string, managed map[string]managedB
return nil, err
}
remoteCount := 0
type bundleLink struct{ source, destination, relative string }
var links []bundleLink
for index, internalID := range ids {
if strings.HasPrefix(internalID, resourcecatalog.RemotePrefix) {
relative, err := resourcecatalog.BundlePath(internalID)
if err != nil {
return nil, err
}
source := filepath.Join(release, filepath.FromSlash(relative))
destination := filepath.Join(aa, filepath.FromSlash(relative))
if err := ensureCatalogBundleLink(source, destination, managed[relative]); err != nil {
source, err := catalogFilePath(release, relative)
if err != nil {
return nil, err
}
info, err := os.Stat(source)
if err != nil || !info.Mode().IsRegular() {
return nil, fmt.Errorf("local ServerData catalog references a missing bundle: %s", source)
}
destination, err := catalogFilePath(aa, relative)
if err != nil {
return nil, err
}
links = append(links, bundleLink{source, destination, relative})
ids[index] = localCatalogPrefix + strings.ReplaceAll(filepath.ToSlash(relative), "/", "\\")
remoteCount++
continue
}
if relative, ok := strings.CutPrefix(internalID, localCatalogPrefix); ok {
relative = filepath.FromSlash(strings.ReplaceAll(relative, "\\", "/"))
if info, err := os.Stat(filepath.Join(aa, relative)); err != nil || !info.Mode().IsRegular() {
relative = strings.ReplaceAll(relative, "\\", "/")
path, err := catalogFilePath(aa, relative)
if err != nil {
return nil, err
}
if info, err := os.Stat(path); err != nil || !info.Mode().IsRegular() {
return nil, fmt.Errorf("built-in Addressables catalog references a missing local bundle: %s", relative)
}
}
@@ -256,6 +303,11 @@ func localizeCatalog(raw []byte, release, aa string, managed map[string]managedB
if err != nil {
return nil, fmt.Errorf("encode localized ServerData catalog: %w", err)
}
for _, link := range links {
if err := ensureCatalogBundleLink(link.source, link.destination, managed[link.relative]); err != nil {
return nil, err
}
}
return localized, nil
}
@@ -264,19 +316,29 @@ func ensureCatalogBundleLink(source, destination string, managed managedBundle)
if err != nil || !sourceInfo.Mode().IsRegular() {
return fmt.Errorf("local ServerData catalog references a missing bundle: %s", source)
}
if destinationInfo, err := os.Stat(destination); err == nil {
if destinationInfo, err := os.Lstat(destination); err == nil {
if !destinationInfo.Mode().IsRegular() {
return fmt.Errorf("game Addressables bundle conflicts with the selected local release: %s", destination)
}
if os.SameFile(sourceInfo, destinationInfo) {
return nil
}
if managed.Path == "" {
return fmt.Errorf("game Addressables bundle conflicts with the selected local release: %s", destination)
}
if sourceInfo.Size() == managed.SourceSize && sourceInfo.ModTime().UnixNano() == managed.SourceModified && destinationInfo.Size() == managed.TargetSize && destinationInfo.ModTime().UnixNano() == managed.TargetModified {
if managed.Path != "" && sourceInfo.Size() == managed.SourceSize && sourceInfo.ModTime().UnixNano() == managed.SourceModified && destinationInfo.Size() == managed.TargetSize && destinationInfo.ModTime().UnixNano() == managed.TargetModified {
return nil
}
if sourceInfo.Size() == destinationInfo.Size() {
sourceHash, err := util.SHA256File(source)
if err != nil {
return err
}
targetHash, err := util.SHA256File(destination)
if err != nil {
return err
}
if sourceHash == targetHash {
return nil
}
}
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect game Addressables bundle: %w", err)
}
@@ -314,7 +376,85 @@ func ensureCatalogBundleLink(source, destination string, managed managedBundle)
return errors.New("incomplete local Addressables bundle copy")
}
}
return os.Rename(path, destination)
return util.ReplaceFile(path, destination)
}
func catalogFilePath(root, relative string) (string, error) {
root, err := filepath.Abs(root)
if err != nil {
return "", err
}
if !filepath.IsLocal(filepath.FromSlash(relative)) {
return "", errors.New("catalog file path must be relative to its directory")
}
target := filepath.Join(root, filepath.FromSlash(relative))
rel, err := filepath.Rel(root, target)
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", errors.New("catalog file escapes its directory")
}
for path := target; ; path = filepath.Dir(path) {
info, err := os.Lstat(path)
if err == nil {
if info.Mode()&os.ModeSymlink != 0 {
return "", fmt.Errorf("catalog path contains a symbolic link: %s", path)
}
if path == target && !info.Mode().IsRegular() || path != target && !info.IsDir() {
return "", fmt.Errorf("catalog path conflicts with a non-regular file or directory: %s", path)
}
} else if !errors.Is(err, os.ErrNotExist) {
return "", err
}
if path == root {
break
}
}
return target, nil
}
func resolvedCatalogPath(path string) (string, error) {
path, err := filepath.Abs(path)
if err != nil {
return "", err
}
var suffix []string
for {
resolved, err := filepath.EvalSymlinks(path)
if err == nil {
for _, part := range slices.Backward(suffix) {
resolved = filepath.Join(resolved, part)
}
return resolved, nil
}
if !errors.Is(err, os.ErrNotExist) {
return "", err
}
parent := filepath.Dir(path)
if parent == path {
return "", err
}
suffix = append(suffix, filepath.Base(path))
path = parent
}
}
func separateCatalogDirectories(release string, outputs ...string) error {
source, err := resolvedCatalogPath(release)
if err != nil {
return err
}
for _, output := range outputs {
target, err := resolvedCatalogPath(output)
if err != nil {
return err
}
for _, pair := range [][2]string{{source, target}, {target, source}} {
rel, err := filepath.Rel(pair[0], pair[1])
if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return errors.New("local resource source and game output directories must not overlap")
}
}
}
return nil
}
func writeExclusiveFile(path string, data []byte, mode os.FileMode) error {
@@ -332,6 +472,11 @@ func writeExclusiveFile(path string, data []byte, mode os.FileMode) error {
}
func replaceCatalog(path string, data []byte) error {
if current, err := os.ReadFile(path); err == nil && bytes.Equal(current, data) {
return nil
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
temporary, err := os.CreateTemp(filepath.Dir(path), ".catalog-local-*.json")
if err != nil {
return err
@@ -1,6 +1,8 @@
package setup
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"runtime"
@@ -9,6 +11,211 @@ import (
"time"
)
type catalogScenario struct{ game, resources, aa, release string }
func newCatalogScenario(t *testing.T, remote ...string) catalogScenario {
t.Helper()
root := t.TempDir()
s := catalogScenario{game: filepath.Join(root, "instance", "game"), resources: filepath.Join(root, "resources")}
s.aa = filepath.Join(s.game, "BrownDust II_Data", "StreamingAssets", "aa")
s.release = filepath.Join(s.resources, "ServerData", "StandaloneWindows64", "HD", "20261007175947")
s.write(t, filepath.Join(s.game, "BrownDust II.exe"), "game")
s.write(t, filepath.Join(s.game, "BrownDust II_Data", "resources.assets"), "assets")
s.write(t, filepath.Join(root, "instance", "instance.json"), `{"schema_version":1,"id":"instance"}`)
s.write(t, filepath.Join(s.aa, "catalog.json"), `{"m_InternalIds":["{UnityEngine.AddressableAssets.Addressables.RuntimePath}\\builtin.bundle"]}`)
s.write(t, filepath.Join(s.aa, "builtin.bundle"), "builtin bytes")
ids := []string{localCatalogPrefix + "builtin.bundle"}
for _, relative := range remote {
ids = append(ids, "{BDNetwork.CdnInfo.Info}/StandaloneWindows64/HD/20261007175947/"+relative)
}
raw, err := json.Marshal(map[string]any{"m_InternalIds": ids})
if err != nil {
t.Fatal(err)
}
s.write(t, filepath.Join(s.release, "catalog_alpha.json"), string(raw))
s.write(t, filepath.Join(s.release, "catalog_alpha.hash"), "0f90a94601be05737f86a4ec7a1c889f")
return s
}
func (s catalogScenario) write(t *testing.T, path, value string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(value), 0600); err != nil {
t.Fatal(err)
}
}
func (s catalogScenario) install() error {
return InstallLocalCatalog(s.game, s.resources, "20261007175947")
}
func catalogTree(t *testing.T, root string) map[string][]byte {
t.Helper()
files := map[string][]byte{}
if err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return nil
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
relative, err := filepath.Rel(root, path)
if err != nil {
return err
}
files[relative] = data
return nil
}); err != nil {
t.Fatal(err)
}
return files
}
func assertCatalogTree(t *testing.T, root string, before map[string][]byte) {
t.Helper()
after := catalogTree(t, root)
if len(after) != len(before) {
t.Fatalf("rejected synchronization changed file count: %d -> %d", len(before), len(after))
}
for path, data := range before {
if !bytes.Equal(data, after[path]) {
t.Fatalf("rejected synchronization changed %s", path)
}
}
}
func TestIncompleteCatalogDoesNotPartiallyInstallAndRetryAdoptsCopiedBundle(t *testing.T) {
s := newCatalogScenario(t, "a-first.bundle", "z-missing.bundle")
s.write(t, filepath.Join(s.release, "a-first.bundle"), "current first")
s.write(t, filepath.Join(s.aa, "a-first.bundle"), "existing first")
before := catalogTree(t, s.game)
if err := s.install(); err == nil {
t.Fatal("incomplete source catalog was installed")
}
assertCatalogTree(t, s.game, before)
s.write(t, filepath.Join(s.release, "z-missing.bundle"), "last bundle")
s.write(t, filepath.Join(s.aa, "a-first.bundle"), "current first")
partial, err := os.Stat(filepath.Join(s.aa, "a-first.bundle"))
if err != nil {
t.Fatal(err)
}
source, err := os.Stat(filepath.Join(s.release, "a-first.bundle"))
if err != nil {
t.Fatal(err)
}
if os.SameFile(partial, source) {
t.Fatal("partial-install scenario must exercise an independent copy")
}
if err := s.install(); err != nil {
t.Fatalf("retry rejected an unrecorded completed copy: %v", err)
}
after, err := os.Stat(filepath.Join(s.aa, "a-first.bundle"))
if err != nil || !os.SameFile(partial, after) || !partial.ModTime().Equal(after.ModTime()) {
t.Fatal("retry unnecessarily replaced the matching partial copy")
}
if actual, err := os.ReadFile(filepath.Join(s.aa, "z-missing.bundle")); err != nil || string(actual) != "last bundle" {
t.Fatal("retry did not finish the remaining bundle")
}
if actual, err := os.ReadFile(filepath.Join(s.aa, "builtin.bundle")); err != nil || string(actual) != "builtin bytes" {
t.Fatal("retry changed an unrelated built-in bundle")
}
if _, err := os.Stat(filepath.Join(s.aa, localBundleManifest)); err != nil {
t.Fatal("completed retry did not publish its managed bundle record")
}
}
func TestAuthoritativeRemoteBundleReplacesUnrecordedOldContent(t *testing.T) {
s := newCatalogScenario(t, "scene.bundle")
s.write(t, filepath.Join(s.release, "scene.bundle"), "current release")
s.write(t, filepath.Join(s.aa, "scene.bundle"), "previous release")
if err := s.install(); err != nil {
t.Fatal(err)
}
if actual, err := os.ReadFile(filepath.Join(s.aa, "scene.bundle")); err != nil || string(actual) != "current release" {
t.Fatal("remote catalog entry kept unrecorded outdated content")
}
if actual, err := os.ReadFile(filepath.Join(s.aa, "builtin.bundle")); err != nil || string(actual) != "builtin bytes" {
t.Fatal("remote synchronization modified unrelated builtin content")
}
if actual, err := os.ReadFile(filepath.Join(s.release, "scene.bundle")); err != nil || string(actual) != "current release" {
t.Fatal("synchronization modified the source resource")
}
}
func TestCatalogRejectsSourceOutputAliasAndDirectoryConflictsBeforeCopy(t *testing.T) {
t.Run("game output nested inside source", func(t *testing.T) {
s := newCatalogScenario(t, "scene.bundle")
oldGame := s.game
s.game = filepath.Join(s.release, "instance", "game")
s.aa = filepath.Join(s.game, "BrownDust II_Data", "StreamingAssets", "aa")
for relative, data := range catalogTree(t, oldGame) {
s.write(t, filepath.Join(s.game, relative), string(data))
}
s.write(t, filepath.Join(s.release, "instance", "instance.json"), `{"schema_version":1,"id":"instance"}`)
s.write(t, filepath.Join(s.release, "scene.bundle"), "source must survive")
before := catalogTree(t, s.release)
if err := s.install(); err == nil {
t.Fatal("game output nested inside resource input was accepted")
}
assertCatalogTree(t, s.release, before)
})
t.Run("source aliases game output", func(t *testing.T) {
s := newCatalogScenario(t, "scene.bundle")
for _, name := range []string{"catalog_alpha.json", "catalog_alpha.hash"} {
data, err := os.ReadFile(filepath.Join(s.release, name))
if err != nil {
t.Fatal(err)
}
s.write(t, filepath.Join(s.aa, name), string(data))
}
s.write(t, filepath.Join(s.aa, "scene.bundle"), "aliased source")
if err := os.RemoveAll(s.release); err != nil {
t.Fatal(err)
}
if err := os.Symlink(s.aa, s.release); err != nil {
t.Skipf("symbolic links unavailable: %v", err)
}
before := catalogTree(t, s.aa)
if err := s.install(); err == nil {
t.Fatal("source/output directory alias was accepted")
}
assertCatalogTree(t, s.aa, before)
})
t.Run("target directory", func(t *testing.T) {
s := newCatalogScenario(t, "a-first.bundle", "z-conflict.bundle")
s.write(t, filepath.Join(s.release, "a-first.bundle"), "first")
s.write(t, filepath.Join(s.release, "z-conflict.bundle"), "last")
if err := os.Mkdir(filepath.Join(s.aa, "z-conflict.bundle"), 0700); err != nil {
t.Fatal(err)
}
before := catalogTree(t, s.game)
if err := s.install(); err == nil {
t.Fatal("bundle target directory was overwritten")
}
assertCatalogTree(t, s.game, before)
})
t.Run("target symbolic link", func(t *testing.T) {
s := newCatalogScenario(t, "scene.bundle")
s.write(t, filepath.Join(s.release, "scene.bundle"), "release bytes")
other := filepath.Join(t.TempDir(), "outside.bundle")
s.write(t, other, "keep outside")
if err := os.Symlink(other, filepath.Join(s.aa, "scene.bundle")); err != nil {
t.Skipf("symbolic links unavailable: %v", err)
}
if err := s.install(); err == nil {
t.Fatal("bundle target symbolic link was accepted")
}
if actual, err := os.ReadFile(other); err != nil || string(actual) != "keep outside" {
t.Fatal("target alias modified an unrelated file")
}
if _, err := os.Stat(filepath.Join(s.aa, localBundleManifest)); !os.IsNotExist(err) {
t.Fatal("rejected alias published a managed manifest")
}
})
}
func TestLocalCatalogRefreshReplacesManagedBundlesAndPreservesBuiltins(t *testing.T) {
root := t.TempDir()
resources := t.TempDir()
@@ -91,4 +298,48 @@ func TestLocalCatalogRefreshReplacesManagedBundlesAndPreservesBuiltins(t *testin
if !os.SameFile(installed, unchanged) {
t.Fatal("unchanged cached resource was unnecessarily replaced")
}
cache := filepath.Join(root, "instance", "unity", "persistent", "com.unity.addressables")
stable := map[string]os.FileInfo{}
for _, path := range []string{filepath.Join(aa, "catalog.json"), filepath.Join(aa, localBundleManifest), filepath.Join(cache, "catalog_alpha.json"), filepath.Join(cache, "catalog_alpha.hash")} {
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
stable[path] = info
}
if err := InstallLocalCatalog(game, resources, version); err != nil {
t.Fatal(err)
}
for path, previous := range stable {
current, err := os.Stat(path)
if err != nil || !os.SameFile(previous, current) || !previous.ModTime().Equal(current.ModTime()) {
t.Fatalf("unchanged preparation rewrote %s: %v", path, err)
}
}
if err := os.Remove(streamed); err != nil {
t.Fatal(err)
}
if err := InstallLocalCatalog(game, resources, version); err != nil {
t.Fatal(err)
}
if actual, err := os.ReadFile(streamed); err != nil || string(actual) != "new bytes" {
t.Fatalf("cached preparation did not restore the missing current bundle: %q, %v", actual, err)
}
persistentCatalog := filepath.Join(cache, "catalog_alpha.json")
if err := os.Remove(persistentCatalog); err != nil {
t.Fatal(err)
}
if err := InstallLocalCatalog(game, resources, version); err != nil {
t.Fatal(err)
}
gameCatalog, err := os.ReadFile(filepath.Join(aa, "catalog.json"))
if err != nil {
t.Fatal(err)
}
if actual, err := os.ReadFile(persistentCatalog); err != nil || string(actual) != string(gameCatalog) {
t.Fatalf("cached preparation did not restore the persistent catalog: %v", err)
}
if actual, err := os.ReadFile(filepath.Join(aa, "builtin.bundle")); err != nil || string(actual) != "keep builtin" {
t.Fatalf("repair modified the unrelated built-in bundle: %q, %v", actual, err)
}
}
+40
View File
@@ -0,0 +1,40 @@
package setup
import (
"os"
"path/filepath"
"testing"
clientconfig "bd2server/internal/client/config"
)
func TestSaveLocalSettingsBeforeGameAndResourcesAreInstalled(t *testing.T) {
root := t.TempDir()
game, resources := filepath.Join(root, "game"), filepath.Join(root, "resources")
input := clientconfig.Settings{ServerOrigin: "https://play.example.com", CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: resources}
if _, err := SaveSettings(game, input); err != nil {
t.Fatal("saving an installation location depended on game or resource preparation", err)
}
saved, err := clientconfig.Load(game)
if err != nil || saved.ServerOrigin != input.ServerOrigin || saved.CDNMode != input.CDNMode || saved.LocalResourceDirectory != resources {
t.Fatalf("saved settings could not be restored for preparation: %+v, %v", saved, err)
}
if _, err := os.Stat(resources); !os.IsNotExist(err) {
t.Fatal("saving settings tried to create the resource installation", err)
}
if _, err := os.Stat(filepath.Join(game, "BrownDust II_Data")); !os.IsNotExist(err) {
t.Fatal("saving settings tried to prepare the game", err)
}
configPath := clientconfig.Path(game)
before, err := os.Stat(configPath)
if err != nil {
t.Fatal(err)
}
if _, err := SaveSettings(game, input); err != nil {
t.Fatal(err)
}
after, err := os.Stat(configPath)
if err != nil || !os.SameFile(before, after) || !before.ModTime().Equal(after.ModTime()) {
t.Fatal("saving unchanged settings rewrote the configuration", err)
}
}
+18 -24
View File
@@ -20,6 +20,7 @@ import (
"time"
clientconfig "bd2server/internal/client/config"
"bd2server/internal/client/download"
"bd2server/internal/client/introdb"
clientlayout "bd2server/internal/client/layout"
"bd2server/internal/client/plugin"
@@ -52,6 +53,10 @@ type ResourcePolicy struct {
type InstallResult = plugin.SetResult
func Inspect(gameDir string, versions versionconfig.Config) (GameStatus, error) {
return inspect(gameDir, versions, true)
}
func inspect(gameDir string, versions versionconfig.Config, verifyPatch bool) (GameStatus, error) {
if strings.TrimSpace(gameDir) == "" {
return GameStatus{}, errors.New("select the Brown Dust II installation directory")
}
@@ -71,15 +76,17 @@ func Inspect(gameDir string, versions versionconfig.Config) (GameStatus, error)
if status.ClientVersion != versions.GameVersion {
return status, fmt.Errorf("unsupported Brown Dust II client version %s; this bd2client release requires %s", status.ClientVersion, versions.GameVersion)
}
if verified, verifyErr := introdb.VerifyClient(installation.Root); verifyErr == nil {
status.PatchedURL = verified.URL
if verifyPatch {
if verified, verifyErr := introdb.VerifyClient(installation.Root); verifyErr == nil {
status.PatchedURL = verified.URL
}
}
return status, nil
}
func SaveSettings(gameDir string, settings clientconfig.Settings, versions versionconfig.Config) (clientconfig.Settings, error) {
if _, err := Inspect(gameDir, versions); err != nil {
return clientconfig.Settings{}, err
func SaveSettings(gameDir string, settings clientconfig.Settings) (clientconfig.Settings, error) {
if strings.TrimSpace(gameDir) == "" {
return clientconfig.Settings{}, errors.New("select the Brown Dust II installation directory")
}
normalized, err := clientconfig.Normalize(settings)
if err != nil {
@@ -92,50 +99,37 @@ func SaveSettings(gameDir string, settings clientconfig.Settings, versions versi
return clientconfig.Settings{}, err
}
}
if normalized.CDNMode == clientconfig.CDNLocal {
if err := InstallLocalCatalog(gameDir, normalized.LocalResourceDirectory, versions.BundleVersion); err != nil {
return clientconfig.Settings{}, err
}
}
return clientconfig.Save(gameDir, normalized)
}
func Patch(gameDir string, settings clientconfig.Settings, versions versionconfig.Config) (introdb.Result, error) {
if _, err := SaveSettings(gameDir, settings, versions); err != nil {
return introdb.Result{}, err
}
func Patch(gameDir string) (introdb.Result, error) {
result, err := introdb.PatchClient(gameDir, PatchPlaceholder)
if err != nil {
return introdb.Result{}, err
}
if _, err := introdb.VerifyClient(gameDir); err != nil {
return introdb.Result{}, fmt.Errorf("verify patched client resources: %w", err)
}
if _, err := disableLegacyPlugin(gameDir); err != nil {
return introdb.Result{}, err
}
if err := download.RecordPreparedGame(gameDir, "BrownDust II_Data/resources.assets"); err != nil {
return introdb.Result{}, err
}
return result, nil
}
func InstallPlugins(
gameDir string,
settings clientconfig.Settings,
versions versionconfig.Config,
localIdentitySource string,
loginUISource string,
cashShopSource string,
fChatSource string,
) (InstallResult, error) {
status, err := Inspect(gameDir, versions)
installation, err := clientlayout.Resolve(gameDir)
if err != nil {
return InstallResult{}, err
}
if !status.BepInEx {
if !regularFile(filepath.Join(installation.BepInEx, "core", "BepInEx.dll")) {
return InstallResult{}, fmt.Errorf("BepInEx is not installed; install it from %s before installing the plugins", plugin.BepInExReleasesURL)
}
if _, err := SaveSettings(gameDir, settings, versions); err != nil {
return InstallResult{}, err
}
var sources []string
for spec, explicit := range map[plugin.Spec]string{plugin.LocalIdentity: localIdentitySource, plugin.LoginUI: loginUISource, plugin.CashShop: cashShopSource, plugin.FChat: fChatSource} {
source, err := plugin.ResolvePackaged(spec, explicit)
+18 -4
View File
@@ -1,6 +1,7 @@
package update
import (
"bd2server/internal/common/util"
"context"
"errors"
"fmt"
@@ -116,6 +117,7 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if fp.RequireClientUpdate && clientUpdateRequired(m.options.Versions.ClientVersion, fp.ClientVersion) {
return fmt.Errorf("update the launcher to %s before updating the game", fp.ClientVersion)
}
m.options.Logger.Info("game installation does not match the server requirement", "game", game, "requirement", fp.ID, "game_version", gameVersion(fp))
reuseResources := previousErr == nil && previous.ResourceFingerprint == fp.GameFingerprint && fp.GameFingerprint != "" && len(previous.Files) > 0 && gameReceiptMatches(game, previous.Fingerprint)
installGame := fp.RequireGameUpdate && !reuseResources
if installGame {
@@ -155,13 +157,17 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if resources == "" {
resources = filepath.Join(m.options.Directory, "resources")
}
m.options.Logger.Info("downloading required game and resources", "game", game, "resources", resources, "game_version", fp.Game.GameVersion, "bundle_version", fp.Game.BundleVersion, "game_data_version", fp.Game.GameDataVersion)
installed, err := download.Client(ctx, download.Options{PackageDir: m.options.Directory, GameDir: game, ResourceDir: resources, Workers: 8, Pinned: fp.Game}, io.Discard)
if err != nil {
return err
}
v.GameVersion, v.BundleVersion, v.GameDataVersion = installed.Versions.GameVersion, installed.Versions.BundleVersion, installed.Versions.GameDataVersion
resources = installed.ResourceDir
if _, err := setup.Patch(game, settings, v); err != nil {
if _, err := setup.SaveSettings(game, settings); err != nil {
return fmt.Errorf("restore game connection settings: %w", err)
}
if _, err := setup.Patch(game); err != nil {
return fmt.Errorf("restore game connection patch: %w", err)
}
if err := setup.InstallLocalCatalog(game, resources, v.BundleVersion); err != nil {
@@ -197,7 +203,7 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if err != nil {
return err
}
digest, err := release.HashFile(path)
digest, err := util.SHA256File(path)
if err != nil {
return err
}
@@ -209,6 +215,7 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if err := commonconfig.Save(filepath.Join(game, gameReceiptFile), receipt, commonconfig.WriteOptions{FileMode: 0644}); err != nil {
return err
}
m.options.Logger.Info("game installation recorded for the server requirement", "game", game, "requirement", fp.ID, "downloaded", installGame, "reused_resources", reuseResources, "verified_files", len(receipt.Files))
m.mu.Lock()
delete(m.gamePending, game)
if len(m.gamePending) == 0 {
@@ -268,8 +275,8 @@ func (m *Manager) installGameUpdates(ctx context.Context) {
// PrepareGame resolves the server's signed requirement before inspecting a
// possibly obsolete game installation with the new release's versions.
func (m *Manager) PrepareGame(ctx context.Context, game, origin string) error {
if !m.begin("preparing") {
return operationBusy()
if err := m.acquire(ctx, "preparing"); err != nil {
return err
}
defer m.end()
if err := m.CheckServer(ctx, m.options.Client, origin); err != nil {
@@ -339,3 +346,10 @@ func (m *Manager) clearServerRequirement() {
m.fingerprint = nil
m.mu.Unlock()
}
func gameVersion(fp *release.Fingerprint) string {
if fp.Game == nil {
return ""
}
return fp.Game.GameVersion
}
+92 -16
View File
@@ -6,6 +6,7 @@
package update
import (
"bd2server/internal/common/util"
"context"
"encoding/json"
"errors"
@@ -93,7 +94,7 @@ type Manager struct {
manifestURL string
keys []release.TrustedKey
operation sync.Mutex
operation chan struct{}
envelope []byte
mu sync.Mutex
status Status
@@ -109,7 +110,7 @@ func New(options Options) *Manager {
options.Logger = slog.Default()
}
address := release.BuiltinChannel().ManifestURL
m := &Manager{options: options, manifestURL: address, keys: release.BuiltinChannel().TrustedKeys, pending: map[string]bool{}, gamePending: map[string]bool{}}
m := &Manager{options: options, manifestURL: address, keys: release.BuiltinChannel().TrustedKeys, pending: map[string]bool{}, gamePending: map[string]bool{}, operation: make(chan struct{}, 1)}
m.status.Enabled = address != "" && !options.Development
m.loadPackagedFingerprint()
if result := TakeResult(options.Directory); result != nil {
@@ -176,14 +177,39 @@ func operationBusy() error {
}
func (m *Manager) begin(busy string) bool {
if !m.operation.TryLock() {
select {
case m.operation <- struct{}{}:
m.setBusy(busy)
return true
default:
return false
}
m.setBusy(busy)
return true
}
func (m *Manager) end() { m.setBusy(""); m.operation.Unlock() }
// acquire waits for a running background operation, so an action the player
// asked for runs after it instead of failing.
func (m *Manager) acquire(ctx context.Context, busy string) error {
select {
case m.operation <- struct{}{}:
m.setBusy(busy)
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (m *Manager) end() { m.setBusy(""); <-m.operation }
// WaitIdle waits until no update operation is running.
func (m *Manager) WaitIdle(ctx context.Context) error {
select {
case m.operation <- struct{}{}:
<-m.operation
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// Run checks shortly after start and then every six hours, downloads what
// is newer, installs a downloaded plugin set wherever no game runs, and
@@ -211,20 +237,25 @@ func (m *Manager) Run(ctx context.Context) {
}
func (m *Manager) refresh(ctx context.Context) {
warn := func(message string, err error) {
if ctx.Err() == nil {
m.options.Logger.Warn(message, "error", err)
}
}
if err := m.Check(ctx); err != nil {
m.options.Logger.Warn("update check failed", "error", err)
warn("update check failed", err)
return
}
if err := m.Download(ctx); err != nil {
m.options.Logger.Warn("update download failed", "error", err)
warn("update download failed", err)
return
}
if err := m.CommitPlugins(); err != nil {
m.options.Logger.Warn("plugin update not installed", "error", err)
warn("plugin update not installed", err)
return
}
if err := m.CommitGame(ctx); err != nil {
m.options.Logger.Warn("game resources not installed", "error", err)
warn("game resources not installed", err)
}
}
@@ -270,9 +301,39 @@ func (m *Manager) Check(ctx context.Context) error {
m.status.Plugins = offer(c, files, m.pluginStaging(c.Version))
}
}
m.logCheck(manifest)
return nil
}
// logCheck records what the manifest offers compared with this launcher.
func (m *Manager) logCheck(manifest release.Manifest) {
attrs := []any{"manifest_commit", manifest.Commit, "published_at", manifest.PublishedAt}
if c := manifest.Launcher; c != nil {
attrs = append(attrs, "launcher_installed", m.options.Versions.ClientVersion, "launcher_available", c.Version)
}
if c := manifest.Plugins; c != nil {
attrs = append(attrs, "plugins_installed", m.storeVersion(), "plugins_available", c.Version)
}
if c := manifest.Server; c != nil {
attrs = append(attrs, "server_available", c.Version)
}
var updates []string
if o := m.status.Launcher; o != nil {
updates = append(updates, fmt.Sprintf("launcher %s (%d bytes, downloaded=%t)", o.Version, o.Bytes, o.Ready))
}
if o := m.status.Plugins; o != nil {
updates = append(updates, fmt.Sprintf("plugins %s (%d bytes, downloaded=%t)", o.Version, o.Bytes, o.Ready))
}
if o := m.status.Game; o != nil {
updates = append(updates, fmt.Sprintf("game resources %s for %d instance(s)", o.Version, len(m.gamePending)))
}
if len(updates) == 0 {
m.options.Logger.Info("update check: everything is up to date", attrs...)
return
}
m.options.Logger.Info("update check: updates found", append(attrs, "updates", strings.Join(updates, "; "))...)
}
func newer(current, candidate string) bool {
ok, err := release.Newer(current, candidate)
return err == nil && ok
@@ -376,6 +437,7 @@ func (m *Manager) Download(ctx context.Context) error {
var finished int64
for _, j := range jobs {
for _, f := range j.files {
m.options.Logger.Info("downloading update file", "version", j.offer.Version, "file", f.Name, "bytes", f.Size)
_, err := release.Download(ctx, m.options.Client, m.manifestURL, f, j.staging, func(_ string, done, _ int64) {
m.mu.Lock()
m.status.Done = finished + done
@@ -389,6 +451,7 @@ func (m *Manager) Download(ctx context.Context) error {
m.mu.Lock()
j.offer.Ready = true
m.mu.Unlock()
m.options.Logger.Info("update downloaded and verified", "version", j.offer.Version, "files", len(j.files))
}
return nil
}
@@ -495,8 +558,8 @@ func (m *Manager) replaceStore(c *release.Component) error {
// StoreSources lists the plugin files of the current store set.
func (m *Manager) StoreSources() ([]string, error) {
m.operation.Lock()
defer m.operation.Unlock()
m.operation <- struct{}{}
defer func() { <-m.operation }()
return m.storeSources()
}
@@ -515,7 +578,7 @@ func (m *Manager) storeSources() ([]string, error) {
return nil, fmt.Errorf("invalid stored plugin %q", f.Name)
}
source := filepath.Join(directory, f.Name)
digest, err := release.HashFile(source)
digest, err := util.SHA256File(source)
if err != nil {
return nil, err
}
@@ -588,11 +651,19 @@ func (m *Manager) ensurePlugins(game string) error {
m.mu.Lock()
delete(m.pending, game)
m.mu.Unlock()
m.options.Logger.Info("plugin set installed", "game", game)
m.options.Logger.Info("plugin set installed", "game", game, "plugins", strings.Join(pluginNames(sources), ", "))
}
return err
}
func pluginNames(sources []string) []string {
names := make([]string, len(sources))
for i, source := range sources {
names[i] = filepath.Base(source)
}
return names
}
func (m *Manager) installWaiting() {
if !m.begin("installing") {
return
@@ -802,6 +873,11 @@ func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin s
}
}
slices.Sort(stale)
requirement := "none"
if fp != nil {
requirement = fmt.Sprintf("%s (client %s, update required=%t, game update required=%t)", fp.ID, fp.ClientVersion, fp.RequireClientUpdate, fp.RequireGameUpdate)
}
m.options.Logger.Info("server compatibility checked", "origin", origin, "server_version", compat.ServerVersion, "game_version", compat.GameVersion, "requirement", requirement, "stale_plugins", strings.Join(stale, ", "))
if len(stale) != 0 {
return fmt.Errorf("Server %s no longer accepts these plugins: %s. Update the plugins in the launcher first", compat.ServerVersion, strings.Join(stale, ", ")) //nolint:staticcheck // ST1005: shown to players
}
@@ -810,8 +886,8 @@ func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin s
// WithLaunch keeps updates excluded until the prepared game process has started.
func (m *Manager) WithLaunch(ctx context.Context, client *http.Client, game, origin string, launch func() error) error {
if !m.begin("preparing") {
return operationBusy()
if err := m.acquire(ctx, "preparing"); err != nil {
return err
}
defer m.end()
if err := m.CheckServer(ctx, client, origin); err != nil {
+3 -2
View File
@@ -1,6 +1,7 @@
package update
import (
"bd2server/internal/common/util"
"encoding/json"
"errors"
"fmt"
@@ -146,7 +147,7 @@ func switchLauncher(staging, target, from, to string, keys []release.TrustedKey)
for _, m := range slices.Backward(done) {
current := filepath.Join(target, m.name)
if m.backup != "" {
if err := commonconfig.ReplaceFile(m.backup, current); err != nil {
if err := util.ReplaceFile(m.backup, current); err != nil {
failures = append(failures, fmt.Errorf("restore %s: %w", m.name, err))
}
} else if err := os.Remove(current); err != nil && !errors.Is(err, os.ErrNotExist) {
@@ -195,7 +196,7 @@ func switchLauncher(staging, target, from, to string, keys []release.TrustedKey)
return undo(err)
}
done = append(done, m)
if err := commonconfig.ReplaceFile(name, current); err != nil {
if err := util.ReplaceFile(name, current); err != nil {
_ = os.Remove(name)
return undo(err)
}
+3 -2
View File
@@ -1,6 +1,7 @@
package update
import (
"bd2server/internal/common/util"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
@@ -67,7 +68,7 @@ func TestRunHelperWaitsForOldLauncherBeforeReplacementResultAndRestart(t *testin
target, staging := filepath.Join(root, "installed"), filepath.Join(root, "staged")
launcherPath := filepath.Join(target, launcherExecutable())
pid, stopLauncher := startWaitingProcess(t, launcherPath)
oldDigest, err := release.HashFile(launcherPath)
oldDigest, err := util.SHA256File(launcherPath)
if err != nil {
t.Fatal(err)
}
@@ -121,7 +122,7 @@ func TestRunHelperWaitsForOldLauncherBeforeReplacementResultAndRestart(t *testin
t.Fatalf("updater finished while the old launcher was still running: %v", helperErr)
case <-time.After(300 * time.Millisecond):
}
if digest, err := release.HashFile(launcherPath); err != nil || digest != oldDigest {
if digest, err := util.SHA256File(launcherPath); err != nil || digest != oldDigest {
t.Fatalf("running launcher was replaced: digest=%s, error=%v", digest, err)
}
assertContent(t, filepath.Join(target, "runtime.dat"), "old runtime")
+3 -2
View File
@@ -2,6 +2,7 @@
package config
import (
"bd2server/internal/common/util"
"bytes"
"encoding/json"
"errors"
@@ -71,7 +72,7 @@ func Save[T any](path string, value T, options WriteOptions) error {
return err
}
defer func() { _ = os.Remove(temporary) }()
return ReplaceFile(temporary, path)
return util.ReplaceFile(temporary, path)
}
// Ensure publishes defaults atomically and never replaces an existing file.
@@ -111,7 +112,7 @@ func WriteFile(path string, raw []byte) error {
return err
}
defer func() { _ = os.Remove(temporary) }()
return ReplaceFile(temporary, path)
return util.ReplaceFile(temporary, path)
}
func stageBytes(path string, raw []byte, options WriteOptions) (string, error) {
+3 -17
View File
@@ -2,6 +2,7 @@ package release
import (
"archive/zip"
"bd2server/internal/common/util"
"context"
"crypto/sha256"
"encoding/hex"
@@ -13,8 +14,6 @@ import (
"path/filepath"
"strings"
"time"
commonconfig "bd2server/internal/common/config"
)
const (
@@ -154,7 +153,7 @@ func Download(ctx context.Context, client *http.Client, manifestURL string, file
if written != file.Size || hex.EncodeToString(digest.Sum(nil)) != file.SHA256 {
return "", fmt.Errorf("release: %s failed verification; the download was discarded", file.Name)
}
if err := commonconfig.ReplaceFile(temporary.Name(), target); err != nil {
if err := util.ReplaceFile(temporary.Name(), target); err != nil {
return "", err
}
return target, nil
@@ -166,23 +165,10 @@ func Matches(path string, file File) bool {
if err != nil || !info.Mode().IsRegular() || info.Size() != file.Size {
return false
}
sum, err := HashFile(path)
sum, err := util.SHA256File(path)
return err == nil && sum == file.SHA256
}
func HashFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer func() { _ = f.Close() }()
digest := sha256.New()
if _, err := io.Copy(digest, f); err != nil {
return "", err
}
return hex.EncodeToString(digest.Sum(nil)), nil
}
// Extract unpacks a verified zip archive into an empty directory, refusing
// entries that would escape it.
func Extract(archive, directory string) error {
+21
View File
@@ -0,0 +1,21 @@
package util
import (
"crypto/sha256"
"encoding/hex"
"io"
"os"
)
func SHA256File(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer func() { _ = f.Close() }()
digest := sha256.New()
if _, err := io.Copy(digest, f); err != nil {
return "", err
}
return hex.EncodeToString(digest.Sum(nil)), nil
}
+42
View File
@@ -0,0 +1,42 @@
package util
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"errors"
"math/big"
)
func RandomUint64N(limit uint64) (uint64, error) {
if limit == 0 {
return 0, errors.New("util: random upper bound must be positive")
}
value, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
if err != nil {
return 0, err
}
return value.Uint64(), nil
}
func RandomHex(size int) (string, error) {
if size < 0 {
return "", errors.New("util: random byte count must not be negative")
}
raw := make([]byte, size)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return hex.EncodeToString(raw), nil
}
func RandomBase64URL(size int) (string, error) {
if size < 0 {
return "", errors.New("util: random byte count must not be negative")
}
raw := make([]byte, size)
if _, err := rand.Read(raw); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(raw), nil
}
@@ -1,6 +1,6 @@
//go:build !windows
package config
package util
import "os"
@@ -1,6 +1,6 @@
//go:build windows
package config
package util
import (
"os"
+31
View File
@@ -0,0 +1,31 @@
package util
type Well512 struct {
State [16]uint64
Index uint64
}
func NewWell512(seed uint64) Well512 {
r := Well512{}
for i := range r.State {
r.State[i] = seed + uint64(i)*90
}
return r
}
func (r *Well512) Next() uint64 {
index := r.Index
x, y := r.State[index], r.State[(index+13)&15]
b := x ^ y ^ (x << 16) ^ (y << 15)
c := r.State[(index+9)&15]
c ^= c >> 11
x = b ^ c
r.State[index] = x
// Client IL zero-extends this uint32 mask into the 64-bit state.
d := x ^ ((x << 5) & uint64(0xda442d24))
index = (index + 15) & 15
x = r.State[index]
r.State[index] = x ^ b ^ d ^ (x << 2) ^ (b << 18) ^ (c << 28)
r.Index = index
return r.State[index]
}
+4 -3
View File
@@ -5,6 +5,7 @@ package admin
import (
"bd2server/internal/common/i18n"
"bd2server/internal/common/util"
"context"
"crypto/subtle"
"embed"
@@ -125,7 +126,7 @@ func New(options Options) (*Console, error) {
// externally visible origin of this server. Whoever can read the server's
// output is its operator, so the link needs no other credential.
func (c *Console) IssueSignInLink(base string) (string, error) {
token, err := randomToken(32)
token, err := util.RandomBase64URL(32)
if err != nil {
return "", err
}
@@ -319,7 +320,7 @@ func (c *Console) loginStart(w http.ResponseWriter, r *http.Request) {
fail(w, http.StatusBadRequest, "invalid", "login could not be started")
return
}
key, err := randomToken(24)
key, err := util.RandomBase64URL(24)
if err != nil {
fail(w, http.StatusInternalServerError, "unavailable", "login could not be started")
return
@@ -647,7 +648,7 @@ func (c *Console) sendMail(w http.ResponseWriter, r *http.Request, current sessi
fail(w, http.StatusBadRequest, "invalid_text", "title (1-500) and body (1-5000) are required")
return
}
identity, err := randomToken(18)
identity, err := util.RandomBase64URL(18)
if err != nil {
fail(w, http.StatusInternalServerError, "unavailable", "mail unavailable")
return
@@ -0,0 +1,54 @@
package admin
import (
"net/http"
"net/http/httptest"
"testing"
"bd2server/internal/server/design/gameconfig"
)
func TestOwnerCanConfigureRecordingProxyForNextServerStart(t *testing.T) {
console, identity, _ := newConsole(t)
server := httptest.NewServer(console.Handler())
defer server.Close()
owner := newBrowser(t, server)
if owner.login(identity, "owner") != http.StatusOK {
t.Fatal("owner could not open the configuration editor")
}
status, document := owner.do(http.MethodGet, "/admin/api/config/game", nil, nil)
if status != http.StatusOK {
t.Fatal("game settings are unavailable")
}
view := document["view"].(map[string]any)
value := view["value"].(map[string]any)
value["spine_recording"] = map[string]string{"download_base_url": "https://replay.example.com/recordings"}
status, saved := owner.do(http.MethodPut, "/admin/api/config/game", value, map[string]string{"If-Match": view["revision"].(string)})
if status != http.StatusOK || saved["pending"] != true {
t.Fatalf("recording URL was not saved for restart: status=%d", status)
}
restarted, err := gameconfig.Document.Load(saved["path"].(string))
if err != nil || restarted.SpineRecording.DownloadBaseURL != "https://replay.example.com/recordings" {
t.Fatalf("the next server start would lose the owner's recording proxy: %v", err)
}
for _, invalid := range []string{"javascript:alert(1)", "https://user:password@example.com/replays", "https://example.com/replays?token=secret", "http://example.com/replays"} {
value["spine_recording"] = map[string]string{"download_base_url": invalid}
status, _ = owner.do(http.MethodPut, "/admin/api/config/game", value, map[string]string{"If-Match": saved["revision"].(string)})
if status != http.StatusUnprocessableEntity {
t.Fatalf("unsafe recording address replaced a working proxy: status=%d", status)
}
}
restarted, err = gameconfig.Document.Load(saved["path"].(string))
if err != nil || restarted.SpineRecording.DownloadBaseURL != "https://replay.example.com/recordings" {
t.Fatalf("rejected edit damaged the working recording URL: %v", err)
}
value["spine_recording"] = map[string]string{"download_base_url": ""}
status, saved = owner.do(http.MethodPut, "/admin/api/config/game", value, map[string]string{"If-Match": saved["revision"].(string)})
if status != http.StatusOK {
t.Fatal("owner could not restore this server as the recording source")
}
restarted, err = gameconfig.Document.Load(saved["path"].(string))
if err != nil || restarted.SpineRecording.DownloadBaseURL != "" {
t.Fatalf("clearing the proxy did not persist: %v", err)
}
}
+3 -12
View File
@@ -1,11 +1,10 @@
package admin
import (
"bd2server/internal/common/util"
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -80,10 +79,10 @@ func (s *Store) Close() error { return s.db.Close() }
// CreateSession returns a new session token and its CSRF token.
func (s *Store) CreateSession(ctx context.Context, accountID string, role Role) (token, csrf string, err error) {
if token, err = randomToken(32); err != nil {
if token, err = util.RandomBase64URL(32); err != nil {
return "", "", err
}
if csrf, err = randomToken(24); err != nil {
if csrf, err = util.RandomBase64URL(24); err != nil {
return "", "", err
}
now := s.now()
@@ -187,14 +186,6 @@ func (s *Store) RemoveAdministrator(ctx context.Context, accountID string) error
return tx.Commit()
}
func randomToken(size int) (string, error) {
b := make([]byte, size)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func digest(token string) []byte {
sum := sha256.Sum256([]byte(token))
return sum[:]
@@ -504,5 +504,9 @@
"console.error.confirming_update": "The previous update is still being checked. Wait until it is confirmed healthy.",
"console.updates.component": "Update content",
"console.updates.component.server": "Server program",
"console.updates.restarting": "The server is restarting to apply the update. This page reconnects automatically."
"console.updates.restarting": "The server is restarting to apply the update. This page reconnects automatically.",
"config.game.section.spine_recording.title": "Interaction recording",
"config.game.section.spine_recording.help": "Save players’ interactive illustration actions for playback in the game. Restart the server after changing this setting.",
"config.game.field.spine_recording.download_base_url.label": "Recording download base URL",
"config.game.field.spine_recording.download_base_url.help": "Leave empty to use this server. A custom address must reverse proxy to /client/spine-recordings/ on this server; recording paths and access credentials are appended automatically. Public addresses must use HTTPS."
}
@@ -504,5 +504,9 @@
"console.error.confirming_update": "前回の更新の動作確認中です。正常動作の確認が完了するまでお待ちください。",
"console.updates.component": "更新内容",
"console.updates.component.server": "サーバープログラム",
"console.updates.restarting": "更新を適用するためにサーバーを再起動しています。このページは自動的に再接続します。"
"console.updates.restarting": "更新を適用するためにサーバーを再起動しています。このページは自動的に再接続します。",
"config.game.section.spine_recording.title": "インタラクション録画",
"config.game.section.spine_recording.help": "プレイヤーのイラスト操作を保存し、ゲーム内で再生します。変更後はサーバーを再起動してください。",
"config.game.field.spine_recording.download_base_url.label": "録画ダウンロードのベース URL",
"config.game.field.spine_recording.download_base_url.help": "空欄の場合はこのサーバーを使用します。独自のアドレスは、このサーバーの /client/spine-recordings/ にリバースプロキシしてください。録画パスとアクセス資格情報は自動で追加されます。外部公開には HTTPS が必要です。"
}
@@ -504,5 +504,9 @@
"console.error.confirming_update": "이전 업데이트의 정상 작동을 확인하는 중입니다. 확인이 완료될 때까지 기다려 주세요.",
"console.updates.component": "업데이트 내용",
"console.updates.component.server": "서버 프로그램",
"console.updates.restarting": "업데이트를 적용하기 위해 서버를 다시 시작하는 중입니다. 이 페이지는 자동으로 다시 연결됩니다."
"console.updates.restarting": "업데이트를 적용하기 위해 서버를 다시 시작하는 중입니다. 이 페이지는 자동으로 다시 연결됩니다.",
"config.game.section.spine_recording.title": "상호작용 녹화",
"config.game.section.spine_recording.help": "플레이어의 일러스트 상호작용을 저장하여 게임에서 재생합니다. 설정을 변경한 후 서버를 다시 시작하세요.",
"config.game.field.spine_recording.download_base_url.label": "녹화 다운로드 기본 URL",
"config.game.field.spine_recording.download_base_url.help": "비워 두면 이 서버를 사용합니다. 사용자 지정 주소는 이 서버의 /client/spine-recordings/ 로 역방향 프록시해야 합니다. 녹화 경로와 접근 자격 정보는 자동으로 추가됩니다. 외부 공개 주소에는 HTTPS가 필요합니다."
}
@@ -504,5 +504,9 @@
"console.error.confirming_update": "上一次更新仍在进行健康检查,请等待确认完成。",
"console.updates.component": "更新内容",
"console.updates.component.server": "服务端程序",
"console.updates.restarting": "服务器正在重启以应用更新,本页面会自动重新连接。"
"console.updates.restarting": "服务器正在重启以应用更新,本页面会自动重新连接。",
"config.game.section.spine_recording.title": "互动录制",
"config.game.section.spine_recording.help": "保存玩家的互动立绘操作记录,并供原生客户端回放。修改后重启服务端生效。",
"config.game.field.spine_recording.download_base_url.label": "录制下载基础 URL",
"config.game.field.spine_recording.download_base_url.help": "留空使用本服地址。自定义地址须反向代理到本服的 /client/spine-recordings/;系统会在其后追加录制路径和访问凭据。公网须使用 HTTPS。"
}
@@ -504,5 +504,9 @@
"console.error.confirming_update": "上次更新仍在進行健康檢查,請等待確認完成。",
"console.updates.component": "更新內容",
"console.updates.component.server": "伺服器程式",
"console.updates.restarting": "伺服器正在重新啟動以套用更新,本頁面會自動重新連線。"
"console.updates.restarting": "伺服器正在重新啟動以套用更新,本頁面會自動重新連線。",
"config.game.section.spine_recording.title": "互動錄製",
"config.game.section.spine_recording.help": "儲存玩家的互動立繪操作記錄,供原生客戶端重播。修改後重新啟動伺服器生效。",
"config.game.field.spine_recording.download_base_url.label": "錄製下載基礎 URL",
"config.game.field.spine_recording.download_base_url.help": "留空使用本服位址。自訂位址須反向代理至本服的 /client/spine-recordings/;系統會在其後附加錄製路徑與存取憑證。公網須使用 HTTPS。"
}
@@ -0,0 +1,163 @@
//go:build integration
package app
import (
"bytes"
"encoding/base64"
"encoding/binary"
"slices"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/protocol/wire"
)
// Current 20261012190548 GameData binds Greed floor 1 to pack3003 deck10001.
// Its win/no-death/8-turn challenges award material1000 x1, gold30000 and
// bonus hunting AP5. These expectations come from the read-only GameData query,
// independently of the castle loader and the runtime reward response.
func TestCastleTowerBattleRewardsAndChallengesSurviveAccountReopen(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
a := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
b := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
t.Cleanup(func() { closeNicknamePlayer(t, a.owner); closeNicknamePlayer(t, b.owner) })
var blue, deck, character []byte
a.run(t, true, func(ctx command.Context, p *playerAssembly) {
// ContentOpenTable group1/3003 requires the actual Evil Castle ticket13003.
if _, e := p.ownedItems.GrantOnce(ctx, "castle-entry-ticket", []gamedata.BattleReward{{Type: 19, ID: 13003, Count: 1}}); e != nil {
t.Fatal(e)
}
for _, c := range p.worldService.CharacterService().RawAll() {
if roster.IsStoryCharacter(c) || roster.IsCharmCharacter(c) {
continue
}
costume, owned := p.collection.CostumeByIndex(c.UseCostume)
if !owned || costume.UseChar != c.InvenIndex {
continue
}
hp, e := p.worldService.CharacterService().MaxHealth(ctx, c.InvenIndex)
if e != nil {
t.Fatal(e)
}
blue = appScalar(1, 1)
blue = append(blue, appScalar(2, c.InvenIndex)...)
blue = append(blue, appScalar(3, c.ID)...)
blue = append(blue, appScalar(4, hp)...)
blue = append(blue, appScalar(6, costume.InvenIndex)...)
blue = append(blue, appScalar(7, costume.ID)...)
deck = appScalar(1, c.InvenIndex)
deck = append(deck, appScalar(2, 0)...)
deck = append(deck, appScalar(3, 1)...)
character = roster.CharacterWire(c)
character, _, e = wire.ReplaceVarint(character, 3, hp)
if e != nil {
t.Fatal(e)
}
break
}
if len(blue) == 0 {
t.Fatal("starter player has no owned battle participant")
}
})
a.reopen(t)
a.protocol(t, "/PackInGameInfo", trapRequest(1, 3003))
beforeGold := a.owner.assembly.wallet.Snapshot(command.Context{}).Gold
beforeMaterial := appItemTotals(a.protocol(t, "/ItemInfo", appScalar(1, 2)))[[2]uint64{8, 1000}]
bGold := b.owner.assembly.wallet.Snapshot(command.Context{}).Gold
bMaterial := appItemTotals(b.protocol(t, "/ItemInfo", appScalar(1, 1)))[[2]uint64{8, 1000}]
bonusAP := func(s *trapPlayerScenario) uint64 {
t.Helper()
var bonus uint64
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
var e error
_, bonus, e = p.huntingService.HuntingAP(ctx)
if e != nil {
t.Fatal(e)
}
})
return bonus
}
beforeAP, otherAP := bonusAP(a), bonusAP(b)
enter := appScalar(1, 3)
enter = append(enter, appScalar(4, 10001)...)
enter = append(enter, appScalar(5, 16)...)
enter = append(enter, appScalar(9, 1)...)
a.protocol(t, "/BattleEnter", enter)
common := appScalar(1, 16)
common = append(common, appScalar(2, 10001)...)
checkpoint := appMessage(1, common)
checkpoint = append(checkpoint, appMessage(8, []byte(base64.StdEncoding.EncodeToString(appMessage(3, blue))))...)
start := trapRequest(4, 10001)
start = wire.AppendBytes(start, 3, deck)
start = wire.AppendBytes(start, 5, blue)
start = wire.AppendBytes(start, 100, checkpoint)
a.protocol(t, "/BattleStart", start)
// Reassembly must retain the normal battle's owned party and round evidence.
a.reopen(t)
end := trapRequest(5, 1)
end = wire.AppendBytes(end, 3, character)
for _, index := range []uint64{0, 1, 2} {
end = wire.AppendVarint(end, 5, index)
}
settled := a.protocol(t, "/BattleEnd", end)
assertAssets := func() {
t.Helper()
if a.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold+30000 || appItemTotals(a.protocol(t, "/ItemInfo", appScalar(1, uint64(a.commands+100))))[[2]uint64{8, 1000}] != beforeMaterial+1 || bonusAP(a) != beforeAP+5 {
t.Fatal("tower challenges did not credit their authored gold, material and hunting AP exactly once")
}
}
assertAssets()
assertTower := func(s *trapPlayerScenario, want bool) {
t.Helper()
rows := appRows(s.protocol(t, "/EvilCastleTowerInfo", appScalar(1, uint64(s.commands+100))), 1)
if !want {
if len(rows) != 0 {
t.Fatal("unplayed account acquired another player's tower progress")
}
return
}
if len(rows) != 1 || appValue(rows[0], 1) != 1 || appValue(rows[0], 3) != 16 {
t.Fatal("restored tower floor/mode differs from the played encounter")
}
var indexes []uint64
if e := wire.Walk(rows[0], func(f wire.Field) error {
if f.Number == 2 {
for raw := f.Value; len(raw) > 0; {
value, count := binary.Uvarint(raw)
if count <= 0 {
return wire.ErrMalformed
}
indexes = append(indexes, value)
raw = raw[count:]
}
}
return nil
}); e != nil {
t.Fatal(e)
}
if !slices.Equal(indexes, []uint64{0, 1, 2}) {
t.Fatalf("completed tower challenges were lost or fabricated: %v", indexes)
}
}
assertTower(a, true)
assertTower(b, false)
if replay := a.protocol(t, "/BattleEnd", end); !bytes.Equal(replay, settled) {
t.Fatal("battle settlement replay changed its reply")
}
assertAssets()
a.reopen(t)
b.reopen(t)
assertTower(a, true)
assertTower(b, false)
assertAssets()
if replay := a.protocol(t, "/BattleEnd", end); !bytes.Equal(replay, settled) {
t.Fatal("reopened battle receipt changed its reply")
}
assertAssets()
if b.owner.assembly.wallet.Snapshot(command.Context{}).Gold != bGold || appItemTotals(b.protocol(t, "/ItemInfo", appScalar(1, uint64(b.commands+100))))[[2]uint64{8, 1000}] != bMaterial || bonusAP(b) != otherAP {
t.Fatal("tower rewards crossed account boundaries")
}
}
+50
View File
@@ -13,6 +13,15 @@ import (
)
type designCatalog struct {
collectionStatistics *gamedata.CollectionStatisticsDesign
interaction *gamedata.SpineInteractionDesign
community *gamedata.CommunityRewards
cafeteria *gamedata.CafeteriaDesign
dating *gamedata.DatingDesign
castle *gamedata.CastleRewardDesign
ib *gamedata.IBDesign
roguelike *gamedata.RogueLikeDesign
life *gamedata.LifeCatalog
friends gamedata.FriendRules
rooms *gamedata.RoomDesign
roomCommerce *gamedata.RoomCommerceDesign
@@ -34,6 +43,7 @@ type designCatalog struct {
presetDesign *gamedata.PresetDesign
recipeDesign *gamedata.CookingRecipeDesign
randomBoxes *gamedata.RandomBoxDesign
resourceItems *gamedata.ResourceItemDesign
itemStacks *gamedata.ItemStackDesign
slotDesign *gamedata.InventorySlotDesign
contentTickets *gamedata.GachaContentTicketDesign
@@ -101,9 +111,45 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
calendars, gameRules := c.calendars, c.gameRules
d := &designCatalog{source: gamedata.NewSource(gameData, gameDataVersion)}
var err error
d.collectionStatistics, err = gamedata.LoadCollectionStatistics(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load collection statistics: %w", err)
}
if err := d.loadSharedDesign(c); err != nil {
return nil, err
}
d.interaction, err = gamedata.LoadSpineInteractionDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load interaction design: %w", err)
}
d.community, err = gamedata.LoadCommunityRewards(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load community rewards: %w", err)
}
d.cafeteria, err = gamedata.LoadCafeteriaDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load cafeteria design: %w", err)
}
d.dating, err = gamedata.LoadDatingDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load dating design: %w", err)
}
d.castle, err = gamedata.LoadCastleRewardDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load castle design: %w", err)
}
d.ib, err = gamedata.LoadIBDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load IB design: %w", err)
}
d.roguelike, err = gamedata.LoadRogueLikeDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load roguelike design: %w", err)
}
d.life, err = gamedata.LoadLifeCatalog(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load life design: %w", err)
}
d.nicknameTicketID, err = gamedata.LoadNicknameTicketID(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load nickname ticket: %w", err)
@@ -137,6 +183,10 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
if err != nil {
return nil, fmt.Errorf("load deterministic random-box GameData: %w", err)
}
d.resourceItems, err = gamedata.LoadResourceItemDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load resource selection items: %w", err)
}
d.itemStacks, err = gamedata.LoadItemStackDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load item stack GameData: %w", err)
@@ -0,0 +1,89 @@
//go:build integration
package app
import (
"testing"
"time"
"bd2server/internal/server/domain/events"
)
// LocalText5700035 asks to change the homescreen. LobbySettingUI saves its
// slots locally and reports condition39 only through MissionUpdate. Current
// GameData mission3038 grants four type8/id14 materials and belongs to the
// third day of EventMissionGroup7001; mission3037 requires equipment upgrades.
func TestHomescreenMissionPersistsAndPaysOnceWithoutAuthorizingEquipmentProgress(t *testing.T) {
g := newMissionGameplay(t)
now := time.Now().UTC()
g.now = now
schedule := events.Schedule{UID: 9001, Type: 4, ID: 7001, Start: now.Add(-72 * time.Hour).UnixMilli(), End: now.Add(24 * time.Hour).UnixMilli()}
installCalendar := func() {
t.Helper()
if err := g.owner.assembly.eventRegistry.Replace([]events.Schedule{schedule}); err != nil {
t.Fatal(err)
}
}
installCalendar()
update := func(id, value uint64) error {
t.Helper()
row := append(appScalar(1, 303), appScalar(2, id)...)
row = append(row, appScalar(3, value)...)
row = append(row, appScalar(4, 7001)...)
_, err := g.execute("/MissionUpdate", appMessage(2, row))
return err
}
assertHomescreen := func(want uint64, claimed bool) {
t.Helper()
for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) {
if appValue(row, 1) == 7001 && appValue(row, 3) == 3038 {
if appValue(row, 4) != want || (appValue(row, 5) == 1) != claimed {
t.Fatalf("homescreen progress not restored: value=%d claimed=%v", appValue(row, 4), appValue(row, 5) == 1)
}
return
}
}
t.Fatal("third-day homescreen task missing")
}
claim := append(appScalar(3, 2), appScalar(4, 303)...)
claim = append(claim, appScalar(5, 3038)...)
claim = append(claim, appScalar(6, 7001)...)
before := g.itemCount(8, 14)
if _, err := g.execute("/MissionClear", claim); err == nil {
t.Fatal("homescreen reward was available before changing the setting")
}
if err := update(3037, 1); err == nil {
t.Fatal("a client report manufactured equipment upgrades")
}
assertHomescreen(0, false)
if err := update(3038, 1); err != nil {
t.Fatalf("native local homescreen change rejected: %v", err)
}
if g.itemCount(8, 14) != before {
t.Fatal("reporting a setting change paid its unclaimed reward")
}
g.reopen()
installCalendar()
assertHomescreen(1, false)
if err := update(3038, 2); err != nil {
t.Fatalf("repeated local change beyond completed target rejected: %v", err)
}
assertHomescreen(1, false)
response := g.call("/MissionClear", claim)
if missionRewardCount(t, response, 8, 14) != 4 || g.itemCount(8, 14) != before+4 {
t.Fatal("homescreen task did not pay its four crafting materials")
}
g.reopen()
installCalendar()
assertHomescreen(1, true)
if _, err := g.execute("/MissionClear", claim); err == nil {
t.Fatal("a new claim paid the same homescreen task twice")
}
if g.itemCount(8, 14) != before+4 {
t.Fatal("reopening or retrying duplicated homescreen materials")
}
if err := update(3038, 0); err != nil {
t.Fatal(err)
}
assertHomescreen(1, true)
}
@@ -0,0 +1,259 @@
//go:build integration
package app
import (
"bytes"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/events"
"bd2server/internal/server/protocol/wire"
)
// FriendshipPacket defaults an owned costume to level1 before any counseling.
// GameData501's first two stories award80 diamonds at levels1 and3; favorite
// gift7001 gives40EXP, and the first two level thresholds are50 and60.
func TestFriendshipStoriesFollowEarnedLevelsAndSurviveReentryWithoutDuplicateRewards(t *testing.T) {
s := newFriendshipScenario(t)
var before, giftIndex uint64
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if err := p.eventRegistry.Replace(nil); err != nil {
t.Fatal(err)
}
if _, err := p.collection.GrantCostumes(ctx, "friendship-owned-costume", []uint64{501}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
items, err := p.ownedItems.GrantOnce(ctx, "friendship-gifts", []gamedata.BattleReward{{Type: 8, ID: 7001, Count: 3}})
if err != nil || len(items) != 1 {
t.Fatalf("supply gifts: %v", err)
}
giftIndex = items[0].InvenIndex
before = p.wallet.Snapshot(ctx).FreeJewelry
})
first := friendshipEpisodeRequest(10, 501, 1)
response := s.protocol(t, "/FriendshipSpecialEpisodeClear", first)
assertFriendshipDiamonds(t, s, before+80)
s.reopen(t)
if replay := s.protocol(t, "/FriendshipSpecialEpisodeClear", first); !bytes.Equal(response, replay) {
t.Fatal("reopening lost the acknowledged story completion")
}
s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(11, 501, 1))
assertFriendshipDiamonds(t, s, before+80)
if _, err := s.execute("/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(12, 501, 2)); err == nil {
t.Fatal("next story opened without earning its friendship level")
}
assertFriendshipEpisodes(t, s, 501, 1)
request := wire.AppendBytes(wire.AppendVarint(wire.AppendVarint(nil, 1, 13), 2, 501), 3, inventoryItem(giftIndex, 7001, 8, 3))
s.protocol(t, "/FriendshipGift", request)
s.reopen(t)
s.protocol(t, "/FriendshipGift", request)
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
if level := p.friendshipService.CurrentLevel(501); level != 3 {
t.Fatalf("three favorite gifts should earn level3, got%d", level)
}
for _, item := range p.ownedItems.All(ctx) {
if item.InvenIndex == giftIndex && item.Count != 0 {
t.Fatal("consumed gifts reappeared after reopening")
}
}
})
s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(14, 501, 2))
s.reopen(t)
assertFriendshipEpisodes(t, s, 501, 1, 2)
assertFriendshipDiamonds(t, s, before+160)
}
// FriendshipStoryPopupUI_StoryItem waives the level requirement only for the
// scheduled group/episode, but still requires the preceding story to be clear.
func TestFriendshipEventUnlockIsEpisodeSpecificAndKeepsCompletedStoriesAfterTheEvent(t *testing.T) {
s := newFriendshipScenario(t)
var before, coinsBefore uint64
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.collection.GrantCostumes(ctx, "event-friendship-owned-costume", []uint64{60804}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
now := time.Now()
if err := p.eventRegistry.Replace([]events.Schedule{{UID: 991, Type: 24, ID: 60804, SubID: 2, Start: now.Add(-time.Hour).UnixMilli(), End: now.Add(time.Hour).UnixMilli()}}); err != nil {
t.Fatal(err)
}
before = p.wallet.Snapshot(ctx).FreeJewelry
for _, item := range p.ownedItems.All(ctx) {
if item.Type == 8 && item.ID == 2068 {
coinsBefore += item.Count
}
}
})
if _, err := s.execute("/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(20, 60804, 2)); err == nil {
t.Fatal("event bypassed the required preceding story")
}
s.run(t, false, func(_ command.Context, p *playerAssembly) {
now := time.Now()
if err := p.eventRegistry.Replace([]events.Schedule{{UID: 991, Type: 24, ID: 60804, SubID: 2, Start: now.Add(-time.Hour).UnixMilli(), End: now.Add(time.Hour).UnixMilli()}}); err != nil {
t.Fatal(err)
}
})
s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(21, 60804, 1))
s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(22, 60804, 2))
if _, err := s.execute("/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(23, 60804, 3)); err == nil {
t.Fatal("one scheduled episode unlocked an unscheduled episode")
}
s.reopen(t)
s.run(t, false, func(_ command.Context, p *playerAssembly) {
if err := p.eventRegistry.Replace(nil); err != nil {
t.Fatal(err)
}
})
s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(24, 60804, 2))
assertFriendshipEpisodes(t, s, 60804, 1, 2)
assertFriendshipDiamonds(t, s, before+160)
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
var coins uint64
for _, item := range p.ownedItems.All(ctx) {
if item.Type == 8 && item.ID == 2068 {
coins += item.Count
}
}
if coins != coinsBefore+650 {
t.Fatalf("only scheduled episode2 should grant event coins once: got%d want%d", coins, coinsBefore+650)
}
})
}
// FriendshipPacket consumes free AP before stacked AP. The per-costume daily
// limit is separate; an acknowledged consultation must not charge twice.
func TestFriendshipCounselingConsumesStackedAPOnlyAfterDailyFreeAPAndPersistsTheStory(t *testing.T) {
s := newFriendshipScenario(t)
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.collection.GrantCostumes(ctx, "counseling-costumes", []uint64{501, 801, 1001, 1002}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
if _, err := p.eventEconomy.Apply(ctx, "stacked-counseling-supply", nil, []gamedata.Reward{{Type: 72, Count: 1}}); err != nil {
t.Fatal(err)
}
})
counsel := func(seq, costume uint64) []byte {
return wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, seq), 2, costume), 3, 1)
}
for i, costume := range []uint64{501, 801, 1001} {
s.protocol(t, "/FriendshipCounseling", counsel(uint64(30+i), costume))
}
s.reopen(t)
s.run(t, false, func(_ command.Context, p *playerAssembly) {
remaining, err := p.friendshipService.FriendshipAP()
if err != nil || remaining != 0 {
t.Fatalf("three consultations did not exhaust free AP: remaining%d err%v", remaining, err)
}
})
request := counsel(33, 1002)
s.protocol(t, "/FriendshipCounseling", request)
s.reopen(t)
s.protocol(t, "/FriendshipCounseling", request)
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
balance, err := p.eventEconomy.CurrencyBalance(ctx, 72)
if err != nil || balance != 0 {
t.Fatalf("fourth consultation did not spend exactly one stacked AP: balance%d err%v", balance, err)
}
if level := p.friendshipService.CurrentLevel(1002); level != 2 {
t.Fatalf("consultation progress was lost or applied twice: level%d", level)
}
})
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.eventEconomy.Apply(ctx, "stacked-counseling-second-supply", nil, []gamedata.Reward{{Type: 72, Count: 1}}); err != nil {
t.Fatal(err)
}
})
if _, err := s.execute("/FriendshipCounseling", counsel(34, 1002)); err == nil {
t.Fatal("daily costume limit allowed a repeated consultation")
}
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
balance, err := p.eventEconomy.CurrencyBalance(ctx, 72)
if err != nil || balance != 1 {
t.Fatalf("rejected repeated consultation consumed stacked AP: balance%d err%v", balance, err)
}
})
info := s.protocol(t, "/FriendshipInfo", wire.AppendVarint(nil, 1, 35))
var completed bool
if err := wire.Walk(info, func(field wire.Field) error {
if field.Number == 2 {
id, _, err := wire.Varint(field.Value, 1)
if err != nil {
return err
}
if id == 1002 {
completed = true
}
}
return nil
}); err != nil {
t.Fatal(err)
}
if !completed {
t.Fatal("reentering friendship lost the completed consultation story")
}
}
func newFriendshipScenario(t *testing.T) *trapPlayerScenario {
t.Helper()
factory, accounts := newIntegrationFactory(t)
owner, err := factory.open(accounts[0])
if err != nil {
t.Fatal(err)
}
s := &trapPlayerScenario{factory: factory, owner: owner, account: accounts[0]}
t.Cleanup(func() {
if err := s.owner.Close(); err != nil {
t.Error(err)
}
})
return s
}
func friendshipEpisodeRequest(seq, group, id uint64) []byte {
return wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, seq), 2, group), 3, id)
}
func assertFriendshipDiamonds(t *testing.T, s *trapPlayerScenario, want uint64) {
t.Helper()
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
if got := p.wallet.Snapshot(ctx).FreeJewelry; got != want {
t.Fatalf("friendship story rewards: diamonds got%d want%d", got, want)
}
})
}
func assertFriendshipEpisodes(t *testing.T, s *trapPlayerScenario, group uint64, want ...uint64) {
t.Helper()
response := s.protocol(t, "/FriendshipSpecialEpisodeInfo", wire.AppendVarint(nil, 1, uint64(100+s.commands)))
completed := make(map[uint64]bool)
if err := wire.Walk(response, func(field wire.Field) error {
if field.Number != 1 {
return nil
}
gotGroup, _, err := wire.Varint(field.Value, 1)
if err != nil {
return err
}
id, _, err := wire.Varint(field.Value, 2)
if err != nil {
return err
}
if gotGroup != group || completed[id] {
t.Fatalf("wrong or repeated story completion: group%d episode%d", gotGroup, id)
}
completed[id] = true
return nil
}); err != nil {
t.Fatal(err)
}
if len(completed) != len(want) {
t.Fatalf("saved stories got%v want%v", completed, want)
}
for _, id := range want {
if !completed[id] {
t.Fatalf("completed story%d lost after reopening", id)
}
}
}
@@ -0,0 +1,99 @@
//go:build integration
package app
import (
"encoding/json"
"testing"
"bd2server/internal/server/domain/command"
)
// PassInfo.GetPassTableList includes schedule-free newbie passes. Current
// GameData pass76/step1 starts at level1 with box510031, which opens costume3303;
// level2 requires65 EXP. Homescreen mission3038 contributes10 EXP when claimed.
func TestGuidePassClaimsAndExperienceSurviveWithoutEventCalendarEntry(t *testing.T) {
g := newMissionGameplay(t)
passInfo := func() []byte { return g.call("/PassInfo", nil) }
assertExperience := func(want uint64) {
t.Helper()
for _, row := range appRows(passInfo(), 1) {
if appValue(row, 1) == 76 {
if appValue(row, 2) != want {
t.Fatalf("guide pass lost earned EXP: got%d want%d", appValue(row, 2), want)
}
return
}
}
t.Fatal("native guide pass missing without a seasonal calendar entry")
}
reward := func(pass, level uint64) []byte {
return append(appScalar(3, pass), appScalar(4, level)...)
}
assertExperience(0)
if _, owned := g.owner.assembly.collection.CostumeByID(3303); owned {
t.Fatal("guide reward costume already owned before the first guide reward")
}
if _, err := g.execute("/PassReward", reward(77, 1)); err == nil {
t.Fatal("step2 pass rewarded while only step1 was unlocked")
}
if _, err := g.execute("/PassReward", reward(76, 2)); err == nil {
t.Fatal("guide level2 rewarded without its65 EXP")
}
row := append(appScalar(1, 303), appScalar(2, 3038)...)
row = append(row, appScalar(3, 1)...)
row = append(row, appScalar(4, 7001)...)
g.call("/MissionUpdate", appMessage(2, row))
claim := append(appScalar(3, 2), appScalar(4, 303)...)
claim = append(claim, appScalar(5, 3038)...)
claim = append(claim, appScalar(6, 7001)...)
g.call("/MissionClear", claim)
assertExperience(10)
// Reproduce the previous server's missing derived pass ledger while retaining
// the mission reward receipt that independently proves the earned EXP.
s := &trapPlayerScenario{owner: g.owner, account: g.account}
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
raw, err := p.gameplayStore.Load(ctx.State, "eventtasks")
if err != nil {
t.Fatal(err)
}
var state map[string]json.RawMessage
if err := json.Unmarshal(raw, &state); err != nil {
t.Fatal(err)
}
state["Passes"] = json.RawMessage(`{}`)
raw, err = json.Marshal(state)
if err != nil {
t.Fatal(err)
}
if err := p.gameplayStore.Save(ctx.State, "eventtasks", raw); err != nil {
t.Fatal(err)
}
})
g.reopen()
assertExperience(10)
assertExperience(10)
g.reopen()
assertExperience(10)
g.call("/PassReward", reward(76, 1))
costume, owned := g.owner.assembly.collection.CostumeByID(3303)
if !owned || costume.Level != 0 {
t.Fatal("guide level1 box failed to grant its initial costume")
}
g.reopen()
if _, err := g.execute("/PassReward", reward(76, 1)); err == nil {
t.Fatal("guide reward paid again after player reopen")
}
if after, owned := g.owner.assembly.collection.CostumeByID(3303); !owned || after.InvenIndex != costume.InvenIndex || after.Level != 0 {
t.Fatal("retry duplicated or enhanced the guide reward costume")
}
claimed := false
for _, row := range appRows(passInfo(), 2) {
if appValue(row, 1) == 76 && appValue(row, 2) == 1 && appValue(row, 3) == 1 {
claimed = true
}
}
if !claimed {
t.Fatal("native pass UI cannot restore the claimed level1 marker")
}
}
@@ -0,0 +1,133 @@
//go:build integration
package app
import (
"bytes"
"context"
"slices"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/design/schedule"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/runtime/player"
)
// GameData 20261012190548 LocalText 7900026 promises a single reward per
// board first clear; 7900084 requires every stage win; 7900122 resets run items.
// IbStageEndResponse and RewardDBInfoBundle field numbers are from the current
// extracted Proto.Net classes. This exercises the actual account transaction,
// economy and HTTP handler chain, including a failed multi-request command.
func TestIBFirstClearAccountTransactionAndRecovery(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
d := factory.design.ib
var seasons []uint64
for id := range d.Seasons {
seasons = append(seasons, id)
}
slices.Sort(seasons)
season := seasons[0]
var board gamedata.IBDungeon
for _, id := range d.Seasons[season] {
if candidate := d.Dungeons[id]; candidate.Unlock == 0 {
board = candidate
break
}
}
if board.ID == 0 || board.Reward.Type != 70 {
t.Fatal("selected design has no soul-board initial currency reward")
}
now := time.Now()
found := false
for n, content := range factory.options.calendars.RegularService.Contents {
if content.ID == 9 {
factory.options.calendars.RegularService.Contents[n].Current = schedule.Season{ID: season, StartMilliseconds: uint64(now.Add(-time.Hour).UnixMilli()), EndMilliseconds: uint64(now.Add(time.Hour).UnixMilli())}
found = true
break
}
}
if !found {
t.Fatal("calendar has no IB content")
}
owner, err := factory.open(accounts[0])
if err != nil {
t.Fatal(err)
}
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
t.Cleanup(func() {
if g.owner != nil {
if e := g.owner.Close(); e != nil {
t.Error(e)
}
}
})
balance := func() uint64 {
t.Helper()
tx, e := g.owner.repository.BeginCommand(context.Background())
if e != nil {
t.Fatal(e)
}
defer func() { _ = tx.Rollback() }()
currencies, e := g.owner.assembly.eventEconomy.AdditionalCurrencies(command.Context{State: tx})
if e != nil {
t.Fatal(e)
}
return currencies[71]
}
baseline := balance()
g.call("/IbMainInfo", nil)
entered := g.call("/IbDungeonEnter", appScalar(2, board.ID))
if len(appRows(entered, 2)) == 0 || len(appRows(entered, 3)) == 0 {
t.Fatal("handler chain did not create initial board inventory and deck")
}
for n, stage := range board.Stages {
request := append(appScalar(2, board.ID), appScalar(3, stage.ID)...)
started := g.call("/IbStageStart", request)
g.reopen()
if resumed := g.call("/IbStageStart", request); !bytes.Equal(started, resumed) {
t.Fatal("account reload changed battle process")
}
if n+1 < len(board.Stages) {
g.call("/IbStageEnd", appScalar(2, 1))
continue
}
failed := g.request("/IbStageEnd", appScalar(2, 1))
failed.Requests = append(failed.Requests, player.Request{Path: "/IbDungeonEnter", Body: append(appScalar(1, 9000), appScalar(2, 999999)...)})
g.execute(failed, true)
g.reopen()
if balance() != baseline {
t.Fatal("failed batch committed first-clear currency")
}
main := g.call("/IbMainInfo", nil)
play := appRows(main, 1)[0]
if appValue(play, 7) != 1 || appValue(play, 2) != stage.ID {
t.Fatal("failed batch lost the active final battle")
}
claim := g.request("/IbStageEnd", appScalar(2, 1))
paid := g.execute(claim, false)
if appValue(paid, 2) != 1 || appValue(paid, 3) != 1 || balance() != baseline+board.Reward.Count {
t.Fatal("first clear did not atomically credit the real account currency")
}
g.reopen()
if retry := g.execute(claim, false); !bytes.Equal(paid, retry) || balance() != baseline+board.Reward.Count {
t.Fatal("durable claim retry paid again or changed response")
}
}
if len(appRows(g.call("/IbItemInfo", nil), 1)) != 0 || len(appRows(g.call("/IbDeckInfo", nil), 1)) != 0 {
t.Fatal("board completion retained run inventory")
}
g.call("/IbDungeonEnter", appScalar(2, board.ID))
for _, stage := range board.Stages {
g.call("/IbStageStart", append(appScalar(2, board.ID), appScalar(3, stage.ID)...))
out := g.call("/IbStageEnd", appScalar(2, 1))
if appValue(out, 3) != 0 {
t.Fatal("rechallenge was marked first clear")
}
}
g.reopen()
if balance() != baseline+board.Reward.Count {
t.Fatal("rechallenge minted additional first-clear currency")
}
}
@@ -4,6 +4,8 @@ package app
import (
"encoding/binary"
"slices"
"strconv"
"testing"
"bd2server/internal/server/design/gamedata"
@@ -12,6 +14,93 @@ import (
"bd2server/internal/server/protocol/wire"
)
// MapPacket and MapFogController use eight ordered hexadecimal row masks;
// PackInGameInfo clears the local cache before restoring field 10.
func TestMapFogKeepsRevealedCellsAcrossAreaChangesAndAccountReopen(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
players := make([]*trapPlayerScenario, 2)
for i, account := range accounts {
s := &trapPlayerScenario{factory: factory, account: account, owner: openNicknamePlayer(t, factory, account)}
players[i] = s
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
if _, err := p.ownedItems.GrantOnce(ctx, "fog-pack-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
t.Fatal(err)
}
}
})
}
a, b := players[0], players[1]
reveal := func(s *trapPlayerScenario, pack, mapID uint64, rows ...string) {
t.Helper()
request := wire.AppendVarint(trapRequest(uint64(s.commands+1), pack), 3, mapID)
for _, row := range rows {
request = wire.AppendString(request, 4, row)
}
s.protocol(t, "/ActiveMap", request)
}
assertCells := func(s *trapPlayerScenario, pack uint64, expected map[uint64][]int) {
t.Helper()
entry := s.protocol(t, "/PackInGameInfo", trapRequest(uint64(s.commands+1), pack))
maps := appRows(entry, 10)
if len(maps) != len(expected) {
t.Fatalf("field entry restored %d explored maps, want %d", len(maps), len(expected))
}
seen := map[uint64]bool{}
for _, m := range maps {
id := appValue(m, 1)
wanted, exists := expected[id]
if !exists || seen[id] {
t.Fatalf("field entry restored unrelated or duplicated map %d", id)
}
seen[id] = true
rows := appRows(m, 2)
if len(rows) != 8 {
t.Fatal("native fog renderer requires all eight rows, including empty rows")
}
var cells []int
for r, text := range rows {
var mask uint64
if len(text) != 0 {
var err error
mask, err = strconv.ParseUint(string(text), 16, 8)
if err != nil {
t.Fatal(err)
}
}
for column := range 8 {
if mask&(1<<column) != 0 {
cells = append(cells, r*8+column)
}
}
}
if !slices.Equal(cells, wanted) {
t.Fatalf("map %d restored explored cells %v, want %v", id, cells, wanted)
}
}
}
assertCells(a, 5, nil)
reveal(a, 5, 55, "1", "", "", "", "1", "", "", "")
reveal(a, 5, 55, "3", "", "80", "", "1", "", "", "")
reveal(a, 5, 57, "", "2", "", "", "", "", "", "")
assertCells(a, 1, nil)
// The older upload arrives after the newer snapshot and after leaving the pack.
reveal(a, 5, 55, "1", "", "", "", "1", "", "", "")
wantA := map[uint64][]int{55: {0, 1, 23, 32}, 57: {9}}
assertCells(a, 5, wantA)
assertCells(b, 5, nil)
reveal(b, 5, 55, "", "", "", "", "", "", "", "80")
for _, s := range players {
closeNicknamePlayer(t, s.owner)
s.owner = openNicknamePlayer(t, factory, s.account)
}
assertCells(a, 5, wantA)
assertCells(b, 5, map[uint64][]int{55: {63}})
assertCells(a, 1, nil)
assertCells(a, 5, wantA)
}
// Current GameData pack5 has seven research points in map55, eight in map57,
// and six one-time chests in map52/group23. Native MapUI filters researched IDs
// by scene; PackMapRewardInfo builds map rows from PackDetailInfo's object IDs.
@@ -0,0 +1,129 @@
//go:build integration
package app
import (
"bytes"
"context"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/battle/monsterhunt"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
func TestMonsterHuntRankingSeasonRewardPaysActualPlaceAfterRollover(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
original, e := factory.design.source.MonsterHunt(75)
if e != nil {
t.Fatal(e)
}
// Synthetic season tiers exercise distinct payouts through the real economy.
design := *original
design.Ranks = map[uint64][]gamedata.MonsterHuntRankReward{1: {{ID: 1, Type: 0, Ranking: 1, Rewards: []gamedata.BattleReward{{Type: 4, Count: 11}}}, {ID: 2, Type: 0, Ranking: 2, Rewards: []gamedata.BattleReward{{Type: 4, Count: 5}}}}}
load := func(uint64) (*gamedata.MonsterHunt, error) { return &design, nil }
presets, e := gamedata.LoadMonsterHuntPresetDesign(factory.options.gameData, factory.options.gameDataVersion)
if e != nil {
t.Fatal(e)
}
now := time.Now()
playing := monsterhunt.Season{ID: 81, Hunt: 75, Start: uint64(now.Add(-time.Hour).UnixMilli()), End: uint64(now.Add(time.Hour).UnixMilli()), Calculate: uint64(now.Add(2 * time.Hour).UnixMilli()), RankGroup: 1}
factory.design.monsterHunt, e = monsterhunt.NewRules([]monsterhunt.Season{playing}, factory.seeds.defaults, presets, load)
if e != nil {
t.Fatal(e)
}
shared, e := openSharedRuntime(context.Background(), factory.options, factory.design)
if e != nil {
t.Fatal(e)
}
factory.shared, factory.pvpSource = shared, shared.pvp
scenarios := []*monsterHuntScenario{{factory: factory, account: accounts[0]}, {factory: factory, account: accounts[1]}}
for _, s := range scenarios {
s.open(t)
}
t.Cleanup(func() {
for _, s := range scenarios {
if s.owner != nil {
if e := s.owner.Close(); e != nil {
t.Error(e)
}
}
}
if e := shared.store.Close(); e != nil {
t.Error(e)
}
})
hp, e := design.HP(3)
if e != nil {
t.Fatal(e)
}
scenarios[0].battle(t, "alice-clear", 3, true, 100, hp)
scenarios[1].battle(t, "bob-clear", 3, true, 200, hp)
for _, s := range scenarios {
var publication monsterhunt.RankPublication
s.command(t, func(ctx command.Context) ([]byte, error) {
owner, e := s.owner.assembly.ProfileOwner(ctx)
if e != nil {
return nil, e
}
records, e := s.owner.assembly.monsterHuntService.RankRecords()
publication = monsterhunt.RankPublication{Account: s.account, Version: 1, Profile: monsterhunt.RankProfile{Owner: owner, Name: s.account}, Records: records}
return nil, e
})
if e := shared.huntRanks.Publish(context.Background(), publication); e != nil {
t.Fatal(e)
}
}
value := func(raw []byte, field int) uint64 { n, _, _ := wire.Varint(raw, field); return n }
query := func(s *monsterHuntScenario, path string, seq uint64) []byte {
return s.command(t, func(ctx command.Context) ([]byte, error) {
_, out, _, e := s.owner.assembly.monsterHuntService.Handle(ctx, path, wire.AppendVarint(nil, 1, seq))
return out, e
})
}
for i, s := range scenarios {
out := query(s, "/MonsterHuntUserInfo", 1)
if value(out, 2) != uint64(2-i) {
t.Fatal("user info fabricated first place instead of multiplayer rank")
}
}
before := []uint64{scenarios[0].assets(t).Wallet.Gold, scenarios[1].assets(t).Wallet.Gold}
// Closing one season and opening the next must retain the old pending reward.
playing.Start, playing.End, playing.Calculate = uint64(now.Add(-3*time.Hour).UnixMilli()), uint64(now.Add(-2*time.Hour).UnixMilli()), uint64(now.Add(-time.Hour).UnixMilli())
next := monsterhunt.Season{ID: 82, Hunt: 75, Start: uint64(now.Add(-time.Minute).UnixMilli()), End: uint64(now.Add(time.Hour).UnixMilli()), Calculate: uint64(now.Add(2 * time.Hour).UnixMilli()), RankGroup: 1}
factory.design.monsterHunt, e = monsterhunt.NewRules([]monsterhunt.Season{playing, next}, factory.seeds.defaults, presets, load)
if e != nil {
t.Fatal(e)
}
for i, s := range scenarios {
s.reopen(t)
info := query(s, "/MonsterHuntUserInfo", 2)
user, _, e := wire.Bytes(info, 1)
if e != nil || value(user, 1) != 82 || value(user, 10) != 1 {
t.Fatal("rollover lost pending season reward or replaced current season")
}
reward := query(s, "/MonsterHuntSeasonReward", 3)
if value(reward, 1) != uint64(2-i) {
t.Fatal("season payout used first place for both accounts")
}
want := uint64(5)
if i == 1 {
want = 11
}
if s.assets(t).Wallet.Gold != before[i]+want {
t.Fatal("rank tier was not credited to the player's actual wallet")
}
replay := query(s, "/MonsterHuntSeasonReward", 3)
if !bytes.Equal(reward, replay) {
t.Fatal("season reward receipt changed on retry")
}
s.reopen(t)
info = query(s, "/MonsterHuntUserInfo", 4)
user, _, _ = wire.Bytes(info, 1)
if value(user, 1) != 82 || value(user, 10) != 0 || s.assets(t).Wallet.Gold != before[i]+want {
t.Fatal("reopen lost claim, duplicated currency, or contaminated new season")
}
}
}
@@ -70,6 +70,15 @@ func (p *playerAssembly) attachAchievementProjection(provider *achievements.Owne
add(key[0], key[1], value)
}
}
if p.eventPlayService != nil {
values, err := p.eventPlayService.AchievementProgress(p.design.achievementCounterDesign)
if err != nil {
return err
}
for key, value := range values {
add(key[0], key[1], value)
}
}
if p.pvpService != nil {
for key, value := range p.pvpService.RecordedBattleCounts() {
add(key[0], key[1], value)
+1
View File
@@ -39,6 +39,7 @@ func (p *playerAssembly) assets(ctx command.Context) error {
if err := p.ownedItems.AttachItemStacks(p.design.itemStacks); err != nil {
return err
}
p.ownedItems.AttachPrestigeIllustrations(p.design.prestigeCatalog.Illustrations)
if p.initializeAccount {
if err := p.ownedItems.InitializeItems(ctx, p.starter.OwnedItems); err != nil {
return fmt.Errorf("initialize owned item seed: %w", err)
@@ -0,0 +1,78 @@
package app
import (
"bd2server/internal/server/domain/battle/castle"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/storage/outbox"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
)
func (p *playerAssembly) publishCastleRanking(ctx command.Context) error {
if p.shared == nil || p.shared.castleRanks == nil {
return nil
}
owner, err := p.ProfileOwner(ctx)
if err != nil {
return err
}
records, err := p.castleService.RankRecords(ctx)
if err != nil || len(records) == 0 {
return err
}
profile, err := p.PublicProfile(ctx, owner)
if err != nil {
return err
}
xp, err := p.missionService.AchievementExperience()
if err != nil {
return err
}
next := castle.RankPublication{Account: ctx.AccountID, Records: records, Profile: castle.RankProfile{
Owner: owner, Name: profile.UserID, XP: xp, Portrait: profile.PortraitCostumeID, PortraitDesign: profile.PortraitDesignID, Title: profile.TitleID, Guild: profile.GuildBase,
}}
oldRaw, found, err := ctx.State.LoadEntry("directory", "castle_publication", "current")
if err != nil {
return err
}
if found {
var old castle.RankPublication
if err := json.Unmarshal(oldRaw, &old); err != nil {
return err
}
next.Version = old.Version
raw, err := json.Marshal(next)
if err != nil {
return err
}
if bytes.Equal(raw, oldRaw) {
return nil
}
}
if next.Version == ^uint64(0) {
return errors.New("castle publication version exhausted")
}
next.Version++
raw, err := json.Marshal(next)
if err != nil {
return err
}
if err := ctx.Publish(command.Event{ID: fmt.Sprintf("castle-ranking:%d", next.Version), Topic: "castle.ranking", Payload: raw}); err != nil {
return err
}
return ctx.State.PutEntry("directory", "castle_publication", "current", raw)
}
func (s *sharedRuntime) consumeCastleRanking(ctx context.Context, event outbox.Pending) error {
var publication castle.RankPublication
if err := json.Unmarshal(event.Envelope.Event.Payload, &publication); err != nil {
return err
}
if publication.Account != event.Envelope.Source {
return errors.New("castle ranking source mismatch")
}
return s.castleRanks.Publish(ctx, publication)
}
+12 -16
View File
@@ -34,6 +34,7 @@ func (p *playerAssembly) events(ctx command.Context) error {
if err != nil {
return fmt.Errorf("load random box state: %w", err)
}
p.boxService.AttachResourceItems(p.design.resourceItems)
p.eventPlayService, err = eventplay.Open(ctx, p.gameplayStore, p.design.eventPlay, func(id uint64) (*gamedata.EventField, error) {
return p.design.source.EventField(p.design.eventPlay, id)
}, p.eventRegistry, p.eventEconomy)
@@ -41,6 +42,13 @@ func (p *playerAssembly) events(ctx command.Context) error {
return fmt.Errorf("load event play state: %w", err)
}
p.eventPlayService.AttachBattleChallenges(p.design.eventBattleChallenges)
p.eventPlayService.AttachBattleCostumes(func(command.Context) map[uint64]bool {
owned := make(map[uint64]bool)
for _, costume := range p.collection.Costumes() {
owned[costume.ID] = true
}
return owned
})
if p.shared != nil {
p.eventPlayService.AttachArcadeRankings(p.shared.arcadeRanks, p.arcadeRankingProfile)
p.eventPlayService.AttachRankingGuilds(p.arcadeRankingGuilds)
@@ -83,14 +91,7 @@ func (p *playerAssembly) events(ctx command.Context) error {
if err = p.eventActionsService.AttachMiniContent(ctx, p.eventPlayService, p.design.miniContent); err != nil {
return fmt.Errorf("attach mini event content: %w", err)
}
p.eventActionsService.AttachFriendshipLevel(func(id uint64) uint64 {
for _, entry := range p.collection.FriendshipEntries() {
if entry.State != nil && entry.State.CostumeID == id {
return entry.State.Level
}
}
return 0
})
p.eventActionsService.AttachFriendshipLevel(p.friendshipService.CurrentLevel)
p.eventActionsService.AttachChargeInfo(func(ctx command.Context) ([]byte, error) {
rows, err := p.eventEconomy.ChargeInfo(ctx)
if err != nil {
@@ -111,17 +112,12 @@ func (p *playerAssembly) events(ctx command.Context) error {
return rows, nil
})
p.eventActionsService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error {
if err := p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked); err != nil {
return err
}
return p.eventTasksService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
return p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
})
p.eventPlayService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error {
if err := p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked); err != nil {
return err
}
return p.eventTasksService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
return p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
})
p.eventPlayService.AttachRhythmResult(p.eventTasksService.RecordRhythmResult)
p.eventTasksService.AttachAssociatedMissionGroup(func(schedule events.Schedule) uint64 {
if group := p.eventActionsService.AssociatedMissionGroup(schedule); group != 0 {
return group
+23 -1
View File
@@ -3,6 +3,7 @@ package app
import (
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/runtime/player"
accountstate "bd2server/internal/server/storage/account"
"bd2server/internal/server/storage/outbox"
@@ -172,6 +173,7 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
if !changed {
return cause
}
slog.Warn("player command rollback requires session renewal", "account_id", p.accountID, "error", cause)
p.assembly = nil
if recoveryErr := p.Recover(context.WithoutCancel(ctx)); recoveryErr != nil {
return player.Failure{Cause: errors.Join(cause, recoveryErr), RecoveryRequired: true}
@@ -237,7 +239,8 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
}
}
if err != nil {
return reply, failCommand(err)
sequence, _, _ := wire.Varint(item.Body, 1)
return reply, failCommand(&command.RequestError{Path: item.Path, Sequence: sequence, Cause: err})
}
reply.Responses = append(reply.Responses, response)
@@ -252,6 +255,9 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
if err := assembly.publishHuntRanking(identity); err != nil {
return reply, failCommand(err)
}
if err := assembly.publishCastleRanking(identity); err != nil {
return reply, failCommand(err)
}
}
if isLogin || friendProfileChanged(request.Requests) {
if err := assembly.publishFriendProfile(identity, isLogin); err != nil {
@@ -301,6 +307,19 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
}
func (p *playerAssembly) dispatch(ctx command.Context, path string, request []byte) (int, []byte, error) {
if (path == "/PopularCostumeInfo" || path == "/PopularEquipInfo") && p.shared != nil {
return p.shared.popularInfo(ctx, path, request, time.Now())
}
if path == "/UserRelayInfoUpdate" {
seq, found, err := wire.Varint(request, 1)
if err != nil || !found || seq == 0 || ctx.AccountID == "" || ctx.SessionID == "" || ctx.State == nil {
return 506, nil, fmt.Errorf("relay: invalid authenticated refresh")
}
if err := p.publishFriendProfile(ctx, false); err != nil {
return 506, nil, err
}
return 506, nil, p.publishDirectory(ctx)
}
for _, handler := range p.handlers {
code, body, handled, err := handler.Handle(ctx, path, request)
if handled || err != nil {
@@ -324,6 +343,9 @@ func (p *playerAssembly) beginLogin(ctx command.Context) error {
hook.BeginLogin(ctx)
}
}
if err := p.eventTasksService.ReconcileRhythmResults(ctx, p.eventPlayService.CompletedRhythmResults()); err != nil {
return err
}
return p.missionService.RecordLogin(ctx, p.worldService.MissionsUnlocked)
}
+18 -6
View File
@@ -2,15 +2,20 @@ package app
import (
"bd2server/internal/server/domain/battle"
"bd2server/internal/server/domain/battle/castle"
"bd2server/internal/server/domain/battle/hunting"
"bd2server/internal/server/domain/battle/ib"
"bd2server/internal/server/domain/battle/monsterhunt"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/battle/roguelike"
"bd2server/internal/server/domain/cafeteria"
"bd2server/internal/server/domain/chat"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/commerce"
"bd2server/internal/server/domain/commerce/gacha"
"bd2server/internal/server/domain/commerce/npcinn"
"bd2server/internal/server/domain/commerce/npcshop"
"bd2server/internal/server/domain/dating"
"bd2server/internal/server/domain/events"
"bd2server/internal/server/domain/events/actions"
"bd2server/internal/server/domain/events/exchange"
@@ -19,6 +24,7 @@ import (
"bd2server/internal/server/domain/events/tasks"
"bd2server/internal/server/domain/fishing"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/life"
"bd2server/internal/server/domain/mail"
"bd2server/internal/server/domain/profile"
"bd2server/internal/server/domain/progression/achievements"
@@ -60,11 +66,17 @@ type PlayerFactory struct {
}
type playerAssembly struct {
fishingService *fishing.Service
pvpService *pvp.Service
worldSeed world.Seed
mailbox *mail.Starter
deckSeed deck.Seed
cafeteriaService *cafeteria.Service
datingService *dating.Service
castleService *castle.Service
ibService *ib.Service
rogueLikeService *roguelike.Service
lifeService *life.Service
fishingService *fishing.Service
pvpService *pvp.Service
worldSeed world.Seed
mailbox *mail.Starter
deckSeed deck.Seed
*PlayerFactory
progressState *progress.Store
deckStateStore *deck.Store
@@ -225,7 +237,7 @@ func (f *PlayerFactory) assemble(ctx context.Context, accountID string, reposito
}()
identity := command.Context{Identity: command.Identity{AccountID: accountID, SessionID: "startup", RequestID: "initialize"}, Cancellation: ctx, State: startupTransaction}
for _, assemble := range []func(command.Context) error{p.assets, p.worldRoster, p.gameplay, p.commerce, p.events, p.session} {
for _, assemble := range []func(command.Context) error{p.assets, p.worldRoster, p.gameplay, p.commerce, p.events, p.optionalGameplay, p.openIB, p.rogueLike, p.session} {
if err := assemble(identity); err != nil {
return nil, err
}
@@ -90,6 +90,7 @@ func (p *playerAssembly) gameplay(ctx command.Context) error {
return fmt.Errorf("load event economy: %w", err)
}
p.eventEconomy.AttachHuntingAP(p.huntingService)
p.friendshipService.AttachEconomy(p.eventEconomy)
if err = p.worldService.AttachSkyWay(ctx, p.design.skyway, p.gameplayStore, p.eventEconomy, p.huntingService, p.design.skywaySchedules, p.design.rewardGraph); err != nil {
return fmt.Errorf("attach SkyWay: %w", err)
}
@@ -113,6 +114,8 @@ func (p *playerAssembly) gameplay(ctx command.Context) error {
return fmt.Errorf("attach overwhelm design: %w", err)
}
p.talentUseService.AttachEffect(4, p.worldService.ApplyTalentFieldAbsorb)
p.talentUseService.AttachEffect(15, p.worldService.ApplyTalentWaypoint)
p.deckStateStore.AttachWaypointTalent(p.talentUseService.ConsumeWaypoint)
p.talentUseService.AttachEffect(20, p.worldService.ApplyTalentMonsterSummon)
p.dispatchService, err = roster.OpenTalentDispatch(p.gameplayStore, p.design.dispatchDesign, p.eventEconomy)
if err != nil {
+47
View File
@@ -0,0 +1,47 @@
package app
import (
"fmt"
"time"
"bd2server/internal/server/design/schedule"
"bd2server/internal/server/domain/battle/ib"
"bd2server/internal/server/domain/command"
)
func (p *playerAssembly) openIB(ctx command.Context) error {
var err error
p.ibService, err = ib.Open(ctx, p.gameplayStore, p.design.ib, p.eventEconomy, ib.Options{CostumeLevel: func(_ command.Context, id uint64) (uint64, error) {
costume, owned := p.collection.CostumeByID(id)
if !owned {
return 0, nil
}
return uint64(costume.Level), nil
}, Period: func(command.Context) (ib.Period, error) {
calendar := p.options.calendars.RegularService
if calendar == nil {
return ib.Period{}, fmt.Errorf("ib: missing regular calendar")
}
var regular uint64
for _, entry := range calendar.Regular {
if entry.ContentID == 9 {
regular = entry.Season
break
}
}
now := uint64(time.Now().UnixMilli())
for _, content := range calendar.Contents {
if content.ID != 9 {
continue
}
for _, season := range []schedule.Season{content.Current, content.Next} {
if now >= season.StartMilliseconds && now < season.EndMilliseconds {
return ib.Period{Season: season.ID, Regular: regular, Open: !season.Error}, nil
}
}
return ib.Period{Season: content.Current.ID, Regular: regular}, nil
}
return ib.Period{}, fmt.Errorf("ib: missing content calendar")
}})
return err
}
@@ -0,0 +1,37 @@
package app
import "bd2server/internal/server/domain/command"
func (p *playerAssembly) interactionAvailable(ctx command.Context, group uint64) (bool, error) {
for _, access := range p.design.interaction.Access[group] {
if access.Prestige != 0 {
for _, item := range p.ownedItems.All(ctx) {
if item.Type == 45 && item.ID == access.Prestige && item.Count != 0 {
return true, nil
}
}
continue
}
if access.Costume != 0 {
if _, owned := p.collection.CostumeByID(access.Costume); owned {
return true, nil
}
continue
}
switch access.Provide {
case 0:
return true, nil
case 1:
if p.worldService.PackAvailable(ctx, access.Pack) {
return true, nil
}
case 2:
for _, item := range p.ownedItems.All(ctx) {
if item.Type == 25 && item.ID == access.Item && item.Count != 0 {
return true, nil
}
}
}
}
return false, nil
}
@@ -0,0 +1,133 @@
package app
import (
"encoding/json"
"fmt"
"slices"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/design/schedule"
"bd2server/internal/server/domain/battle/castle"
"bd2server/internal/server/domain/cafeteria"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/dating"
"bd2server/internal/server/domain/life"
"bd2server/internal/server/domain/roster/deck"
)
func (p *playerAssembly) optionalGameplay(ctx command.Context) error {
var err error
p.lifeService, err = life.Open(ctx, p.design.life, life.Options{ValidateAvatar: func(ctx command.Context, raw []byte) error {
if p.avatarService == nil {
return fmt.Errorf("life: avatar service unavailable")
}
return p.avatarService.ValidateAppearance(ctx, raw)
}})
if err != nil {
return fmt.Errorf("open life: %w", err)
}
p.eventEconomy.AttachLife(p.lifeService)
if err := p.eventEconomy.AttachDatingAP(p.design.dating.Default.V(5)); err != nil {
return err
}
p.datingService, err = dating.Open(ctx, p.gameplayStore, p.design.dating, p.eventEconomy)
if err != nil {
return fmt.Errorf("open dating: %w", err)
}
p.cafeteriaService, err = cafeteria.Open(ctx, p.gameplayStore, p.design.cafeteria, p.eventEconomy)
if err != nil {
return fmt.Errorf("open cafeteria: %w", err)
}
p.datingService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
p.cafeteriaService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
p.cafeteriaService.AttachOwnedCostumes(func() []uint64 {
var ids []uint64
for _, costume := range p.collection.Costumes() {
ids = append(ids, costume.ID)
}
return ids
})
p.cafeteriaService.AttachDatingHasEpisode(p.datingService.HasEpisode)
p.datingService.AttachFirstMeeting(p.cafeteriaService.CanMeet)
p.castleService = castle.NewService(p.design.castle)
p.castleService.AttachTotalWarTextCheck(p.checkProfileText)
if err := p.castleService.AttachTotalWarRuntime(p.worldService.CharacterService(), p.collection, p.ownedEquipment, p.wallet); err != nil {
return err
}
if err := p.login.AttachTotalWarSlots(p.castleService.TotalWarPresetSlotCount); err != nil {
return err
}
p.castleService.AttachTotalWarCompletion(func(ctx command.Context, identity string, score uint64, costumes []uint64) error {
owner, err := p.ProfileOwner(ctx)
if err != nil {
return err
}
payload, err := json.Marshal(deck.PopularityPublication{CompletedAt: uint64(time.Now().UnixMilli()), Score: score, OwnerIndex: owner, TotalWarCostumes: append([]uint64(nil), costumes...)})
if err != nil {
return err
}
return ctx.Publish(command.Event{ID: "totalwar:" + identity, Topic: deck.PopularityTopic, Payload: payload})
})
p.castleService.AttachCurrentPack(p.worldService.CurrentPackID)
p.castleService.AttachEvidence(p.battleService.SettlementEvidence)
p.castleService.AttachRewards(func(ctx command.Context, identity string, rewards []gamedata.Reward) ([]byte, error) {
return p.eventEconomy.Apply(ctx, identity, nil, rewards)
})
p.castleService.AttachSeasonSettlement(func(id uint64) bool {
calendar := p.options.calendars.RegularService
if calendar == nil {
return false
}
now := uint64(time.Now().UnixMilli())
for _, content := range calendar.Contents {
if content.ID != 2 {
continue
}
for _, season := range []schedule.Season{content.Current, content.Next} {
if season.ID == id {
return !season.Error && now >= season.EndMilliseconds+calendar.CalculateMilliseconds
}
}
return id < content.Current.ID
}
return false
})
p.castleService.AttachPeriod(func(command.Context) (uint64, bool, error) {
if p.options.calendars.RegularService == nil {
return 0, false, fmt.Errorf("castle: missing regular calendar")
}
now := uint64(time.Now().UnixMilli())
for _, content := range p.options.calendars.RegularService.Contents {
if content.ID != 2 {
continue
}
for _, season := range []schedule.Season{content.Current, content.Next} {
if now >= season.StartMilliseconds && now < season.EndMilliseconds && !season.Error {
return season.ID, true, nil
}
}
return content.Current.ID, false, nil
}
return 0, false, fmt.Errorf("castle: missing season")
})
p.castleService.AttachTotalWarValidation(func(ctx command.Context, participants []castle.Participant) error {
for _, participant := range participants {
costume, owned := p.collection.CostumeByIndex(participant.CostumeIndex)
if !owned || costume.ID != participant.CostumeID {
return fmt.Errorf("castle: total war costume unavailable")
}
character, owned := p.worldService.CharacterService().Find(ctx, participant.CharacterIndex)
if !owned || character.ID != participant.CharacterID {
return fmt.Errorf("castle: total war character unavailable")
}
definition, found := p.design.regularGacha.Character(costume.ID)
if !found || definition.ID != character.ID && !slices.Contains(definition.GrowthCharacterIDs, character.ID) {
return fmt.Errorf("castle: costume belongs to a different character")
}
}
return nil
})
p.battleService.AttachEventBattle(p.castleService)
return nil
}
+172
View File
@@ -0,0 +1,172 @@
package app
import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/design/schedule"
"bd2server/internal/server/domain/battle/roguelike"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/outbox"
"context"
"encoding/json"
"fmt"
"time"
)
func (s *sharedRuntime) consumeRogueRanking(ctx context.Context, event outbox.Pending) error {
var p roguelike.RankPublication
if e := json.Unmarshal(event.Envelope.Event.Payload, &p); e != nil {
return e
}
if p.Account != event.Envelope.Source {
return fmt.Errorf("roguelike: ranking source mismatch")
}
return s.rogueRanks.Publish(ctx, p)
}
func (p *playerAssembly) rogueLike(ctx command.Context) error {
owner, e := p.ProfileOwner(ctx)
if e != nil {
return e
}
service, e := roguelike.Open(p.gameplayStore, p.design.roguelike, roguelike.Options{Access: func(ctx command.Context) error {
rule := p.design.roguelike.Open
xp, e := p.missionService.AchievementExperience()
if e != nil {
return e
}
if p.design.levelDesign.Level(xp) < rule.SquadLevel {
return fmt.Errorf("roguelike: squad level locked")
}
if rule.TicketID > 0 {
found := false
for _, i := range p.ownedItems.All(ctx) {
if i.Type == 19 && i.ID == rule.TicketID && i.Count > 0 {
found = true
}
}
if !found {
return fmt.Errorf("roguelike: content locked")
}
}
return nil
}, Economy: p.eventEconomy, Owner: owner, Evidence: p.battleService.SettlementEvidence,
CostumeOwned: func(id uint64) bool {
_, owned := p.collection.CostumeByID(id)
return owned
},
SeasonSettled: func(id uint64) bool {
calendar := p.options.calendars.RegularService
if calendar == nil {
return false
}
now := uint64(time.Now().UnixMilli())
for _, content := range calendar.Contents {
if content.ID != 5 {
continue
}
for _, season := range []schedule.Season{content.Current, content.Next} {
if season.ID == id {
return !season.Error && now >= season.EndMilliseconds+calendar.CalculateMilliseconds
}
}
return id < content.Current.ID
}
return false
},
Period: func(command.Context) (roguelike.Period, error) {
calendar := p.options.calendars.RegularService
if calendar == nil {
return roguelike.Period{}, fmt.Errorf("roguelike: calendar unavailable")
}
now := uint64(time.Now().UnixMilli())
var regular uint64
for _, r := range calendar.Regular {
if r.ContentID == 5 {
regular = r.Season
}
}
for _, c := range calendar.Contents {
if c.ID != 5 {
continue
}
for _, s := range []schedule.Season{c.Current, c.Next} {
if now >= s.StartMilliseconds && now < s.EndMilliseconds && !s.Error {
return roguelike.Period{Season: s.ID, Regular: regular, Active: true}, nil
}
}
return roguelike.Period{Season: c.Current.ID, Regular: regular}, nil
}
return roguelike.Period{}, fmt.Errorf("roguelike: missing schedule")
},
Tickets: func(ctx command.Context, key string, count uint64) error {
free, e := p.eventEconomy.CurrencyBalance(ctx, 35)
if e != nil {
return e
}
var costs []gamedata.Reward
if use := min(free, count); use > 0 {
costs = append(costs, gamedata.Reward{Type: 35, Count: use})
count -= use
}
if count > 0 {
costs = append(costs, gamedata.Reward{Type: 38, Count: count})
}
_, e = p.eventEconomy.Apply(ctx, key+":tickets", costs, nil)
return e
},
Health: func(ctx command.Context, c gamedata.RogueCostume, growth float64) (uint64, error) {
contributions, e := p.pictorialService.Contributions(ctx)
if e != nil {
return 0, e
}
awake, e := p.charAwakeService.Contributions(ctx, roster.Character{ID: c.Character})
if e != nil {
return 0, e
}
contributions = append(contributions, awake...)
contributions = append(contributions, gamedata.StatContribution{Stat: gamedata.StatHealth, Percent: growth})
hp := gamedata.AggregateStats(gamedata.BaseStats{Health: float64(c.Health)}, contributions).Health
return uint64(hp), nil
},
Ranking: p.rogueRanking(),
Publish: func(ctx command.Context, season, score, damage, version uint64) error {
profile, e := p.PublicProfile(ctx, owner)
if e != nil {
return e
}
xp, e := p.missionService.AchievementExperience()
if e != nil {
return e
}
raw := wire.AppendString(nil, 2, profile.UserID)
raw = wire.AppendVarint(raw, 3, xp)
raw = wire.AppendVarint(raw, 4, profile.PortraitCostumeID)
raw = wire.AppendVarint(raw, 5, profile.PortraitDesignID)
raw = wire.AppendVarint(raw, 9, profile.TitleID)
if len(profile.GuildBase) > 0 {
raw = wire.AppendBytes(raw, 6, profile.GuildBase)
}
payload, e := json.Marshal(roguelike.RankPublication{Account: ctx.AccountID, Season: season, Version: version, Entry: roguelike.RankEntry{Owner: owner, Score: score, Damage: damage, Profile: raw}})
if e != nil {
return e
}
return ctx.Publish(command.Event{ID: fmt.Sprintf("roguelike-rank:%d:%d", season, version), Topic: "roguelike.ranking", Payload: payload})
},
})
if e != nil {
return e
}
p.rogueLikeService = service
p.battleService.AttachEventBattle(service)
return nil
}
func (p *playerAssembly) rogueRanking() roguelike.Ranking {
if p.shared == nil {
return nil
}
return p.shared.rogueRanks
}
+13
View File
@@ -8,6 +8,7 @@ import (
"bd2server/internal/server/domain/events"
"bd2server/internal/server/domain/notice"
"bd2server/internal/server/domain/profile"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/gateway/session"
"bd2server/internal/server/protocol/defaults"
@@ -26,6 +27,7 @@ func (p *playerAssembly) session(ctx command.Context) error {
return err
}
p.monsterHuntService.AttachRanking(owner, p.shared.huntRanks)
p.castleService.AttachRanking(owner, p.shared.castleRanks)
}
if err := p.nickname(ctx); err != nil {
return err
@@ -47,6 +49,17 @@ func (p *playerAssembly) session(ctx command.Context) error {
return fmt.Errorf("restore recorded achievement history: %w", err)
}
p.handlers = []session.Handler{
p.lifeService,
p.cafeteriaService,
p.datingService,
p.castleService,
p.ibService,
p.rogueLikeService,
notice.CommunityService{Store: p.gameplayStore, Design: p.design.community, Board: p.options.notices, Economy: p.eventEconomy},
roster.InteractionService{Store: p.gameplayStore, Design: p.design.interaction, Authorize: p.interactionAvailable, Grant: func(ctx command.Context, key string, rewards []gamedata.Reward) ([]byte, error) {
return p.eventEconomy.Apply(ctx, key, nil, rewards)
}},
p.interactionRecords(),
p.chatService,
p.nicknameService,
p.avatarService,
+7
View File
@@ -40,6 +40,13 @@ func executePlayerSystem(ctx context.Context, registry *playerRegistry, account
func (instance *playerInstance) executeSystem(ctx command.Context, tx *accountstate.CommandStore, request *player.SystemRequest) ([]byte, error) {
p := instance.assembly
if request.Kind == player.ReadSpineRecording {
var input spineRecordingDownload
if err := json.Unmarshal(request.Body, &input); err != nil {
return nil, err
}
return p.interactionRecords().LoadRecordData(ctx, input.ID, input.Token)
}
if request.Kind == player.StoryCheckpoint {
var input world.StoryCheckpointRequest
if err := json.Unmarshal(request.Body, &input); err != nil {
+21 -18
View File
@@ -30,24 +30,27 @@ type textField struct {
}
var playerTextFields = map[string][]textField{
"/UserNicknameChange": {{"nickname", 74, []int{2}}},
"/UserGreetingChange": {{"greeting", 219, []int{2}}},
"/MasterTitleInfoUpdate": {{"master_title", 592, []int{2}}},
"/PresetSave": {{"preset_name", 179, []int{2, 1}}},
"/PresetInfoChange": {{"preset_name", 278, []int{2}}},
"/EquipPresetSave": {{"equipment_preset_name", 254, []int{4}}},
"/EquipPresetNameChange": {{"equipment_preset_name", 259, []int{4}}},
"/EquipMarkSet": {{"equipment_mark", 396, []int{3}}},
"/MonsterHuntPresetSave": {{"monster_hunt_preset_name", 406, []int{2, 1}}},
"/MonsterHuntPresetInfoChange": {{"monster_hunt_preset_name", 0, []int{2}}},
"/GuildRaidPresetSave": {{"guild_raid_preset_name", 404, []int{2, 1}}},
"/GuildRaidPresetInfoChange": {{"guild_raid_preset_name", 0, []int{2}}},
"/ColosseumPresetSave": {{"colosseum_preset_name", 494, []int{2, 1}}},
"/ColosseumPresetInfoChange": {{"colosseum_preset_name", 497, []int{2}}},
"/GuildCreate": {{"guild_name", 296, []int{2}}, {"guild_message", 296, []int{5}}},
"/GuildInfoEdit": {{"guild_message", 305, []int{4}}},
"/GuildNameChange": {{"guild_name", 570, []int{2}}},
"/GuildNoticeUpdate": {{"guild_notice", 382, []int{2}}},
"/UserNicknameChange": {{"nickname", 74, []int{2}}},
"/UserGreetingChange": {{"greeting", 219, []int{2}}},
"/MasterTitleInfoUpdate": {{"master_title", 592, []int{2}}},
"/PresetSave": {{"preset_name", 179, []int{2, 1}}},
"/PresetInfoChange": {{"preset_name", 278, []int{2}}},
"/EquipPresetSave": {{"equipment_preset_name", 254, []int{4}}},
"/EquipPresetNameChange": {{"equipment_preset_name", 259, []int{4}}},
"/EquipMarkSet": {{"equipment_mark", 396, []int{3}}},
"/MonsterHuntPresetSave": {{"monster_hunt_preset_name", 406, []int{2, 1}}},
"/MonsterHuntPresetInfoChange": {{"monster_hunt_preset_name", 0, []int{2}}},
"/GuildRaidPresetSave": {{"guild_raid_preset_name", 404, []int{2, 1}}},
"/GuildRaidPresetInfoChange": {{"guild_raid_preset_name", 0, []int{2}}},
"/ColosseumPresetSave": {{"colosseum_preset_name", 494, []int{2, 1}}},
"/ColosseumPresetInfoChange": {{"colosseum_preset_name", 497, []int{2}}},
"/TotalWarDeckPresetSave": {{"total_war_preset_name", 240, []int{2, 2}}},
"/TotalWarPresetInfoChange": {{"total_war_preset_name", 0, []int{2}}},
"/GuildCreate": {{"guild_name", 296, []int{2}}, {"guild_message", 296, []int{5}}},
"/GuildInfoEdit": {{"guild_message", 305, []int{4}}},
"/GuildNameChange": {{"guild_name", 570, []int{2}}},
"/GuildNoticeUpdate": {{"guild_notice", 382, []int{2}}},
"/SpineInteractionRecordNameUpdate": {{"spine_record_name", 576, []int{3}}},
}
func hasPlayerText(requests []player.Request) bool {
@@ -68,6 +68,9 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
}
p.gachaService.AttachInventory(p.ownedItems)
p.gachaService.AttachEquipmentGacha(p.design.equipmentGacha, p.ownedEquipment)
if err := p.gachaService.AttachStatistics(p.design.collectionStatistics); err != nil {
return err
}
p.gachaService.AttachDrawMission(func(ctx command.Context, count uint64) error {
return p.missionService.RecordEvent(ctx, missions.ConditionGachaBuy, 0, count, p.worldService.MissionsUnlocked)
})
@@ -174,7 +177,7 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
if err != nil {
return err
}
p.friendshipService, err = roster.NewFriendshipService(&p.design.friendshipDesign, p.design.charAwakeDesign, p.design.costumePotentialDesign, p.collection, p.ownedItems, p.wallet)
p.friendshipService, err = roster.NewFriendshipService(&p.design.friendshipDesign, p.design.charAwakeDesign, p.design.costumePotentialDesign, p.collection, p.ownedItems)
if err != nil {
return fmt.Errorf("load friendship state: %w", err)
}
@@ -0,0 +1,126 @@
//go:build integration
package app
import (
"bytes"
"context"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
// Current GameData links prestige 65193 to lobby illustration274 and prestige
// 3892 to135. Ordinary illustration32 is a dating reward, not a costume grant.
// Native MenuUI builds its interaction button from ItemInfo's Type25 rows.
func TestOwnedPrestigeUnlocksInteractionOnLoginAndWhenClaimed(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
var sourceTime uint64
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
p.ownedItems.AttachPrestigeIllustrations(nil)
items, err := p.ownedItems.GrantOnce(ctx, "historical-prestige", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}})
if err != nil || len(items) != 1 {
t.Fatalf("seed historical external ownership: %v", err)
}
sourceTime = items[0].TimeValue
if _, err := p.collection.GrantCostumes(ctx, "ordinary-costume", []uint64{3303}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
if err := p.mailService.EnqueueCompensation(ctx, "new-prestige", "Interaction test", "Claim a new prestige skin", []gamedata.Reward{{Type: 45, ID: 3892, Count: 1}}, time.Now()); err != nil {
t.Fatal(err)
}
})
closeNicknamePlayer(t, s.owner)
registry := newPlayerRegistry(factory, time.Minute)
t.Cleanup(func() {
if err := registry.Close(context.Background()); err != nil {
t.Error(err)
}
})
a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
find := func(rows [][]byte, typ, id uint64) []byte {
t.Helper()
var result []byte
for _, row := range rows {
if appValue(row, 3) == typ && appValue(row, 2) == id {
if result != nil {
t.Fatalf("duplicate native inventory row for %d/%d", typ, id)
}
result = row
}
}
return result
}
items := appRows(a.send("/ItemInfo", nil, 21, 0), 1)
illustration := find(items, 25, 274)
if illustration == nil || appValue(illustration, 1) == 0 || appValue(illustration, 4) != 1 || appValue(illustration, 6) != sourceTime {
t.Fatal("historical prestige ownership did not restore a selectable interactive illustration")
}
if find(items, 25, 32) != nil || find(items, 25, 135) != nil {
t.Fatal("login bypassed dating progression or unlocked an unclaimed prestige skin")
}
if find(appRows(b.send("/ItemInfo", nil, 21, 0), 1), 25, 274) != nil {
t.Fatal("another player's prestige unlocked this player's interaction entry")
}
var mailID uint64
for _, row := range appRows(a.send("/MailInfo", nil, 131, 0), 1) {
title, _, err := wire.Bytes(row, 5)
if err != nil {
t.Fatal(err)
}
if string(title) == "Interaction test" {
mailID = appValue(row, 1)
}
}
if mailID == 0 {
t.Fatal("new prestige claim mail is missing")
}
claim := a.send("/MailOpen", appScalar(2, mailID), 132, 0)
bundles := appRows(claim, 1)
if len(bundles) != 1 {
t.Fatal("mail claim did not return the native reward bundle")
}
granted := appRows(bundles[0], 1)
if find(granted, 45, 3892) == nil || find(granted, 25, 135) == nil {
t.Fatal("claiming prestige did not unlock interaction in the current client session")
}
a.seq--
if retry := a.send("/MailOpen", appScalar(2, mailID), 132, 0); !bytes.Equal(retry, claim) {
t.Fatal("claim retry changed the associated illustration update")
}
if err := registry.Close(context.Background()); err != nil {
t.Fatal(err)
}
registry = newPlayerRegistry(factory, time.Minute)
a = friendHTTPLogin(t, registry, accounts[0])
items = appRows(a.send("/ItemInfo", nil, 21, 0), 1)
if !bytes.Equal(find(items, 25, 274), illustration) || find(items, 25, 135) == nil || find(items, 25, 32) != nil {
t.Fatal("relogin changed illustration identity, lost a claimed interaction, or bypassed dating")
}
a.send("/MailOpen", appScalar(2, mailID), 132, 0)
if rows := appRows(a.send("/ItemInfo", nil, 21, 0), 1); !bytes.Equal(find(rows, 25, 135), find(items, 25, 135)) {
t.Fatal("reopening claimed mail duplicated the companion illustration")
}
if err := registry.Close(context.Background()); err != nil {
t.Fatal(err)
}
s.owner = openNicknamePlayer(t, factory, accounts[0])
var actualIndex uint64
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
granted, err := p.ownedItems.GrantOnce(ctx, "explicit-illustration", []gamedata.BattleReward{{Type: 25, ID: 274, Count: 1}})
if err != nil || len(granted) != 1 {
t.Fatalf("grant separate illustration item: %v", err)
}
actualIndex = granted[0].InvenIndex
})
closeNicknamePlayer(t, s.owner)
registry = newPlayerRegistry(factory, time.Minute)
a = friendHTTPLogin(t, registry, accounts[0])
if row := find(appRows(a.send("/ItemInfo", nil, 21, 0), 1), 25, 274); row == nil || appValue(row, 1) != actualIndex {
t.Fatal("an existing illustration item was duplicated or replaced by the skin ownership view")
}
}
@@ -78,10 +78,14 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
t.Error(err)
}
})
session := scenario.name
run := func(identity, path string, body []byte) []byte {
t.Helper()
request := registryCommand(accounts[0], scenario.name+identity, path, body)
request.Identity.SessionID = scenario.name
request.Identity.SessionID = session
if path == "/LoginUser" {
request.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
}
reply := registryExecute(t, runtime, request)
return reply.Responses[0].Body
}
@@ -112,6 +116,38 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
if appValue(response, 2) != scenario.selected {
t.Fatalf("client receives wrong enemy deck: %d, want %d", appValue(response, 2), scenario.selected)
}
reenter := func(identity string) {
t.Helper()
if err := owner.Recover(context.Background()); err != nil {
t.Fatal(err)
}
session += "-reconnected"
run(identity+"-login", "/LoginUser", appScalar(1, 1))
pack := run(identity+"-pack", "/PackInGameInfo", append(appScalar(1, 2), appScalar(2, 1)...))
// CommonPacket consumes field 17 before GameFieldManager opens BattleResumePopupUI.
positions := appRows(pack, 4)
if appValue(pack, 17) != 1 || len(appRows(pack, 2)) == 0 || len(positions) != 1 || len(positions[0]) == 0 {
t.Fatal("relogin could not load the field and offer the unfinished battle")
}
other := registryCommand(accounts[0], scenario.name+identity+"-switch-pack", "/PackInGameInfo", append(appScalar(1, 3), appScalar(2, 2)...))
other.Identity.SessionID = session
future, err := runtime.Submit(context.Background(), other)
if err != nil {
t.Fatal(err)
}
if _, err := future.Wait(context.Background()); err == nil {
t.Fatal("unfinished battle allowed switching to another pack")
}
if owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold || !maps.Equal(appItemTotals(run(identity+"-items", "/ItemInfo", appScalar(1, 4))), beforeItems) {
t.Fatal("relogin granted battle rewards before victory")
}
}
reenter("before-start")
initial := run("resume-before-start", "/BattleResume", appScalar(1, 5))
commons := appRows(initial, 1)
if appValue(initial, 22) != 1 || len(commons) != 1 || appValue(commons[0], 2) != scenario.selected || appValue(initial, 5) != uint64(scenario.activeQuest) {
t.Fatal("session expiry before BattleStart lost the pending encounter")
}
blue := appScalar(3, 300)
common := append(appScalar(1, 1), appScalar(2, scenario.selected)...)
checkpoint := appMessage(1, common)
@@ -120,9 +156,7 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
start := append(appScalar(1, 3), appScalar(2, scenario.selected)...)
start = append(start, appMessage(100, checkpoint)...)
run("start", "/BattleStart", start)
if err := owner.Recover(context.Background()); err != nil {
t.Fatal(err)
}
reenter("after-start")
resume := run("resume", "/BattleResume", appScalar(1, 101))
if appValue(resume, 5) != uint64(scenario.activeQuest) {
t.Fatal("story battle recovery lost its actual owning quest")
@@ -166,6 +200,10 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
if totals := appItemTotals(run("items-retry", "/ItemInfo", appScalar(1, 6))); !maps.Equal(totals, afterItems) {
t.Fatal("settlement retry credited owned items twice")
}
pack := run("settled-pack", "/PackInGameInfo", append(appScalar(1, 7), appScalar(2, 1)...))
if appValue(pack, 17) != 0 {
t.Fatal("settled encounter still offered battle recovery")
}
})
}
}
+3 -5
View File
@@ -1,11 +1,10 @@
package app
import (
"bd2server/internal/common/util"
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"io"
@@ -99,12 +98,11 @@ func (t *realtimeTickets) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "instance changed", http.StatusConflict)
return
}
var secret [32]byte
if _, err := rand.Read(secret[:]); err != nil {
token, err := util.RandomBase64URL(32)
if err != nil {
http.Error(w, "ticket unavailable", http.StatusServiceUnavailable)
return
}
token := base64.RawURLEncoding.EncodeToString(secret[:])
key := sha256.Sum256([]byte(token))
now := time.Now()
expires := now.Add(30 * time.Second)
@@ -0,0 +1,62 @@
//go:build integration
package app
import (
"bytes"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
func TestRealCostumeSelectorConsumesTicketAndRestoresChosenCostume(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
var selected, index uint64
for id := range factory.design.resourceItems.Selections[1501] {
if _, owned := s.owner.assembly.collection.CostumeByID(id); !owned {
selected = id
break
}
}
if selected == 0 {
t.Fatal("selector has no unowned allowed costume")
}
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
items, err := p.ownedItems.GrantOnce(ctx, "selector-earned-ticket", []gamedata.BattleReward{{Type: 8, ID: 1501, Count: 2}})
if err != nil || len(items) != 1 {
t.Fatalf("earn selector ticket: %v", err)
}
index = items[0].InvenIndex
})
s.reopen(t)
request := wire.AppendVarint(wire.AppendVarint(trapRequest(1, index), 3, 1), 4, selected)
response := s.protocol(t, "/UseResourceItem", request)
chosen, owned := s.owner.assembly.collection.CostumeByID(selected)
if !owned || chosen.Level != 0 {
t.Fatal("using an earned selector did not grant the chosen first costume")
}
s.reopen(t)
if !bytes.Equal(response, s.protocol(t, "/UseResourceItem", request)) {
t.Fatal("selector retry lost the committed response")
}
restored, owned := s.owner.assembly.collection.CostumeByID(selected)
if !owned || restored.Level != 0 {
t.Fatal("selector retry granted an extra enhancement")
}
count := appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 4)))[[2]uint64{8, 1501}]
if count != 1 {
t.Fatal("selector retry consumed a second ticket")
}
other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
defer closeNicknamePlayer(t, other.owner)
if _, err := other.execute("/UseResourceItem", request); err == nil {
t.Fatal("another account used a ticket it does not own")
}
if _, owned := other.owner.assembly.collection.CostumeByID(selected); owned {
t.Fatal("selector costume crossed account boundaries")
}
}
@@ -0,0 +1,370 @@
//go:build integration
package app
import (
"bytes"
"context"
"encoding/binary"
"fmt"
"slices"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
func TestCostumeOverflowPaysCompensationWithoutRepeatingCollectionNotice(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
for _, scenario := range []struct {
name string
costume uint64
goldThreadPerCopy uint64
}{
{"starter", 64701, 2},
{"earned", 1401, 2},
} {
t.Run(scenario.name, func(t *testing.T) {
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
grant := func(key string, count uint64) []byte {
t.Helper()
var bundle []byte
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
var err error
bundle, err = p.eventEconomy.Apply(ctx, scenario.name+":"+key, nil, []gamedata.Reward{{Type: 11, ID: scenario.costume, Count: count}})
if err != nil {
t.Fatal(err)
}
})
return bundle
}
costume, owned := s.owner.assembly.collection.CostumeByID(scenario.costume)
if scenario.name == "earned" {
if owned {
t.Fatal("new costume is already owned before its first reward")
}
rows := appRows(grant("first-copy", 1), 3)
if len(rows) != 1 || appValue(rows[0], 2) != scenario.costume {
t.Fatal("first copy did not deliver the costume")
}
costume, owned = s.owner.assembly.collection.CostumeByID(scenario.costume)
}
if !owned || costume.Level > 4 {
t.Fatal("costume cannot exercise the actual final enhancement")
}
for level := costume.Level; level < 4; level++ {
grant(fmt.Sprintf("enhance-%d", level), 1)
}
upgrade := appRows(grant("final-enhancement", 1), 9)
if len(upgrade) != 1 || appValue(upgrade[0], 4) != 4 || appValue(upgrade[0], 5) != 5 {
t.Fatal("a genuine +4 to +5 enhancement lost its collection notification")
}
s.reopen(t)
book := s.protocol(t, "/PictorialBookInfo", appScalar(1, uint64(s.commands+1)))
before := s.owner.assembly.wallet.Snapshot(command.Context{}).Mileage
bundle := grant("two-overflow-copies", 2)
if len(appRows(bundle, 9)) != 0 || len(appRows(bundle, 2)) != 0 || len(appRows(bundle, 3)) != 0 {
t.Fatal("overflow falsely announced new ownership or an enhancement")
}
exchanges := appRows(bundle, 8)
if len(exchanges) != 2 {
t.Fatal("two overflow copies did not produce their compensation records")
}
for _, exchange := range exchanges {
if appValue(exchange, 1) != 11 || appValue(exchange, 2) != scenario.costume || appValue(exchange, 4) != 20 || appValue(exchange, 6) != scenario.goldThreadPerCopy {
t.Fatal("overflow compensation differs from CostumeGrowthTable's gold thread reward")
}
}
s.reopen(t)
if !bytes.Equal(bundle, grant("two-overflow-copies", 2)) {
t.Fatal("reward retry changed the committed overflow receipt")
}
s.reopen(t)
costume, _ = s.owner.assembly.collection.CostumeByID(scenario.costume)
if costume.Level != 5 || s.owner.assembly.wallet.Snapshot(command.Context{}).Mileage != before+2*scenario.goldThreadPerCopy {
t.Fatal("overflow retry changed enhancement or credited compensation twice")
}
if !bytes.Equal(book, s.protocol(t, "/PictorialBookInfo", appScalar(1, uint64(s.commands+1)))) {
t.Fatal("overflow changed the already completed collection bonus")
}
})
}
}
// NewsUI uses CommunityWebLinkTable's displayed rewards and NoticePacket restores
// claim markers before enabling the same buttons after login.
func TestCommunityRewardCreditsOnceAndRestoresPerAccountClaims(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
players := make([]*trapPlayerScenario, 2)
for i, account := range accounts {
s := &trapPlayerScenario{factory: factory, account: account, owner: openNicknamePlayer(t, factory, account)}
players[i] = s
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
}
a, b := players[0], players[1]
before := a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry
request := trapRequest(1, 1)
result := a.protocol(t, "/CommunityReward", request)
rewards := appRows(appRows(result, 1)[0], 1)
var displayed uint64
for _, reward := range rewards {
if appValue(reward, 3) == 3 {
displayed += appValue(reward, 4)
}
}
// CommunityWebLinkTable 0 in GameData 20261012190548 advertises 100 free diamonds.
if displayed != 100 || a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry != before+100 {
t.Fatal("community reward shown by the client was not credited to spendable diamonds")
}
a.protocol(t, "/CommunityReward", trapRequest(2, 1))
a.reopen(t)
rows := appRows(a.protocol(t, "/CommunityRewardInfo", appScalar(1, 3)), 1)
if len(rows) != 1 || appValue(rows[0], 1) != 1 {
t.Fatal("relogin made the already-claimed community button claimable again")
}
a.protocol(t, "/CommunityReward", trapRequest(4, 1))
if got := a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry; got != before+displayed {
t.Fatal("community reward replay credited diamonds again")
}
if rows := appRows(b.protocol(t, "/CommunityRewardInfo", appScalar(1, 1)), 1); len(rows) != 0 {
t.Fatal("one player's community claims disabled another player's buttons")
}
_, err := a.execute("/CommunityReward", wire.AppendVarint(trapRequest(5, 0), 3, 999999))
if err == nil {
t.Fatal("a nonexistent survey granted its displayed reward")
}
}
// GameData's InteractionAchievementTable gives illustration 1065193 point 1/1
// independent motions 0..4. Client saves only new motions, not a full snapshot.
func TestInteractionDeltasSurviveRelogWithoutErasingEarlierDiscoveries(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.ownedItems.GrantOnce(ctx, "interaction-owned-illustration", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}}); err != nil {
t.Fatal(err)
}
})
save := func(motion uint64) []byte {
point := wire.AppendVarint(nil, 1, 1)
point = wire.AppendVarint(point, 2, motion)
group := wire.AppendVarint(nil, 1, 1065193)
group = wire.AppendVarint(group, 2, 1)
group = wire.AppendBytes(group, 3, point)
return wire.AppendBytes(appScalar(1, uint64(s.commands+1)), 2, group)
}
s.protocol(t, "/SpineInteractionAchievementSave", save(0))
s.reopen(t)
s.protocol(t, "/SpineInteractionAchievementSave", save(1))
s.protocol(t, "/SpineInteractionAchievementSave", save(0))
s.reopen(t)
assertMotions := func() {
t.Helper()
groups := appRows(s.protocol(t, "/SpineInteractionAchievementInfo", appScalar(1, uint64(s.commands+1))), 1)
if len(groups) != 1 || appValue(groups[0], 1) != 1065193 || appValue(groups[0], 2) != 1 {
t.Fatal("relogin did not restore the illustration's discovered group")
}
points := appRows(groups[0], 3)
var motions []uint64
if len(points) != 1 || appValue(points[0], 1) != 1 {
t.Fatal("saved discoveries appeared on another interaction point")
}
if err := wire.Walk(points[0], func(f wire.Field) error {
if f.Number == 2 {
if f.Type != 0 && f.Type != 2 {
return wire.ErrMalformed
}
for raw := f.Value; len(raw) > 0; {
value, count := binary.Uvarint(raw)
if count <= 0 {
return wire.ErrMalformed
}
motions = append(motions, value)
raw = raw[count:]
}
}
return nil
}); err != nil {
t.Fatal(err)
}
if !slices.Equal(motions, []uint64{0, 1}) {
t.Fatalf("incremental save or retry lost/doubled prior motion discoveries: %v", motions)
}
}
assertMotions()
if _, err := s.execute("/SpineInteractionAchievementSave", save(999999)); err == nil {
t.Fatal("an unlisted motion was accepted as discovered")
}
if err := s.owner.Recover(context.Background()); err != nil {
t.Fatal(err)
}
assertMotions()
other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
defer closeNicknamePlayer(t, other.owner)
if rows := appRows(other.protocol(t, "/SpineInteractionAchievementInfo", appScalar(1, 1)), 1); len(rows) != 0 {
t.Fatal("another player's private interaction discoveries leaked")
}
}
// TotalWarPacket registers owned costumes before sending their damage. Its
// persistent best result controls the daily reward button across later logins.
func TestTotalWarResultRestoresDailyRewardWithoutDuplicatingInventory(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
var participant []byte
var costumeID uint64
for _, costume := range s.owner.assembly.collection.Costumes() {
definition, found := factory.design.regularGacha.Character(costume.ID)
if !found {
continue
}
for _, character := range s.owner.assembly.worldService.CharacterService().RawAll() {
if definition.ID != character.ID && !slices.Contains(definition.GrowthCharacterIDs, character.ID) {
continue
}
participant = appScalar(1, 1)
participant = append(participant, appScalar(2, character.InvenIndex)...)
participant = append(participant, appScalar(3, character.ID)...)
participant = append(participant, appScalar(4, character.HP)...)
participant = append(participant, appScalar(5, max(character.Level, 1))...)
participant = append(participant, appScalar(6, costume.InvenIndex)...)
participant = append(participant, appScalar(7, costume.ID)...)
costumeID = costume.ID
break
}
if costumeID != 0 {
break
}
}
if costumeID == 0 {
t.Fatal("starter roster cannot participate in total war")
}
deckEntry := appScalar(2, appValue(participant, 6))
deckEntry = append(deckEntry, appScalar(3, appValue(participant, 2))...)
s.protocol(t, "/TotalWarDeckSave", wire.AppendBytes(appScalar(1, 100), 2, deckEntry))
deckBody := s.protocol(t, "/TotalWarDeckInfo", appScalar(1, 101))
for _, contents := range appRows(deckBody, 2) {
if appValue(contents, 1) != appValue(participant, 2) {
continue
}
participant = append(participant, appScalar(29, appValue(contents, 3))...)
for _, ref := range appRows(contents, 2) {
if id := appValue(ref, 1); id != 0 {
participant = append(participant, appScalar(12, id)...)
}
}
}
// BattlePlayData.SetPlayDataTotalWar reads pack3005 BattleDeck 1 and sets
// its monster HP to one million before TotalWarPacket sends the roster.
enemies := []byte{}
for i, enemy := range factory.design.castle.TotalWarEnemies {
red := appScalar(1, uint64(i+100))
red = append(red, appScalar(3, enemy.ID)...)
red = append(red, appScalar(4, 1000000)...)
red = append(red, appScalar(5, enemy.Level)...)
red = append(red, appScalar(9, uint64(i))...)
enemies = wire.AppendBytes(enemies, 4, red)
}
start := append(wire.AppendBytes(trapRequest(1, 1), 3, participant), enemies...)
s.protocol(t, "/TotalWarBattleStart", start)
s.reopen(t)
// Current TotalWarRewardTable's first tier starts at 10,000 damage and
// grants auto-open box 905001 (gold 2000 + material 603 x1).
end := wire.AppendBytes(appScalar(1, 2), 2, trapRequest(costumeID, 10000))
s.protocol(t, "/TotalWarBattleEnd", end)
s.reopen(t)
if appValue(s.protocol(t, "/TotalWarRewardState", appScalar(1, 3)), 1) != 1 {
t.Fatal("a committed qualifying result lost its unclaimed daily reward on login")
}
before := appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 4)))[[2]uint64{8, 603}]
goldBefore := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
s.protocol(t, "/TotalWarReward", appScalar(1, 5))
after := appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 6)))[[2]uint64{8, 603}]
if after != before+1 || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+2000 {
t.Fatal("total war daily reward did not credit its authored gold and material")
}
s.reopen(t)
if appValue(s.protocol(t, "/TotalWarRewardState", appScalar(1, 7)), 1) != 0 {
t.Fatal("claimed total war daily reward became claimable again after login")
}
if _, err := s.execute("/TotalWarReward", appScalar(1, 8)); err == nil {
t.Fatal("a new request claimed the same day's reward twice")
}
if err := s.owner.Recover(context.Background()); err != nil {
t.Fatal(err)
}
if appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 9)))[[2]uint64{8, 603}] != after || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+2000 {
t.Fatal("rejected repeated daily claim changed owned rewards")
}
s.protocol(t, "/TotalWarBattleStart", append(wire.AppendBytes(trapRequest(10, 1), 3, participant), enemies...))
s.protocol(t, "/TotalWarBattleEnd", wire.AppendBytes(appScalar(1, 11), 2, trapRequest(costumeID, 1)))
s.reopen(t)
result := s.protocol(t, "/TotalWarInfo", appScalar(1, 12))
rows := appRows(result, 1)
if len(rows) != 1 || appValue(rows[0], 1) != costumeID || appValue(rows[0], 2) != 10000 {
t.Fatal("replaying a lower score replaced the committed best result")
}
other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
defer closeNicknamePlayer(t, other.owner)
if len(other.protocol(t, "/TotalWarInfo", appScalar(1, 1))) != 0 {
t.Fatal("total war scores crossed account boundaries")
}
}
func TestExternalLifeRewardsAndShopConsumeTheSamePersistedBalance(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
var group, id, price, itemID, quantity uint64
for key, row := range factory.design.life.Tables["LifeBuyItemTable"] {
// LifeShopUI sends group/id/count; LifeBuyItemTable defines the life-coin
// payment and life-material quantity displayed by that shop entry.
if appValue(row, 8) == 64 && appValue(row, 5) == 66 && appValue(row, 6) != 0 {
group, id, price = key[0], key[1], appValue(row, 6)
itemID, quantity = appValue(row, 4), appValue(row, 3)
break
}
}
if price == 0 || quantity == 0 {
t.Fatal("current life shop has no coin-funded material purchase")
}
grant := func(ctx command.Context, p *playerAssembly) {
t.Helper()
if _, err := p.eventEconomy.Apply(ctx, "external-life-reward", nil, []gamedata.Reward{{Type: 64, Count: price * 2}}); err != nil {
t.Fatal(err)
}
}
s.run(t, true, grant)
request := trapRequest(1, group)
request = wire.AppendVarint(request, 3, id)
request = wire.AppendVarint(request, 4, 1)
s.protocol(t, "/LifeShopBuy", request)
s.reopen(t)
// Replaying the external entitlement after spending must not refill coins.
s.run(t, true, grant)
profile := s.protocol(t, "/LifeUserInfo", appScalar(1, 2))
users := appRows(profile, 2)
if len(users) != 1 || appValue(users[0], 1) != price {
t.Fatal("external reward and life shop used different balances or replay refilled spent coins")
}
info := s.protocol(t, "/LifeInfo", appScalar(1, 3))
var acquired uint64
for _, item := range appRows(info, 3) {
if appValue(item, 2) == itemID && appValue(item, 3) == 66 {
acquired += appValue(item, 4)
}
}
if acquired != quantity {
t.Fatal("spent life coins did not restore the purchased materials after database reopen")
}
other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
defer closeNicknamePlayer(t, other.owner)
otherUsers := appRows(other.protocol(t, "/LifeUserInfo", appScalar(1, 1)), 2)
if len(otherUsers) != 1 || appValue(otherUsers[0], 1) != 0 {
t.Fatal("external life rewards changed another account's life-coin balance")
}
}
@@ -0,0 +1,226 @@
//go:build integration
package app
import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
"bytes"
"encoding/binary"
"testing"
)
// The packet numbers, 1-based sequence, and independent run roster follow
// Proto.Net.PacketCodeTypeProto, RogueLikePacket.CreateDeckList and BattlePacket.
func TestRogueLikeNativeBattleReopenAndTicketConsumption(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
a := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
t.Cleanup(func() { closeNicknamePlayer(t, a.owner) })
seq := uint64(1)
call := func(path string, body []byte, code int) []byte {
t.Helper()
reply, e := a.execute(path, body)
if e != nil {
t.Fatalf("%s: %v", path, e)
}
if len(reply.Responses) != 1 || reply.Responses[0].PacketCode != code {
t.Fatalf("%s packet mismatch: %+v", path, reply.Responses)
}
if e = wire.Walk(reply.Responses[0].Body, func(wire.Field) error { return nil }); e != nil {
t.Fatal(e)
}
return reply.Responses[0].Body
}
var before uint64
a.run(t, true, func(ctx command.Context, p *playerAssembly) {
var e error
before, e = p.eventEconomy.CurrencyBalance(ctx, 35)
if e != nil {
t.Fatal(e)
}
rule := p.design.roguelike.Open
grants := []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}
pack := p.design.roguelike.PackOpen
if pack.TicketID != 0 {
grants = append(grants, gamedata.BattleReward{Type: 19, ID: pack.TicketID, Count: 1})
}
if _, e = p.ownedItems.GrantOnce(ctx, "roguelike-unlock-test", grants); e != nil {
t.Fatal(e)
}
})
a.reopen(t)
call("/PackInGameInfo", trapRequest(seq, factory.design.roguelike.Pack), 5)
seq++
call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
seq++
entered := call("/EvilCastleRogueLikeEnter", trapRequest(seq, 1), 280)
seq++
draftUnique := map[uint64]bool{}
for i := range 5 {
choice := appRows(entered, 2)
if len(choice) == 0 {
t.Fatal("draft choice absent")
}
ids := []uint64{}
if e := wire.Walk(choice[0], func(f wire.Field) error {
if f.Number == 2 && f.Type == 0 {
v, k := binary.Uvarint(f.Value)
if k <= 0 {
return wire.ErrMalformed
}
ids = append(ids, v)
}
return nil
}); e != nil {
t.Fatal(e)
}
if len(ids) == 0 {
t.Fatal("draft offered no costumes")
}
b := trapRequest(seq, 1)
seq++
selected := ids[0]
if i == 0 {
counts := map[uint64]int{}
for _, c := range factory.design.roguelike.Costumes {
counts[c.Unique]++
}
for _, id := range ids {
if counts[factory.design.roguelike.Costumes[id].Unique] == 1 {
selected = id
break
}
}
}
for _, id := range ids {
if i == 0 {
break
}
unique := factory.design.roguelike.Costumes[id].Unique
if !draftUnique[unique] {
selected = id
draftUnique[unique] = true
break
}
}
b = wire.AppendVarint(b, 4, selected)
entered = call("/EvilCastleRogueLikeSelectReward", b, 283)
a.reopen(t)
}
info := call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
seq++
characters, costumes := appRows(info, 5), appRows(info, 6)
if len(costumes) != 5 || len(characters) == 0 {
t.Fatal("draft roster was not persisted")
}
char := characters[0]
index := appValue(char, 1)
var costume []byte
for _, c := range costumes {
if appValue(c, 1) == appValue(char, 7) {
costume = c
}
}
if costume == nil {
t.Fatal("draft character lost costume ownership")
}
deck := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, index), 2, 0), 3, 1)
save := wire.AppendBytes(appScalar(1, seq), 2, deck)
seq++
call("/EvilCastleRogueLikeDeckSave", save, 285)
floors := appRows(info, 3)
room := appRows(floors[0], 2)[0]
group, id := appValue(room, 2), appValue(room, 3)
definition := factory.design.roguelike.Rooms.Row(group, id)
battleDeck := definition.V(1)
call("/EvilCastleRogueLikeRoomEnter", trapRequest(seq, appValue(room, 1)), 282)
seq++
enter := wire.AppendVarint(wire.AppendVarint(appScalar(1, seq), 4, battleDeck), 5, 21)
seq++
call("/BattleEnter", enter, 52)
start := wire.AppendBytes(trapRequest(seq, battleDeck), 3, deck)
seq++
blue := wire.AppendVarint(nil, 1, 1)
for _, f := range []struct {
to int
value uint64
}{{2, index}, {3, appValue(char, 2)}, {4, appValue(char, 3)}, {5, appValue(char, 4)}, {6, appValue(costume, 1)}, {7, appValue(costume, 2)}, {8, appValue(costume, 3)}} {
blue = wire.AppendVarint(blue, f.to, f.value)
}
start = wire.AppendBytes(start, 5, blue)
for i, enemy := range factory.design.roguelike.Enemies[battleDeck] {
red := wire.AppendVarint(nil, 1, uint64(i+2))
red = wire.AppendVarint(red, 3, enemy.ID)
red = wire.AppendVarint(red, 4, 1)
red = wire.AppendVarint(red, 5, enemy.Level)
red = wire.AppendVarint(red, 9, enemy.Position)
start = wire.AppendBytes(start, 4, red)
}
forged, _, e := wire.ReplaceVarint(blue, 7, appValue(costume, 2)+1)
if e != nil {
t.Fatal(e)
}
var bad []byte
if e = wire.Walk(start, func(f wire.Field) error {
switch f.Number {
case 1:
bad = wire.AppendVarint(bad, 1, seq)
case 5:
bad = wire.AppendBytes(bad, 5, forged)
default:
bad = append(bad, start[f.Start:f.End]...)
}
return nil
}); e != nil {
t.Fatal(e)
}
seq++
a.run(t, false, func(ctx command.Context, p *playerAssembly) {
if _, _, _, e := p.battleService.Handle(ctx, "/BattleStart", bad); e == nil {
t.Fatal("unowned battle costume bypassed the event start hook")
}
})
call("/BattleStart", start, 14)
incoming := characters[1]
change := wire.AppendVarint(trapRequest(seq, appValue(incoming, 1)), 3, index)
seq++
call("/EvilCastleRogueLikeBattleCharChange", change, 317)
a.reopen(t)
end := wire.AppendBytes(trapRequest(seq, 1), 3, char)
end = wire.AppendBytes(end, 3, incoming)
seq++
result := call("/BattleEnd", end, 15)
state := appRows(result, 17)
if len(state) != 1 || appValue(state[0], 3) != 1 {
t.Fatal("normal battle settlement did not produce a run reward choice")
}
if !bytes.Equal(result, call("/BattleEnd", end, 15)) {
t.Fatal("normal battle replay changed settlement")
}
a.reopen(t)
resumed := call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
seq++
if appValue(appRows(resumed, 1)[0], 3) != 1 || len(appRows(resumed, 8)) != 1 {
t.Fatal("reopening lost pending battle rewards")
}
a.run(t, false, func(ctx command.Context, p *playerAssembly) {
after, e := p.eventEconomy.CurrencyBalance(ctx, 35)
if e != nil {
t.Fatal(e)
}
if before == 0 || after >= before {
t.Fatal("entry did not consume real account tickets")
}
})
choice := appRows(resumed, 8)[0]
selected := wire.AppendVarint(trapRequest(seq, 1), 4, appValue(choice, 2))
seq++
call("/EvilCastleRogueLikeSelectReward", selected, 283)
a.reopen(t)
resumed = call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
if appValue(appRows(resumed, 1)[0], 1) <= 1 {
t.Fatalf("reward claim did not advance the resumed run: %x", resumed)
}
}
+4 -5
View File
@@ -3,6 +3,7 @@ package app
import (
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/i18n"
"bd2server/internal/common/util"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/events/calendar"
@@ -15,8 +16,6 @@ import (
"bd2server/internal/server/platform/updates"
identitystore "bd2server/internal/server/storage/identity"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log/slog"
@@ -107,11 +106,10 @@ func Serve(args []string) (serveErr error) {
authHandler = authService.Handler()
}
availability := lifecycle.NewGate()
instanceBytes := make([]byte, 16)
if _, err := rand.Read(instanceBytes); err != nil {
instanceID, err := util.RandomHex(16)
if err != nil {
return fmt.Errorf("create server instance identity: %w", err)
}
instanceID := hex.EncodeToString(instanceBytes)
realtime, err := openRealtime(c, registry, game, shared, instanceID)
if err != nil {
return err
@@ -170,6 +168,7 @@ func Serve(args []string) (serveErr error) {
AuthenticationHandler: authHandler, ResourcePolicy: c.publicResources,
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID, RealtimeTickets: realtimeTickets,
StoryCheckpoints: storyCheckpoints{game: game, players: registry}, Console: console.Handler(),
SpineRecordings: spineRecordings{players: registry},
LoginsClosed: func() bool { return loginsClosed(0) != "" },
Releases: releaseFiles(filepath.Join(c.dataDir, "releases")),
ClientAllowed: compatibility.allowed,
+484
View File
@@ -0,0 +1,484 @@
package app
import (
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/domain/roster/deck"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/outbox"
"bd2server/internal/server/storage/shared"
"context"
"encoding/json"
"fmt"
"math"
"slices"
"strconv"
"strings"
"time"
)
const popularityWeekMS uint64 = 7 * 24 * 60 * 60 * 1000
// Friday 00:00 KST is Thursday 15:00 UTC.
func popularityWeek(at uint64) uint64 {
const anchor uint64 = 15 * 60 * 60 * 1000
if at < anchor {
return 0
}
return (at - anchor) / popularityWeekMS
}
func popularityContext(content, side, order, rank, stage uint64) string {
return fmt.Sprintf("%d:%d:%02d:%010d:%010d:", content, side, order, rank, stage)
}
func popularityCount(tx *shared.Tx, bucket, key string, delta int64) error {
raw, found, e := tx.Get(bucket, key)
if e != nil {
return e
}
var n int64
if found && json.Unmarshal(raw, &n) != nil {
return fmt.Errorf("invalid popularity counter")
}
if delta < 0 && n < -delta || delta > 0 && n > math.MaxInt64-delta {
return fmt.Errorf("popularity counter overflow")
}
n += delta
if n == 0 {
_, e = tx.Delete(bucket, key)
return e
}
raw, e = json.Marshal(n)
if e != nil {
return e
}
return tx.Put(bucket, key, raw)
}
func popularityReplace(tx *shared.Tx, identity string, next map[string]int64) error {
raw, found, e := tx.Get("popularity_sources", identity)
if e != nil {
return e
}
old := map[string]int64{}
if found && json.Unmarshal(raw, &old) != nil {
return fmt.Errorf("invalid popularity source")
}
for key, n := range old {
if e = popularityCount(tx, "popularity_counts", key, -n); e != nil {
return e
}
}
for key, n := range next {
if n <= 0 {
return fmt.Errorf("invalid popularity contribution")
}
if e = popularityCount(tx, "popularity_counts", key, n); e != nil {
return e
}
}
raw, e = json.Marshal(next)
if e != nil {
return e
}
return tx.Put("popularity_sources", identity, raw)
}
func scanPopularity(tx *shared.Tx, bucket, prefix string, visit func(shared.Entry) error) error {
for after := ""; ; {
rows, e := tx.Scan(bucket, prefix, after, 256)
if e != nil {
return e
}
if len(rows) == 0 {
return nil
}
for _, row := range rows {
after = row.Key
if e = visit(row); e != nil {
return e
}
}
}
}
func rotatePopularity(tx *shared.Tx, at uint64) error {
week := popularityWeek(at)
raw, found, e := tx.Get("popularity_clock", "week")
if e != nil {
return e
}
previous := week
if found && json.Unmarshal(raw, &previous) != nil {
return fmt.Errorf("invalid popularity week")
}
if previous > week {
return nil
}
if previous < week {
for _, live := range []string{"pvp:", "total:"} {
if e = scanPopularity(tx, "popularity_counts", live, func(row shared.Entry) error {
if e := tx.Put("popularity_counts", fmt.Sprintf("week:%020d:", previous)+strings.TrimPrefix(row.Key, live), row.Value); e != nil {
return e
}
return nil
}); e != nil {
return e
}
}
}
raw, e = json.Marshal(week)
if e != nil {
return e
}
return tx.Put("popularity_clock", "week", raw)
}
func (s *sharedRuntime) refreshPopularity(ctx context.Context, now time.Time) error {
return s.store.Update(ctx, func(tx *shared.Tx) error { return rotatePopularity(tx, uint64(now.UnixMilli())) })
}
func (s *sharedRuntime) equipmentPopularity(tx *shared.Tx, source string, r *deck.RecommendRecord) error {
next := map[string]int64{}
if r != nil {
chars := map[uint64]uint64{}
for _, c := range r.Characters {
if v, ok := s.statistics.Characters[c.ID]; ok {
chars[c.InvenIndex] = v.UniqueID
}
}
seen := map[string]bool{}
for _, v := range r.Equipment {
unique := chars[v.UseChar]
design, ok := s.statistics.Equipment[v.ID]
if !ok || unique == 0 || design.UniqueID == 0 {
continue
}
key := fmt.Sprintf("equip:%010d:%d:%010d", unique, design.Slot, design.UniqueID)
if !seen[key] {
next[key]++
seen[key] = true
}
}
}
return popularityReplace(tx, "equipment:"+source, next)
}
func decodePopularityEquipment(raw []byte, r *deck.RecommendRecord) error {
return wire.Walk(raw, func(f wire.Field) error {
switch f.Number {
case 2:
var c roster.Character
var e error
c.InvenIndex, _, e = wire.Varint(f.Value, 1)
if e != nil {
return e
}
c.ID, _, e = wire.Varint(f.Value, 2)
r.Characters = append(r.Characters, c)
return e
case 4:
var v assets.Equipment
var e error
v.UseChar, _, e = wire.Varint(f.Value, 2)
if e != nil {
return e
}
base, _, e := wire.Bytes(f.Value, 5)
if e != nil {
return e
}
v.ID, _, e = wire.Varint(base, 1)
r.Equipment = append(r.Equipment, v)
return e
}
return nil
})
}
func (s *sharedRuntime) totalWarPopularity(tx *shared.Tx, source string, p deck.PopularityPublication) error {
if p.OwnerIndex == 0 || p.Score > math.MaxInt64 || len(p.TotalWarCostumes) > 100 {
return fmt.Errorf("invalid total-war popularity")
}
for _, id := range p.TotalWarCostumes {
if _, ok := s.statistics.CostumeGrade[id]; !ok {
return fmt.Errorf("unknown total-war popularity costume")
}
}
ownerKey := fmt.Sprintf("%020d", p.OwnerIndex)
owner := recommendationSource(source)
raw, found, e := tx.Get("popularity_total_owners", ownerKey)
if e != nil {
return e
}
if found && string(raw) != owner {
return fmt.Errorf("total-war popularity owner conflict")
}
if e = tx.Put("popularity_total_owners", ownerKey, []byte(owner)); e != nil {
return e
}
raw, found, e = tx.Get("popularity_total", owner)
if e != nil {
return e
}
if found {
var old deck.PopularityPublication
if json.Unmarshal(raw, &old) != nil {
return fmt.Errorf("invalid total-war popularity score")
}
if old.Score >= p.Score {
return nil
}
}
raw, e = json.Marshal(p)
if e != nil {
return e
}
if e = tx.Put("popularity_total", owner, raw); e != nil {
return e
}
var records []deck.PopularityPublication
if e = scanPopularity(tx, "popularity_total", "", func(row shared.Entry) error {
var p deck.PopularityPublication
if json.Unmarshal(row.Value, &p) != nil {
return fmt.Errorf("invalid total-war popularity snapshot")
}
records = append(records, p)
return nil
}); e != nil {
return e
}
slices.SortFunc(records, func(a, b deck.PopularityPublication) int {
if a.Score > b.Score {
return -1
}
if a.Score < b.Score {
return 1
}
return 0
})
next := map[string]int64{}
rank := 0
for i, r := range records {
if i == 0 || records[i-1].Score != r.Score {
rank = i + 1
}
if uint64(rank)*100 > uint64(len(records))*10 {
continue
}
for _, id := range r.TotalWarCostumes {
next["total:"+popularityContext(3, 0, 0, 0, 0)+fmt.Sprintf("%010d", id)]++
}
}
return popularityReplace(tx, "total-war-ranking", next)
}
func (s *sharedRuntime) consumePopularity(ctx context.Context, event outbox.Pending) error {
var p deck.PopularityPublication
if json.Unmarshal(event.Envelope.Event.Payload, &p) != nil || p.CompletedAt == 0 {
return fmt.Errorf("invalid popularity battle")
}
if len(p.TotalWarCostumes) == 0 {
if e := p.Record.Validate(); e != nil {
return e
}
}
if s.statistics == nil {
return fmt.Errorf("missing popularity design")
}
return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
if e := rotatePopularity(tx, p.CompletedAt); e != nil {
return e
}
if len(p.TotalWarCostumes) != 0 {
return s.totalWarPopularity(tx, envelope.Source, p)
}
mode := p.Record.Context.BattleMode
content := uint64(0)
switch mode {
case 7:
content = 1
case 16:
content = 2
case 19:
content = 4
case 20:
content = 5
default:
return nil
}
stage := s.statistics.CastleStages[mode][p.Record.Context.BattleIndex]
if stage == 0 {
return fmt.Errorf("unknown castle popularity stage")
}
day := p.CompletedAt / (24 * 60 * 60 * 1000)
receipt := fmt.Sprintf("%s:%d:%d:%d", recommendationSource(envelope.Source), mode, p.Record.Context.BattleIndex, day)
if _, found, e := tx.Get("popularity_castle_days", receipt); e != nil || found {
return e
}
active := map[uint64]bool{}
for _, c := range p.Record.Characters {
active[c.UseCostume] = true
}
for _, c := range p.Record.Costumes {
if !active[c.InvenIndex] {
continue
}
for _, filter := range []uint64{0, stage} {
key := fmt.Sprintf("week:%020d:", popularityWeek(p.CompletedAt)) + popularityContext(content, 0, 0, 0, filter) + fmt.Sprintf("%010d", c.ID)
if e := popularityCount(tx, "popularity_counts", key, 1); e != nil {
return e
}
if stage == 0 {
break
}
}
}
return tx.Put("popularity_castle_days", receipt, []byte("1"))
})
}
func popularityRequest(raw []byte, max int) (map[int]uint64, error) {
values := map[int]uint64{}
e := wire.Walk(raw, func(f wire.Field) error {
if f.Number < 1 || f.Number > max {
return nil
}
if f.Type != 0 {
return fmt.Errorf("invalid popularity request field")
}
if _, found := values[f.Number]; found {
return fmt.Errorf("duplicate popularity request field")
}
v, _, e := wire.Varint(raw, f.Number)
if e != nil || v > math.MaxInt32 {
return fmt.Errorf("invalid popularity request value")
}
values[f.Number] = v
return nil
})
if e != nil {
return nil, e
}
if values[1] == 0 {
return nil, fmt.Errorf("missing popularity sequence")
}
return values, nil
}
func (s *sharedRuntime) popularInfo(ctx command.Context, path string, raw []byte, now time.Time) (int, []byte, error) {
code := 269
max := 6
if path == "/PopularEquipInfo" {
code = 0
max = 2
}
v, e := popularityRequest(raw, max)
if e != nil {
return code, nil, e
}
if s.statistics == nil {
return code, nil, fmt.Errorf("missing popularity design")
}
if path == "/PopularCostumeInfo" && (v[2] > 5 || v[3] > 1 || v[4] > 4) {
return code, nil, fmt.Errorf("invalid popularity filter")
}
if path == "/PopularEquipInfo" {
known := false
for _, c := range s.statistics.Characters {
known = known || c.UniqueID == v[2]
}
if !known {
return code, nil, fmt.Errorf("unknown popularity character")
}
}
cancel := ctx.Cancellation
if cancel == nil {
cancel = context.Background()
}
var body []byte
e = s.store.View(cancel, func(tx *shared.Tx) error {
if path == "/PopularEquipInfo" {
prefix := fmt.Sprintf("equip:%010d:", v[2])
type winner struct{ id, count uint64 }
winners := map[uint64]winner{}
if e := scanPopularity(tx, "popularity_counts", prefix, func(row shared.Entry) error {
var count uint64
if json.Unmarshal(row.Value, &count) != nil {
return fmt.Errorf("invalid equipment popularity")
}
parts := strings.Split(strings.TrimPrefix(row.Key, prefix), ":")
if len(parts) != 2 {
return fmt.Errorf("invalid equipment popularity key")
}
slot, e := strconv.ParseUint(parts[0], 10, 64)
if e != nil {
return e
}
id, e := strconv.ParseUint(parts[1], 10, 64)
if e != nil {
return e
}
prior := winners[slot]
if count > prior.count || count == prior.count && (prior.id == 0 || id < prior.id) {
winners[slot] = winner{id, count}
}
return nil
}); e != nil {
return e
}
for slot := range uint64(5) {
winner, found := winners[slot]
if !found {
continue
}
b := wire.AppendVarint(nil, 1, v[2])
b = wire.AppendVarint(b, 2, slot)
b = wire.AppendVarint(b, 3, winner.id)
b = wire.AppendVarint(b, 4, winner.count)
body = wire.AppendBytes(body, 1, b)
}
return nil
}
counts := map[uint64][3]uint64{}
week := popularityWeek(uint64(now.UnixMilli()))
for i := uint64(0); i < 3 && i <= week; i++ {
period := week - i
if v[2] == 0 || v[2] == 3 {
if period == 0 {
continue
}
period--
}
prefix := fmt.Sprintf("week:%020d:", period)
prefix += popularityContext(v[2], v[3], v[4], v[5], v[6])
if e := scanPopularity(tx, "popularity_counts", prefix, func(row shared.Entry) error {
id, e := strconv.ParseUint(strings.TrimPrefix(row.Key, prefix), 10, 64)
if e != nil {
return e
}
var n uint64
if json.Unmarshal(row.Value, &n) != nil {
return fmt.Errorf("invalid costume popularity")
}
a := counts[id]
a[i] = n
counts[id] = a
return nil
}); e != nil {
return e
}
}
ids := make([]uint64, 0, len(counts))
for id := range counts {
ids = append(ids, id)
}
slices.Sort(ids)
for _, id := range ids {
b := wire.AppendVarint(nil, 1, id)
for i, n := range counts[id] {
if n != 0 {
b = wire.AppendVarint(b, i+2, n)
}
}
body = wire.AppendBytes(body, 1, b)
}
return nil
})
return code, body, e
}
@@ -0,0 +1,338 @@
package app
import (
"context"
"encoding/json"
"fmt"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/domain/roster/deck"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/outbox"
"bd2server/internal/server/storage/shared"
)
func popularityFixture(t *testing.T) (*sharedRuntime, string) {
t.Helper()
directory := t.TempDir()
store, e := shared.Open(directory)
if e != nil {
t.Fatal(e)
}
s := &sharedRuntime{store: store, statistics: &gamedata.CollectionStatisticsDesign{Characters: map[uint64]gamedata.StatisticsCharacter{501: {UniqueID: 5, Grade: 5}}, CostumeGrade: map[uint64]uint64{101: 5, 102: 5}, Equipment: map[uint64]gamedata.StatisticsEquipment{301: {UniqueID: 900, Slot: 0}, 302: {UniqueID: 901, Slot: 0}}, CastleStages: map[uint64]map[uint64]uint64{16: {900: 1, 901: 2}}}}
t.Cleanup(func() {
if e := s.store.Close(); e != nil {
t.Error(e)
}
})
return s, directory
}
func popularityEvent(t *testing.T, s *sharedRuntime, source, id, topic string, value any) outbox.Pending {
t.Helper()
raw, e := json.Marshal(value)
if e != nil {
t.Fatal(e)
}
var result outbox.Pending
e = s.store.Update(context.Background(), func(tx *shared.Tx) error {
q, e := tx.Outbox()
if e != nil {
return e
}
if e = outbox.Publish(q, source, command.Event{ID: id, Topic: topic, Payload: raw}); e != nil {
return e
}
rows, e := outbox.Read(q, 256)
if e != nil {
return e
}
for _, r := range rows {
if r.Envelope.Source == source && r.Envelope.Event.ID == id {
result = r
return nil
}
}
return fmt.Errorf("missing committed publication")
})
if e != nil {
t.Fatal(e)
}
return result
}
func popularityRecord(owner uint64, costume, equip uint64) deck.RecommendRecord {
r := deck.RecommendRecord{Context: deck.RecommendContext{BattleMode: 16, BattleIndex: 900}, Identity: deck.RecommendIdentity{OwnerIndex: owner, UserID: fmt.Sprint(owner)}, Deck: []deck.DeckEntry{{CharacterInvenIndex: 11, Slot: 1}}, Characters: []roster.Character{{InvenIndex: 11, ID: 501, Level: 1, UseCostume: 21}}, Costumes: []deck.RecommendCostume{{Costume: roster.Costume{InvenIndex: 21, ID: costume, UseChar: 11}}}}
if equip != 0 {
r.Equipment = []assets.Equipment{{InvenIndex: 31, ID: equip, UseChar: 11}}
}
return r
}
func popularityRows(t *testing.T, s *sharedRuntime, path string, now time.Time, values ...uint64) [][]byte {
t.Helper()
raw := wire.AppendVarint(nil, 1, 1)
for i, v := range values {
raw = wire.AppendVarint(raw, i+2, v)
}
_, body, e := s.popularInfo(command.Context{}, path, raw, now)
if e != nil {
t.Fatal(e)
}
var rows [][]byte
if e = wire.Walk(body, func(f wire.Field) error {
if f.Number == 1 {
rows = append(rows, f.Value)
}
return nil
}); e != nil {
t.Fatal(e)
}
return rows
}
func popularityScalar(t *testing.T, b []byte, field int) uint64 {
t.Helper()
v, _, e := wire.Varint(b, field)
if e != nil {
t.Fatal(e)
}
return v
}
func TestCastlePopularityCountsFirstActualBattlePerDayAndRecovers(t *testing.T) {
s, dir := popularityFixture(t)
now := time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC)
p := deck.PopularityPublication{CompletedAt: uint64(now.UnixMilli()), Record: popularityRecord(1, 101, 0)}
event := popularityEvent(t, s, "alice", "attempt-1", deck.PopularityTopic, p)
if e := s.consumePopularity(t.Context(), event); e != nil {
t.Fatal(e)
}
if e := s.consumePopularity(t.Context(), event); e != nil {
t.Fatal(e)
}
p.CompletedAt++
if e := s.consumePopularity(t.Context(), popularityEvent(t, s, "alice", "attempt-2", deck.PopularityTopic, p)); e != nil {
t.Fatal(e)
}
p.Record = popularityRecord(2, 102, 0)
if e := s.consumePopularity(t.Context(), popularityEvent(t, s, "bob", "attempt-1", deck.PopularityTopic, p)); e != nil {
t.Fatal(e)
}
if e := s.store.Close(); e != nil {
t.Fatal(e)
}
var e error
s.store, e = shared.Open(dir)
if e != nil {
t.Fatal(e)
}
rows := popularityRows(t, s, "/PopularCostumeInfo", now, 2, 0, 0, 0, 1)
if len(rows) != 2 {
t.Fatalf("two players' actual active costumes: %d", len(rows))
}
for _, row := range rows {
if got := popularityScalar(t, row, 2); got != 1 {
t.Fatalf("repeat battle inflated daily usage to %d", got)
}
}
if rows := popularityRows(t, s, "/PopularCostumeInfo", now, 4, 0, 0, 0, 1); len(rows) != 0 {
t.Fatal("greed usage escaped into rage content")
}
p.Record = popularityRecord(1, 101, 0)
p.CompletedAt = uint64(now.Add(24 * time.Hour).UnixMilli())
if e := s.consumePopularity(t.Context(), popularityEvent(t, s, "alice", "next-day", deck.PopularityTopic, p)); e != nil {
t.Fatal(e)
}
rows = popularityRows(t, s, "/PopularCostumeInfo", now.Add(24*time.Hour), 2, 0, 0, 0, 1)
if got := popularityScalar(t, rows[0], 2); got != 2 {
t.Fatalf("next reset day did not count: %d", got)
}
}
func TestEquipmentPopularityReplacesOwnerSnapshotAndChoosesMostUsedSlot(t *testing.T) {
s, _ := popularityFixture(t)
now := time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC)
for i, source := range []string{"alice", "bob", "carol"} {
r := popularityRecord(uint64(i+1), 101, 301)
r.Revision = 1
event := popularityEvent(t, s, source, "saved", deck.RecommendationTopic, deck.RecommendationPublication{Revision: 1, Public: true, Record: &r})
if e := s.consumeRecommendation(t.Context(), event); e != nil {
t.Fatal(e)
}
if e := s.consumeRecommendation(t.Context(), event); e != nil {
t.Fatal(e)
}
}
r := popularityRecord(1, 101, 302)
r.Revision = 2
if e := s.consumeRecommendation(t.Context(), popularityEvent(t, s, "alice", "changed", deck.RecommendationTopic, deck.RecommendationPublication{Revision: 2, Public: true, Record: &r})); e != nil {
t.Fatal(e)
}
rows := popularityRows(t, s, "/PopularEquipInfo", now, 5)
if len(rows) != 1 || popularityScalar(t, rows[0], 3) != 900 || popularityScalar(t, rows[0], 4) != 2 {
t.Fatalf("expected most-used item with two remaining owners: %x", rows)
}
if e := s.consumeRecommendation(t.Context(), popularityEvent(t, s, "bob", "hidden", deck.RecommendationTopic, deck.RecommendationPublication{Revision: 2, Public: false})); e != nil {
t.Fatal(e)
}
rows = popularityRows(t, s, "/PopularEquipInfo", now, 5)
if len(rows) != 1 || popularityScalar(t, rows[0], 4) != 1 {
t.Fatalf("withdrawn owner still counted: %x", rows)
}
}
func TestPopularityDoesNotFillUnobservedHistoricalWeeks(t *testing.T) {
first := time.Date(2026, 10, 15, 14, 59, 0, 0, time.UTC)
s, makeSnapshot := pvpPopularityFixture(t, first)
update := pvp.PopularityPublished{Timestamp: uint64(first.UnixMilli()), Snapshot: makeSnapshot(1, false)}
if err := s.consumePVP(t.Context(), popularityEvent(t, s, "alice", "actual-registration", "pvp.popularity", update)); err != nil {
t.Fatal(err)
}
published := first.Add(time.Minute)
if err := s.refreshPopularity(t.Context(), published); err != nil {
t.Fatal(err)
}
rows := popularityRows(t, s, "/PopularCostumeInfo", published, 0, 0, 0, 1, 0)
if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 1 {
t.Fatal("the actually observed registration did not publish at the weekly boundary")
}
later := first.Add(5 * 7 * 24 * time.Hour)
if err := s.refreshPopularity(t.Context(), later); err != nil {
t.Fatal(err)
}
if rows := popularityRows(t, s, "/PopularCostumeInfo", later, 0, 0, 0, 1, 0); len(rows) != 0 {
t.Fatalf("unobserved weeks were synthesized: %x", rows)
}
}
func pvpPopularityFixture(t *testing.T, now time.Time) (*sharedRuntime, func(uint64, bool) pvp.PublishedSnapshot) {
t.Helper()
s, _ := popularityFixture(t)
design := &gamedata.PvpDesign{Mirror: gamedata.PvpDefaults{StartVP: 1000, MinimumVP: 1000}, MirrorSeasons: map[uint64]uint64{1: 1}, MirrorRanks: map[uint64][]gamedata.PvpRank{1: {{Group: 1, ID: 7, VP: 1000}}}}
var e error
s.pvp, e = newSharedPVP(t.Context(), s.store, design, []pvp.Season{{Mode: pvp.Mirror, ID: 1, Start: 1, End: uint64(now.AddDate(1, 0, 0).UnixMilli())}})
if e != nil {
t.Fatal(e)
}
s.statistics.PVPRankGroups = map[uint64]uint64{7: 1}
s.statistics.PVPMinimumGroup = 1
makeSnapshot := func(version uint64, reverse bool) pvp.PublishedSnapshot {
order := []uint64{21, 22}
if reverse {
order = []uint64{22, 21}
}
entry := wire.AppendVarint(nil, 1, 11)
for _, index := range order {
entry = wire.AppendBytes(entry, 5, wire.AppendVarint(nil, 1, index))
}
full := wire.AppendBytes(nil, 1, entry)
for i, id := range []uint64{101, 102} {
c := wire.AppendVarint(nil, 1, uint64(i+21))
c = wire.AppendVarint(c, 2, id)
full = wire.AppendBytes(full, 3, c)
}
return pvp.PublishedSnapshot{Profile: pvp.Profile{OwnerID: "alice", OwnerIndex: 1}, Mode: pvp.Mirror, Season: 1, Version: version, VP: 1000, Snapshot: pvp.FullSnapshot{FullDeck: full}}
}
return s, makeSnapshot
}
func TestPVPPopularitySeparatesRegisteredSkillOrderAndDeckSide(t *testing.T) {
now := time.Date(2026, 10, 15, 14, 59, 0, 0, time.UTC)
s, makeSnapshot := pvpPopularityFixture(t, now)
for side := range uint64(2) {
update := pvp.PopularityPublished{Timestamp: uint64(now.UnixMilli()), Side: side, Snapshot: makeSnapshot(1, side == 1)}
event := popularityEvent(t, s, "alice", fmt.Sprintf("registration-%d", side), "pvp.popularity", update)
if e := s.consumePVP(t.Context(), event); e != nil {
t.Fatal(e)
}
if e := s.consumePVP(t.Context(), event); e != nil {
t.Fatal(e)
}
}
if rows := popularityRows(t, s, "/PopularCostumeInfo", now, 0, 0, 0, 1, 0); len(rows) != 0 {
t.Fatal("unpublished initial registrations were exposed")
}
published := now.Add(time.Minute)
if e := s.refreshPopularity(t.Context(), published); e != nil {
t.Fatal(e)
}
for _, q := range []struct{ side, order, want uint64 }{{0, 0, 101}, {0, 1, 102}, {1, 0, 102}, {1, 1, 101}} {
rows := popularityRows(t, s, "/PopularCostumeInfo", published, 0, q.side, q.order, 1, 0)
if len(rows) != 1 || popularityScalar(t, rows[0], 1) != q.want || popularityScalar(t, rows[0], 2) != 1 {
t.Fatalf("side=%d order=%d wanted costume %d once: %x", q.side, q.order, q.want, rows)
}
}
update := pvp.PopularityPublished{Timestamp: uint64(published.Add(time.Second).UnixMilli()), Side: 0, Snapshot: makeSnapshot(2, true)}
if e := s.consumePVP(t.Context(), popularityEvent(t, s, "alice", "changed-registration", "pvp.popularity", update)); e != nil {
t.Fatal(e)
}
rows := popularityRows(t, s, "/PopularCostumeInfo", published, 0, 0, 0, 1, 0)
if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 {
t.Fatalf("in-period registration change leaked into published statistics: %x", rows)
}
published = published.Add(7 * 24 * time.Hour)
if e := s.refreshPopularity(t.Context(), published); e != nil {
t.Fatal(e)
}
rows = popularityRows(t, s, "/PopularCostumeInfo", published, 0, 0, 0, 1, 0)
if len(rows) != 2 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 0 || popularityScalar(t, rows[0], 3) != 1 || popularityScalar(t, rows[1], 1) != 102 || popularityScalar(t, rows[1], 2) != 1 || popularityScalar(t, rows[1], 3) != 0 {
t.Fatalf("weekly publication/history did not shift independently: %x", rows)
}
}
func TestTotalWarPopularityUsesActualCommunityRanking(t *testing.T) {
s, _ := popularityFixture(t)
now := time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC)
publish := func(owner, score, costume uint64, at time.Time, id string) {
t.Helper()
p := deck.PopularityPublication{CompletedAt: uint64(at.UnixMilli()), Score: score, OwnerIndex: owner, TotalWarCostumes: []uint64{costume}}
event := popularityEvent(t, s, fmt.Sprint(owner), id, deck.PopularityTopic, p)
if e := s.consumePopularity(t.Context(), event); e != nil {
t.Fatal(e)
}
if e := s.consumePopularity(t.Context(), event); e != nil {
t.Fatal(e)
}
}
publish(1, 999, 101, now, "best-run")
if rows := popularityRows(t, s, "/PopularCostumeInfo", now, 3, 0, 0, 0, 0); len(rows) != 0 {
t.Fatal("unpublished first result was exposed")
}
first := now.Add(7 * 24 * time.Hour)
if e := s.refreshPopularity(t.Context(), first); e != nil {
t.Fatal(e)
}
if rows := popularityRows(t, s, "/PopularCostumeInfo", first, 3, 0, 0, 0, 0); len(rows) != 0 {
t.Fatal("one account cannot claim a top-ten-percent rank")
}
for owner := uint64(2); owner <= 10; owner++ {
publish(owner, 1000-owner, 102, first.Add(time.Hour), "best-run")
}
if rows := popularityRows(t, s, "/PopularCostumeInfo", first, 3, 0, 0, 0, 0); len(rows) != 0 {
t.Fatal("in-period population change bypassed weekly publication")
}
second := first.Add(7 * 24 * time.Hour)
if e := s.refreshPopularity(t.Context(), second); e != nil {
t.Fatal(e)
}
rows := popularityRows(t, s, "/PopularCostumeInfo", second, 3, 0, 0, 0, 0)
if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 1 {
t.Fatalf("expected one actual top-ten-percent result: %x", rows)
}
publish(2, 2000, 102, second.Add(time.Minute), "new-best")
rows = popularityRows(t, s, "/PopularCostumeInfo", second, 3, 0, 0, 0, 0)
if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 {
t.Fatalf("new score leaked before the weekly boundary: %x", rows)
}
third := second.Add(7 * 24 * time.Hour)
if e := s.refreshPopularity(t.Context(), third); e != nil {
t.Fatal(e)
}
rows = popularityRows(t, s, "/PopularCostumeInfo", third, 3, 0, 0, 0, 0)
if len(rows) != 2 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 0 || popularityScalar(t, rows[0], 3) != 1 || popularityScalar(t, rows[1], 1) != 102 || popularityScalar(t, rows[1], 2) != 1 || popularityScalar(t, rows[1], 3) != 0 {
t.Fatalf("published ranking/history did not move at the weekly boundary: %x", rows)
}
}
+128
View File
@@ -4,8 +4,13 @@ import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/ranking"
"bd2server/internal/server/domain/roster/deck"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/outbox"
"bd2server/internal/server/storage/shared"
"context"
"encoding/json"
"fmt"
)
type rankingStore struct{ store *shared.Store }
@@ -31,3 +36,126 @@ func (t rankingTx) Scan(bucket, prefix, after string, limit int) ([]ranking.Entr
func newSharedPVP(ctx context.Context, store *shared.Store, design *gamedata.PvpDesign, seasons []pvp.Season) (*ranking.PVP, error) {
return ranking.NewPVP(ctx, rankingStore{store}, design, seasons)
}
func (s *sharedRuntime) consumePVP(ctx context.Context, event outbox.Pending) error {
if event.Envelope.Event.Topic != "pvp.popularity" {
if e := s.pvp.Consume(ctx, event.Envelope.Source, event.Envelope.Event); e != nil {
return e
}
if event.Envelope.Event.Topic == "pvp.battle.settled" && s.statistics != nil {
var battle pvp.BattleSettled
if e := json.Unmarshal(event.Envelope.Event.Payload, &battle); e != nil {
return e
}
if battle.Mode != pvp.Mirror {
return nil
}
return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
for side, snapshot := range []pvp.PublishedSnapshot{battle.Attacker, battle.Defender} {
if e := s.applyPVPPopularity(tx, snapshot.Profile.OwnerID, pvp.PopularityPublished{Timestamp: battle.Timestamp, Side: uint64(side), Snapshot: snapshot}); e != nil {
return e
}
}
return nil
})
}
return nil
}
var update pvp.PopularityPublished
if json.Unmarshal(event.Envelope.Event.Payload, &update) != nil || update.Timestamp == 0 || update.Side > 1 || update.Snapshot.Profile.OwnerID != event.Envelope.Source {
return fmt.Errorf("invalid PvP popularity publication")
}
if s.statistics == nil {
return fmt.Errorf("missing popularity design")
}
if update.Snapshot.Mode != pvp.Mirror {
return nil
}
return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
return s.applyPVPPopularity(tx, envelope.Source, update)
})
}
func (s *sharedRuntime) applyPVPPopularity(tx *shared.Tx, owner string, update pvp.PopularityPublished) error {
id, e := s.pvp.PopularityRank(update.Snapshot)
if e != nil {
return e
}
group := s.statistics.PVPRankGroups[id]
if e := rotatePopularity(tx, update.Timestamp); e != nil {
return e
}
source := recommendationSource(owner)
identity := fmt.Sprintf("pvp:%s:%d", source, update.Side)
raw, found, e := tx.Get("popularity_pvp_revision", fmt.Sprintf("%s:%d", identity, update.Snapshot.Season))
if e != nil {
return e
}
var latest uint64
if found && json.Unmarshal(raw, &latest) != nil {
return fmt.Errorf("invalid PvP popularity revision")
}
if latest > update.Snapshot.Version {
return nil
}
next := map[string]int64{}
costumes := map[uint64]uint64{}
if e = wire.Walk(update.Snapshot.Snapshot.FullDeck, func(f wire.Field) error {
if f.Number != 3 {
return nil
}
index, _, e := wire.Varint(f.Value, 1)
if e != nil {
return e
}
id, _, e := wire.Varint(f.Value, 2)
costumes[index] = id
return e
}); e != nil {
return e
}
if group != 0 && group <= s.statistics.PVPMinimumGroup {
if e = wire.Walk(update.Snapshot.Snapshot.FullDeck, func(f wire.Field) error {
if f.Number != 1 {
return nil
}
order := uint64(0)
return wire.Walk(f.Value, func(skill wire.Field) error {
if skill.Number != 5 {
return nil
}
index, _, e := wire.Varint(skill.Value, 1)
if e != nil {
return e
}
costume := costumes[index]
if costume == 0 {
return fmt.Errorf("invalid PvP popularity costume")
}
for _, filter := range []uint64{0, group} {
key := "pvp:" + popularityContext(0, update.Side, order, filter, 0) + fmt.Sprintf("%010d", costume)
next[key]++
}
order++
return nil
})
}); e != nil {
return e
}
}
if e = popularityReplace(tx, identity, next); e != nil {
return e
}
raw, e = json.Marshal(update.Snapshot.Version)
if e != nil {
return e
}
if e = tx.Put("popularity_pvp_revision", fmt.Sprintf("%s:%d", identity, update.Snapshot.Season), raw); e != nil {
return e
}
r := deck.RecommendRecord{}
if e = decodePopularityEquipment(update.Snapshot.Snapshot.FullDeck, &r); e != nil {
return e
}
return s.equipmentPopularity(tx, source, &r)
}
@@ -61,6 +61,17 @@ func (s *sharedRuntime) consumeRecommendation(ctx context.Context, event outbox.
return e
}
}
if s.statistics != nil && update.Revision > previous.Revision {
var record *deck.RecommendRecord
if update.Public {
record = update.Record
}
if record != nil || !update.Public {
if e = s.equipmentPopularity(tx, source, record); e != nil {
return e
}
}
}
if update.Record == nil {
return nil
}
+26 -2
View File
@@ -11,6 +11,7 @@ import (
"sync/atomic"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/ranking"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/runtime/delivery"
@@ -20,11 +21,14 @@ import (
)
type sharedRuntime struct {
statistics *gamedata.CollectionStatisticsDesign
directory *publicDirectory
rooms *roomResults
store *shared.Store
pvp *ranking.PVP
huntRanks *ranking.MonsterHunt
castleRanks *ranking.Castle
rogueRanks *ranking.RogueLike
arcadeRanks *ranking.Arcade
guild *social.Owner
friends *social.Friends
@@ -46,6 +50,14 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
if err != nil {
return nil, errors.Join(err, store.Close())
}
castleRanks, err := ranking.NewCastle(ctx, rankingStore{store})
if err != nil {
return nil, errors.Join(err, store.Close())
}
rogueRanks, err := ranking.NewRogueLike(ctx, rankingStore{store})
if err != nil {
return nil, errors.Join(err, store.Close())
}
arcadeRanks, err := ranking.NewArcade(ctx, rankingStore{store})
if err != nil {
return nil, errors.Join(err, store.Close())
@@ -66,7 +78,7 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
if err != nil {
return nil, errors.Join(err, store.Close())
}
return &sharedRuntime{store: store, pvp: pvp, huntRanks: huntRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
return &sharedRuntime{statistics: design.collectionStatistics, store: store, pvp: pvp, huntRanks: huntRanks, castleRanks: castleRanks, rogueRanks: rogueRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
}
func (s *sharedRuntime) wake(account string) {
@@ -79,6 +91,12 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
if _, _, err := outbox.Validate(event); err != nil {
return err
}
if event.Envelope.Event.Topic == "roguelike.ranking" {
return s.consumeRogueRanking(ctx, event)
}
if event.Envelope.Event.Topic == "castle.ranking" {
return s.consumeCastleRanking(ctx, event)
}
if event.Envelope.Event.Topic == "monster_hunt.ranking" {
return s.consumeHuntRanking(ctx, event)
}
@@ -88,6 +106,9 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
if event.Envelope.Event.Topic == "deck.recommendation" {
return s.consumeRecommendation(ctx, event)
}
if event.Envelope.Event.Topic == "deck.popularity" {
return s.consumePopularity(ctx, event)
}
if event.Envelope.Event.Topic == "arcade.ranking" {
return s.consumeArcadeRanking(ctx, event)
}
@@ -114,7 +135,7 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
return s.rooms.Consume(ctx, event)
}
if strings.HasPrefix(event.Envelope.Event.Topic, "pvp.") {
return s.pvp.Consume(ctx, event.Envelope.Source, event.Envelope.Event)
return s.consumePVP(ctx, event)
}
if event.Envelope.Event.Topic == "social.confirm" {
var proof social.CommitProof
@@ -179,6 +200,9 @@ func (s *sharedRuntime) stop() error {
}
func (s *sharedRuntime) settle(ctx context.Context, registry *playerRegistry, discovery outboxDiscovery) error {
if err := s.refreshPopularity(ctx, time.Now()); err != nil {
return err
}
if err := s.closeExpiredRaids(ctx, registry); err != nil {
return err
}
+101
View File
@@ -0,0 +1,101 @@
package app
import (
"encoding/base64"
"encoding/json"
"errors"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"unicode/utf8"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/runtime/player"
"bd2server/internal/server/storage/stateio"
)
const spineRecordingPath = "/client/spine-recordings/"
type spineRecordingDownload struct {
ID uint64 `json:"id"`
Token string `json:"token"`
}
func (p *playerAssembly) interactionRecords() roster.InteractionRecordService {
return roster.InteractionRecordService{
Store: stateio.RootStore{}, Design: p.design.interaction,
Authorize: p.interactionAvailable, CheckText: p.checkProfileText,
RecordDataURL: func(ctx command.Context, id uint64, token string) (string, error) {
if ctx.AccountID == "" {
return "", errors.New("recording account identity is missing")
}
account := base64.RawURLEncoding.EncodeToString([]byte(ctx.AccountID))
base := p.options.gameRules.SpineRecording.DownloadBaseURL
if base == "" {
base = strings.TrimRight(consoleOrigin(p.options), "/") + strings.TrimRight(spineRecordingPath, "/")
}
return strings.TrimRight(base, "/") + "/" + account + "/" + strconv.FormatUint(id, 10) + "/" + token, nil
},
}
}
type spineRecordings struct{ players *playerRegistry }
func (h spineRecordings) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.Header().Set("Allow", "GET, HEAD")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, spineRecordingPath), "/")
if !strings.HasPrefix(r.URL.Path, spineRecordingPath) || len(parts) != 3 || len(parts[0]) > 512 || len(parts[2]) != 43 {
http.NotFound(w, r)
return
}
account, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil || len(account) == 0 || !utf8.Valid(account) || base64.RawURLEncoding.EncodeToString(account) != parts[0] {
http.NotFound(w, r)
return
}
id, err := strconv.ParseUint(parts[1], 10, 63)
if err != nil || id == 0 || strconv.FormatUint(id, 10) != parts[1] {
http.NotFound(w, r)
return
}
if token, err := base64.RawURLEncoding.DecodeString(parts[2]); err != nil || len(token) != 32 || base64.RawURLEncoding.EncodeToString(token) != parts[2] {
http.NotFound(w, r)
return
}
statePath := filepath.Join(h.players.factory.options.stateDirectory, "accounts", accountDirectoryName(string(account)), "state.db")
if _, err := os.Stat(statePath); errors.Is(err, os.ErrNotExist) {
http.NotFound(w, r)
return
} else if err != nil {
http.Error(w, "recording unavailable", http.StatusServiceUnavailable)
return
}
request, err := json.Marshal(spineRecordingDownload{ID: id, Token: parts[2]})
if err != nil {
http.Error(w, "recording unavailable", http.StatusServiceUnavailable)
return
}
body, err := executePlayerSystem(r.Context(), h.players, string(account), player.ReadSpineRecording, request)
if errors.Is(err, roster.ErrRecordNotFound) {
http.NotFound(w, r)
return
}
if err != nil {
http.Error(w, "recording unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
if r.Method == http.MethodGet {
_, _ = w.Write(body)
}
}
@@ -0,0 +1,177 @@
//go:build integration
package app
import (
"bytes"
"compress/gzip"
"context"
"encoding/binary"
"hash/crc32"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"bd2server/internal/server/design/gameconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/gateway/transport"
)
// This encodes the 2.36.7 client's RecordData.Serialize/Compress format,
// independently of the server parser: click events on prestige illustration
// 1065193, point 1/1, tool 0 from GameData 20261012190548.
func nativeInteractionRecording(t *testing.T, delays ...int32) []byte {
t.Helper()
raw := binary.LittleEndian.AppendUint32(nil, uint32(len(delays)))
for _, delay := range delays {
raw = append(raw, 1)
for _, value := range []int32{delay, 1, 1, 0} {
raw = binary.AppendUvarint(raw, uint64(uint32(value<<1)^uint32(value>>31)))
}
}
var compressed bytes.Buffer
gz := gzip.NewWriter(&compressed)
if _, err := gz.Write(raw); err != nil {
t.Fatal(err)
}
if err := gz.Close(); err != nil {
t.Fatal(err)
}
out := binary.LittleEndian.AppendUint32(nil, crc32.ChecksumIEEE(raw))
return append(append(out, 1), compressed.Bytes()...)
}
func TestInteractionRecordingPersistsNativePlaybackAndRevokesReplacedData(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
for _, account := range accounts {
s := &trapPlayerScenario{factory: factory, account: account, owner: openNicknamePlayer(t, factory, account)}
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.ownedItems.GrantOnce(ctx, "recording-illustration", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}}); err != nil {
t.Fatal(err)
}
})
closeNicknamePlayer(t, s.owner)
}
registry := newPlayerRegistry(factory, time.Minute)
t.Cleanup(func() {
if err := registry.Close(context.Background()); err != nil {
t.Error(err)
}
})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.Replace(r.URL.Path, "/replay/", spineRecordingPath, 1)
transport.HTTP{SpineRecordings: spineRecordings{players: registry}}.Handler().ServeHTTP(w, r)
}))
defer server.Close()
configured, err := gameconfig.Document.Parse([]byte(`{"schema_version":1,"spine_recording":{"download_base_url":"` + server.URL + `/replay"}}`))
if err != nil {
t.Fatal(err)
}
factory.options.gameRules.SpineRecording = configured.SpineRecording
a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
reject := func(client *friendHTTPClient, path string, fields []byte) {
t.Helper()
client.seq++
body := nicknameEncrypt(t, append(appScalar(1, client.seq), fields...), client.key)
request := httptest.NewRequest(http.MethodPut, "/game"+path, bytes.NewReader(body))
request.Header.Set("Cookie", client.cookie)
response := httptest.NewRecorder()
client.handler.ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("%s accepted invalid recording operation: HTTP%d", path, response.Code)
}
}
download := func(address string, status int, want []byte) {
t.Helper()
response, err := server.Client().Get(address)
if err != nil {
t.Fatal(err)
}
defer func() { _ = response.Body.Close() }()
body, err := io.ReadAll(response.Body)
if err != nil || response.StatusCode != status || status == http.StatusOK && !bytes.Equal(body, want) {
t.Fatalf("native playback download: status=%d want=%d bytes=%d error=%v", response.StatusCode, status, len(body), err)
}
}
data := nativeInteractionRecording(t, 250)
save := append(appScalar(2, 1065193), appMessage(3, data)...)
beforeAchievements := a.send("/SpineInteractionAchievementInfo", nil, 532, 0)
beforeRewards := a.send("/SpineInteractionRewardInfo", nil, 548, 0)
reject(a, "/SpineInteractionRecordSave", append(appScalar(2, 1065193), appMessage(3, nativeInteractionRecording(t, 601000))...))
saved := a.send("/SpineInteractionRecordSave", save, 573, 0)
index, address := appValue(saved, 1), nicknameField(t, saved, 3)
if index == 0 || nicknameField(t, saved, 2) == "" || !strings.HasPrefix(address, server.URL+"/replay/") {
t.Fatal("save did not provide a usable native slot and configured playback address")
}
a.seq--
if retry := a.send("/SpineInteractionRecordSave", save, 573, 0); !bytes.Equal(retry, saved) {
t.Fatal("retry allocated another recording or changed the playback address")
}
list := appRows(a.send("/SpineInteractionRecordInfo", nil, 571, 0), 1)
if len(list) != 1 || appValue(list[0], 1) != index || appValue(list[0], 2) != 1065193 || nicknameField(t, list[0], 4) != address {
t.Fatal("saved recording cannot be selected in the native list")
}
download(address, http.StatusOK, data)
if details := appRows(a.send("/SpineInteractionRecordDetailInfo", appScalar(2, index), 572, 0), 1); len(details) != 1 || !bytes.Equal(details[0], data) {
t.Fatal("design-client playback differs from normal HTTP playback")
}
if rows := appRows(b.send("/SpineInteractionRecordInfo", nil, 571, 0), 1); len(rows) != 0 {
t.Fatal("recording list leaked another player's recordings")
}
reject(b, "/SpineInteractionRecordNameUpdate", append(appScalar(2, index), appMessage(3, []byte("ForeignName"))...))
otherSaved := b.send("/SpineInteractionRecordSave", save, 573, 0)
foreign, err := url.Parse(nicknameField(t, otherSaved, 3))
if err != nil {
t.Fatal(err)
}
foreign.Path = foreign.Path[:strings.LastIndexByte(foreign.Path, '/')+1] + address[strings.LastIndexByte(address, '/')+1:]
download(foreign.String(), http.StatusNotFound, nil)
corrupt := append([]byte(nil), data...)
corrupt[0] ^= 1
reject(a, "/SpineInteractionRecordDataUpdate", append(appScalar(2, index), appMessage(3, corrupt)...))
download(address, http.StatusOK, data)
a.send("/SpineInteractionRecordNameUpdate", append(appScalar(2, index), appMessage(3, []byte("我的回放"))...), 576, 0)
updatedData := nativeInteractionRecording(t, 250, 500)
updated := a.send("/SpineInteractionRecordDataUpdate", append(appScalar(2, index), appMessage(3, updatedData)...), 575, 0)
newAddress := nicknameField(t, updated, 1)
if newAddress == address {
t.Fatal("replacing a recording preserved the previous download capability")
}
download(address, http.StatusNotFound, nil)
download(newAddress, http.StatusOK, updatedData)
if err := registry.Close(context.Background()); err != nil {
t.Fatal(err)
}
registry = newPlayerRegistry(factory, time.Minute)
a = friendHTTPLogin(t, registry, accounts[0])
list = appRows(a.send("/SpineInteractionRecordInfo", nil, 571, 0), 1)
if len(list) != 1 || nicknameField(t, list[0], 3) != "我的回放" || nicknameField(t, list[0], 4) != newAddress {
t.Fatal("server restart lost the renamed recording or its playback link")
}
download(newAddress, http.StatusOK, updatedData)
if !bytes.Equal(a.send("/SpineInteractionAchievementInfo", nil, 532, 0), beforeAchievements) || !bytes.Equal(a.send("/SpineInteractionRewardInfo", nil, 548, 0), beforeRewards) {
t.Fatal("recording/replaying incorrectly changed interaction discoveries or reward claims")
}
for range 3 {
a.send("/SpineInteractionRecordSave", save, 573, 0)
}
reject(a, "/SpineInteractionRecordSave", save)
a.send("/SpineInteractionRecordDelete", appScalar(2, index), 574, 0)
a.seq--
a.send("/SpineInteractionRecordDelete", appScalar(2, index), 574, 0)
download(newAddress, http.StatusNotFound, nil)
newSave := a.send("/SpineInteractionRecordSave", save, 573, 0)
if appValue(newSave, 1) <= index || len(appRows(a.send("/SpineInteractionRecordInfo", nil, 571, 0), 1)) != 4 {
t.Fatal("deleting a recording did not release a slot, or reused a deleted recording identity")
}
if err := registry.Close(context.Background()); err != nil {
t.Fatal(err)
}
registry = newPlayerRegistry(factory, time.Minute)
download(newAddress, http.StatusNotFound, nil)
}
@@ -0,0 +1,102 @@
//go:build integration
package app
import (
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/world/progress"
)
func TestStoryArchiveRestoresPlayableChaptersAndSeparateStoryProgress(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0]}
s.owner = openNicknamePlayer(t, factory, s.account)
t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
for quest := 1; quest <= 46; quest++ {
if err := p.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
t.Fatal(err)
}
}
for _, quest := range []int{101, 102} {
if err := p.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
t.Fatal(err)
}
}
if err := p.progressState.SelectQuest(ctx, 1, progress.QuestSelection{Difficulty: 2}); err != nil {
t.Fatal(err)
}
var tickets []gamedata.BattleReward
for _, chapter := range []int{2, 3} {
rule := p.design.world.Story.Packs[chapter].Open
if rule == nil || rule.TicketID == 0 {
t.Fatal("chapter access prerequisite is unavailable")
}
tickets = append(tickets, gamedata.BattleReward{Type: 19, ID: rule.TicketID, Count: 1})
}
if _, err := p.ownedItems.GrantOnce(ctx, "archive-chapter-unlock", tickets); err != nil {
t.Fatal(err)
}
if err := p.progressState.ClearQuest(ctx, 1, 2, 0); err != nil {
t.Fatal(err)
}
})
chapter3Available := false
for _, row := range appRows(s.protocol(t, "/PackInfo", appScalar(1, uint64(s.commands+1))), 1) {
if appValue(row, 1) == 3 {
chapter3Available = true
if appValue(row, 8) != 0 {
t.Fatal("archive unlocked a chapter that has never been entered")
}
}
}
if !chapter3Available {
t.Fatal("chapter 3 access ticket did not make it available")
}
s.protocol(t, "/PackInGameInfo", trapRequest(uint64(s.commands+1), 3))
assertArchive := func() {
t.Helper()
gold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
packInfo := appRows(s.protocol(t, "/PackInfo", appScalar(1, uint64(s.commands+1))), 1)
chapter2, chapter3 := false, false
for _, row := range packInfo {
if appValue(row, 1) == 2 {
chapter2 = appValue(row, 8) == 1
}
if appValue(row, 1) == 3 {
chapter3 = appValue(row, 8) == 1
}
}
if !chapter2 || !chapter3 {
t.Fatal("story menu locks the free chapter despite satisfied world access")
}
preview := s.protocol(t, "/PackPreviewInfo", trapRequest(uint64(s.commands+1), 1))
got := map[uint64]uint64{}
for _, row := range appRows(preview, 2) {
got[appValue(row, 1)] = appValue(row, 2)
}
// Current pack1 QuestTitleTable separates main1..46, side101..112,
// and side301..319. StoryListPanel filters replay using each title.
if len(got) != 3 || got[1] != 46 || got[2] != 102 || got[3] != 0 {
t.Fatalf("replay lost completed story or unlocked an unplayed side story: %v", got)
}
if s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != gold {
t.Fatal("opening the story archive granted a gameplay reward")
}
}
assertArchive()
closeNicknamePlayer(t, s.owner)
s.owner = openNicknamePlayer(t, factory, s.account)
assertArchive()
other := &trapPlayerScenario{factory: factory, account: accounts[1]}
other.owner = openNicknamePlayer(t, factory, other.account)
defer closeNicknamePlayer(t, other.owner)
for _, row := range appRows(other.protocol(t, "/PackPreviewInfo", trapRequest(1, 1)), 2) {
if appValue(row, 2) != 0 {
t.Fatal("a new account inherited completed story replay")
}
}
}
@@ -261,14 +261,35 @@ func TestUnfinishedQuestPresentationSurvivesReloadWithoutRewindingRewards(t *tes
})
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
s.position(t, 5, 51)
assertHighestQuest := func(want uint64) {
t.Helper()
preview := s.protocol(t, "/PackPreviewInfo", trapRequest(uint64(s.commands+1), 5))
story := appRows(preview, 2)
if len(story) != 1 || appValue(story[0], 1) != 1 || appValue(story[0], 2) != want {
t.Fatalf("story replay frontier did not follow the completed dialogue: %v, want %d", story, want)
}
rows := appRows(s.protocol(t, "/QuestMaxClearInfo", appScalar(1, uint64(s.commands+1))), 1)
for _, row := range rows {
if appValue(row, 1) == 5 {
if got := appValue(row, 2); got != want {
t.Fatalf("client mission unlock frontier=%d, want completed quest %d", got, want)
}
return
}
}
t.Fatal("client cannot update its quest unlock frontier without a pack row")
}
assertHighestQuest(25)
beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
clear := wire.AppendVarint(trapRequest(2, 26), 3, 5)
s.protocol(t, "/QuestClear", clear)
assertHighestQuest(26)
if gold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold; gold != beforeGold+700 {
t.Fatalf("quest gold=%d want%d", gold, beforeGold+700)
}
closeNicknamePlayer(t, s.owner)
s.owner = openNicknamePlayer(t, factory, s.account)
assertHighestQuest(26)
pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint
if pending == nil || pending.PackID != 5 || pending.QuestID != 26 || pending.Phase != "complete" || pending.Timeline != "Quest_Main_26" || pending.MapID != 51 {
t.Fatalf("unfinished cinema was not restored: %+v", pending)
@@ -0,0 +1,167 @@
//go:build integration
package app
import (
"bytes"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/roster"
)
// WayPointMakePopupUI sends the destination map through TalentSkillUse, then
// IUseTalentSkillWaypointMake sends WaypointUse from the map-zero temporary
// point. Pack2's safe point is1/map21 and its temporary point is7.
func TestTalentPortalPaysOnceAndAuthorizesOnlyItsSelectedActivatedDestination(t *testing.T) {
s := newTrapPlayerScenario(t, 2)
s.position(t, 2, 22)
var caster, catalyst uint64
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.collection.GrantCostumes(ctx, "portal-owned-character", []uint64{701}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
for _, c := range p.collection.Characters() {
if p.design.talentUseDesign.Characters[c.ID].Group == 1505 {
c.TalentLevel = 1
c.TalentExp = 0
if err := p.collection.UpdateCharacter(ctx, c.ID, c); err != nil {
t.Fatal(err)
}
caster = c.InvenIndex
}
}
if caster == 0 {
t.Fatal("portal caster not owned")
}
if err := p.wallet.ExchangeOnce(ctx, "portal-catalyst", nil, []gamedata.Reward{{Type: 12, Count: 100}}); err != nil {
t.Fatal(err)
}
catalyst = p.wallet.Snapshot(ctx).Catalyst
})
cast := func(seq, mapID uint64) []byte {
return append(append(appScalar(1, seq), appScalar(2, caster)...), appScalar(3, mapID)...)
}
travel := func(seq, destination uint64) []byte {
return append(append(append(append(appScalar(1, seq), appScalar(2, 2)...), appScalar(3, 7)...), appScalar(4, destination)...), appScalar(5, 1)...)
}
assertBalance := func(want uint64) {
t.Helper()
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
if got := p.wallet.Snapshot(ctx).Catalyst; got != want {
t.Fatalf("portal catalyst balance got%d want%d", got, want)
}
})
}
s.protocol(t, "/WaypointSave", append(append(appScalar(1, 10), appScalar(2, 2)...), appScalar(3, 1)...))
s.protocol(t, "/WaypointSave", append(append(appScalar(1, 11), appScalar(2, 2)...), appScalar(3, 2)...))
if _, err := s.execute("/WaypointUse", travel(12, 1)); err == nil {
t.Fatal("temporary portal worked without a talent cast")
}
if _, err := s.execute("/TalentSkillUse", cast(13, 22)); err == nil {
t.Fatal("novice portal accepted a battle map instead of a safe destination")
}
if _, err := s.execute("/TalentSkillUse", cast(14, 141)); err == nil {
t.Fatal("portal accepted a map belonging to another pack")
}
assertBalance(catalyst)
response := s.protocol(t, "/TalentSkillUse", cast(15, 21))
assertBalance(catalyst - 20)
s.reopen(t)
if replay := s.protocol(t, "/TalentSkillUse", cast(15, 21)); !bytes.Equal(response, replay) {
t.Fatal("reopened player lost its acknowledged cast response")
}
assertBalance(catalyst - 20)
if _, err := s.execute("/WaypointUse", travel(16, 2)); err == nil {
t.Fatal("portal authorization allowed a different activated destination")
}
s.protocol(t, "/WaypointUse", travel(17, 1))
s.reopen(t)
s.protocol(t, "/WaypointUse", travel(17, 1))
if _, err := s.execute("/WaypointUse", travel(17, 2)); err == nil {
t.Fatal("travel retry changed the authorized destination")
}
if _, err := s.execute("/WaypointUse", travel(18, 1)); err == nil {
t.Fatal("one portal cast authorized a second journey")
}
assertBalance(catalyst - 20)
s.position(t, 2, 21)
s.reopen(t)
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
pack, mapID, _, err := p.worldService.TalentFieldContext(ctx)
if err != nil || pack != 2 || mapID != 21 {
t.Fatalf("native post-warp position not restored: pack%d map%d err%v", pack, mapID, err)
}
c, found := p.worldService.CharacterService().Find(ctx, caster)
if !found || c.TalentExp != 1 {
t.Fatal("portal replay duplicated or lost earned talent experience")
}
})
}
// RecvTalentSkillUpgradeResponse resets Overwhelm's shared UseCount. Current
// group305 needs10 EXP and one type8/id3 book plus1000 gold for its first upgrade.
func TestOverwhelmUpgradeRestoresSpentUsesAfterReopening(t *testing.T) {
s := newTrapPlayerScenario(t, 2)
s.position(t, 2, 22)
var caster uint64
var book []byte
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if _, err := p.collection.GrantCostumes(ctx, "overwhelm-owned-character", []uint64{1101}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
for _, c := range p.collection.Characters() {
if p.design.talentUseDesign.Characters[c.ID].Group == 305 {
c.TalentLevel, c.TalentExp = 1, 9
if err := p.collection.UpdateCharacter(ctx, c.ID, c); err != nil {
t.Fatal(err)
}
caster = c.InvenIndex
}
}
if caster == 0 {
t.Fatal("overwhelm caster not owned")
}
if err := p.wallet.ExchangeOnce(ctx, "overwhelm-resources", nil, []gamedata.Reward{{Type: 12, Count: 200}, {Type: 4, Count: 2000}}); err != nil {
t.Fatal(err)
}
items, err := p.ownedItems.GrantOnce(ctx, "overwhelm-upgrade-book", []gamedata.BattleReward{{Type: 8, ID: 3, Count: 1}})
if err != nil || len(items) != 1 {
t.Fatalf("upgrade book fixture: %v", err)
}
book = inventoryItem(items[0].InvenIndex, 3, 8, 1)
})
cast := append(appScalar(1, 20), appScalar(2, caster)...)
result := s.protocol(t, "/TalentSkillUse", cast)
if rows := appRows(result, 1); len(rows) != 1 || appValue(rows[0], 4) != 1 {
t.Fatal("cast did not consume an overwhelm use")
}
upgrade := append(append(append(appScalar(1, 21), appScalar(2, caster)...), appMessage(3, book)...), appMessage(3, inventoryItem(0, 0, 4, 1000))...)
s.protocol(t, "/TalentSkillUpgrade", upgrade)
s.reopen(t)
s.run(t, false, func(ctx command.Context, p *playerAssembly) {
var c roster.Character
c, _ = p.worldService.CharacterService().Find(ctx, caster)
if c.TalentLevel != 2 || c.TalentExp != 10 {
t.Fatalf("earned first upgrade not persisted: level%d EXP%d", c.TalentLevel, c.TalentExp)
}
info, err := p.talentUseService.PackInfo(ctx, 2)
if err != nil {
t.Fatal(err)
}
for _, row := range appRows(info, 13) {
if appValue(row, 1) == 305 {
if appValue(row, 4) != 0 {
t.Fatal("upgraded overwhelm retained its spent uses")
}
return
}
}
t.Fatal("upgraded overwhelm usage absent")
})
result = s.protocol(t, "/TalentSkillUse", append(appScalar(1, 22), appScalar(2, caster)...))
if rows := appRows(result, 1); len(rows) != 1 || appValue(rows[0], 4) != 1 {
t.Fatal("first cast after upgrading did not start from restored uses")
}
}
@@ -19,6 +19,7 @@ type Config struct {
Story StoryConfig `json:"story"`
Purchases PurchasesConfig `json:"purchases"`
TextModeration TextModerationConfig `json:"text_moderation"`
SpineRecording SpineRecordingConfig `json:"spine_recording"`
}
type TextModerationConfig struct {
@@ -42,6 +43,7 @@ var TextScopes = []string{
"nickname", "greeting", "master_title", "preset_name", "equipment_preset_name", "equipment_mark",
"monster_hunt_preset_name", "guild_raid_preset_name", "colosseum_preset_name",
"guild_name", "guild_message", "guild_notice", "room_name", "chat",
"spine_record_name",
}
func DefaultTextModeration() TextModerationConfig {
@@ -141,6 +143,7 @@ var Document = commonconfig.Document[Config]{
var problems commonconfig.Problems
realtimeRules(c.Realtime, &problems)
textModerationRules(c.TextModeration, &problems)
spineRecordingRules(c.SpineRecording, &problems)
return problems
},
Advice: func(c Config, path string) commonconfig.Problems {
@@ -16,6 +16,10 @@ var schema = commonconfig.Schema{
Title: "游戏规则",
Summary: "服务端统一的玩法规则。修改后重启服务端生效。",
Sections: []commonconfig.Section{
{ID: "spine_recording", Title: "互动录制", Help: "保存玩家的互动立绘操作记录,并供原生客户端回放。修改后重启服务端生效。", Fields: []commonconfig.Field{
{Path: "spine_recording.download_base_url", Kind: commonconfig.KindString, Label: "录制下载基础 URL", Format: "url", Placeholder: "https://game.example.com/client/spine-recordings",
Help: "留空使用本服地址。自定义地址须反向代理到本服的 /client/spine-recordings/;系统会在其后追加录制路径和访问凭据。公网须使用 HTTPS。"},
}},
{ID: "story", Title: "开局章节", Help: "首次成功初始化后永久保存在服务器状态中,之后不能更改;不能通过删除数据库切换开局。", Fields: []commonconfig.Field{
{Path: "story.start_pack_id", Kind: commonconfig.KindInteger, Label: "起始章节", Options: []commonconfig.Option{
{Value: 21, Label: "店长篇", Help: "当前客户端默认的开局,使用该篇的任务和教学流程。"},
@@ -0,0 +1,29 @@
package gameconfig
import (
"net"
"net/url"
"strings"
commonconfig "bd2server/internal/common/config"
)
type SpineRecordingConfig struct {
DownloadBaseURL string `json:"download_base_url"`
}
func spineRecordingRules(c SpineRecordingConfig, problems *commonconfig.Problems) {
if c.DownloadBaseURL == "" {
return
}
u, err := url.Parse(c.DownloadBaseURL)
if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" ||
(u.Scheme != "http" && u.Scheme != "https") || strings.ContainsAny(c.DownloadBaseURL, " \t\r\n") {
problems.Add("spine_recording.download_base_url", commonconfig.RuleFormat, "must be an absolute HTTP(S) URL without credentials, query, or fragment")
return
}
ip := net.ParseIP(u.Hostname())
if u.Scheme == "http" && !strings.EqualFold(u.Hostname(), "localhost") && (ip == nil || !ip.IsLoopback()) {
problems.Add("spine_recording.download_base_url", commonconfig.RuleFormat, "must use HTTPS outside loopback development")
}
}
@@ -0,0 +1,155 @@
package gamedata
import (
"bd2server/internal/server/protocol/wire"
"encoding/binary"
"fmt"
"slices"
)
// SocialRow contains scalar and repeated integer fields from the current client schema.
type SocialRow struct{ Fields map[int][]uint64 }
func (r SocialRow) V(n int) uint64 {
if v := r.Fields[n]; len(v) > 0 {
return v[0]
}
return 0
}
func (r SocialRow) A(n int) []uint64 { return r.Fields[n] }
type SocialTable struct {
Rows map[[2]uint64]SocialRow
Groups map[uint64][]uint64
}
func (t SocialTable) Row(group, id uint64) (SocialRow, bool) {
r, ok := t.Rows[[2]uint64{group, id}]
return r, ok
}
func loadSocialTables(root, version string, specs map[string][2]int) (map[string]SocialTable, error) {
db, done, e := openStatDatabase(root, version)
if e != nil {
return nil, e
}
defer done()
out := map[string]SocialTable{}
for name, fields := range specs {
rows, e := db.Query("SELECT ProtoBuf FROM " + name)
if e != nil {
return nil, e
}
table := SocialTable{Rows: map[[2]uint64]SocialRow{}, Groups: map[uint64][]uint64{}}
for rows.Next() {
var p []byte
if e = rows.Scan(&p); e != nil {
_ = rows.Close()
return nil, e
}
r := SocialRow{Fields: map[int][]uint64{}}
e = wire.Walk(p, func(f wire.Field) error {
if f.Type == 0 {
v, _ := binary.Uvarint(f.Value)
r.Fields[f.Number] = append(r.Fields[f.Number], v)
} else if f.Type == 2 && socialPacked(name, f.Number) {
p := f.Value
for len(p) > 0 {
v, n := binary.Uvarint(p)
if n <= 0 {
return wire.ErrMalformed
}
r.Fields[f.Number] = append(r.Fields[f.Number], v)
p = p[n:]
}
}
return nil
})
if e != nil {
_ = rows.Close()
return nil, e
}
g, id := r.V(fields[0]), r.V(fields[1])
if fields[0] == 0 {
g = 0
}
k := [2]uint64{g, id}
if _, ok := table.Rows[k]; ok {
_ = rows.Close()
return nil, fmt.Errorf("%s: duplicate row", name)
}
table.Rows[k] = r
table.Groups[g] = append(table.Groups[g], id)
}
e = rows.Err()
_ = rows.Close()
if e != nil {
return nil, e
}
for _, ids := range table.Groups {
slices.Sort(ids)
}
out[name] = table
}
return out, nil
}
func socialPacked(table string, f int) bool {
switch table {
case "CafeteriaLevelTable":
return f >= 8 && f <= 12
case "DatingDefaultTable":
return f >= 2 && f <= 4
case "DatingMessageTable":
return f >= 6 && f <= 8
case "CafeteriaUniqueNpcSpawnTable":
return f == 2 || f == 5
}
return false
}
type CafeteriaDesign struct {
Default SocialRow
Levels, Manage, Costumes, NPCs, Events, Connections, UniqueNPCs SocialTable
}
func LoadCafeteriaDesign(root, version string) (*CafeteriaDesign, error) {
t, e := loadSocialTables(root, version, map[string][2]int{"CafeteriaDefaultTable": {0, 13}, "CafeteriaLevelTable": {0, 5}, "CafeteriaManageTable": {5, 6}, "CafeteriaCostumeTable": {0, 1}, "CafeteriaNpcTable": {0, 2}, "CafeteriaEventTable": {5, 6}, "DatingCostumeTable": {0, 1}, "CafeteriaUniqueNpcSpawnTable": {0, 1}})
if e != nil {
return nil, e
}
d := &CafeteriaDesign{Levels: t["CafeteriaLevelTable"], Manage: t["CafeteriaManageTable"], Costumes: t["CafeteriaCostumeTable"], NPCs: t["CafeteriaNpcTable"], Events: t["CafeteriaEventTable"], Connections: t["DatingCostumeTable"], UniqueNPCs: t["CafeteriaUniqueNpcSpawnTable"]}
d.Default, _ = t["CafeteriaDefaultTable"].Row(0, 0)
if d.Default.V(16) == 0 || len(d.Levels.Rows) == 0 {
return nil, fmt.Errorf("cafeteria: missing design")
}
return d, nil
}
type DatingDesign struct {
Default SocialRow
Episodes, Messages, Costumes SocialTable
MessageEpisode map[uint64][2]uint64
CostumeGroup map[uint64]SocialRow
}
func LoadDatingDesign(root, version string) (*DatingDesign, error) {
t, e := loadSocialTables(root, version, map[string][2]int{"DatingDefaultTable": {0, 6}, "DatingEpisodeTable": {6, 7}, "DatingMessageTable": {1, 2}, "DatingCostumeTable": {0, 4}})
if e != nil {
return nil, e
}
d := &DatingDesign{Episodes: t["DatingEpisodeTable"], Messages: t["DatingMessageTable"], Costumes: t["DatingCostumeTable"], MessageEpisode: map[uint64][2]uint64{}, CostumeGroup: map[uint64]SocialRow{}}
d.Default, _ = t["DatingDefaultTable"].Row(0, 0)
for k, r := range d.Episodes.Rows {
for _, f := range []int{2, 3} {
if id := r.V(f); id > 0 {
d.MessageEpisode[id] = k
}
}
}
for _, r := range d.Costumes.Rows {
d.CostumeGroup[r.V(2)] = r
}
if d.Default.V(5) == 0 || len(d.Episodes.Rows) == 0 {
return nil, fmt.Errorf("dating: missing design")
}
return d, nil
}
@@ -0,0 +1,372 @@
package gamedata
import (
"database/sql"
"fmt"
"math"
"sort"
)
type CastleChallenge struct {
Type, Value1, Value2, Score uint64
Reward Reward
}
type CastleDeck struct {
ID uint64
Challenges []CastleChallenge
Rewards []Reward
}
type CastleTower struct{ Mode, ID, Previous, Deck uint64 }
type CastleScoring struct {
Base, Turn, Survival, Retry uint64
BossMultiplier float64
}
type CastleFloor struct {
ID, Previous, Boss uint64
Monsters map[uint64]uint64
Scoring CastleScoring
Rewards []Reward
}
type ScoreReward struct {
ID uint64
Score float64
Reward Reward
}
type CastleRankReward struct {
Rank uint64
Rewards []Reward
}
type CastleRewardDesign struct {
FloorRanks, TotalRanks []CastleRankReward
TotalWarEnemies []TotalWarEnemy
TotalWarPresets *PresetDesign
PackID uint64
Towers map[[2]uint64]CastleTower
Floors map[uint64]CastleFloor
Decks map[uint64]CastleDeck
Daily, TotalWarDaily []ScoreReward
Reset FieldResetSchedule
Characters map[uint64]CastleCharacter
}
type CastleCharacter struct{ Unique, Element uint64 }
func LoadCastleRewardDesign(root, version string) (*CastleRewardDesign, error) {
db, done, err := openStatDatabase(root, version)
if err != nil {
return nil, err
}
defer done()
d := &CastleRewardDesign{Towers: map[[2]uint64]CastleTower{}, Floors: map[uint64]CastleFloor{}, Decks: map[uint64]CastleDeck{}}
d.Characters = map[uint64]CastleCharacter{}
err = castleRows(db, "CharTable", func(id uint64, raw []byte) error {
u, e := optionalScalar(raw, 20)
if e != nil {
return e
}
element, e := optionalScalar(raw, 6)
if e != nil {
return e
}
d.Characters[id] = CastleCharacter{u, element}
return nil
})
if err != nil {
return nil, err
}
rows, err := db.Query("SELECT id,ProtoBuf FROM PackTable ORDER BY id")
if err != nil {
return nil, err
}
for rows.Next() {
var id uint64
var raw []byte
if err = rows.Scan(&id, &raw); err != nil {
break
}
var typ uint64
typ, err = optionalScalar(raw, 55)
if err != nil {
break
}
if typ == 4 {
if d.PackID != 0 {
err = fmt.Errorf("gamedata: multiple castle packs")
break
}
d.PackID = id
}
}
if err == nil {
err = rows.Err()
}
_ = rows.Close()
if err != nil {
return nil, err
}
if d.PackID == 0 {
return nil, fmt.Errorf("gamedata: no castle pack")
}
pack, release, err := OpenDatabase(root, version, fmt.Sprintf("pack%d", d.PackID))
if err != nil {
return nil, err
}
defer release()
for _, table := range []struct {
mode uint64
name string
}{{16, "EvilCastleGreedTowerTable"}, {19, "EvilCastleRageTowerTable"}, {20, "EvilCastleEnvyTowerTable"}} {
var previous uint64
err = castleRows(db, table.name, func(id uint64, raw []byte) error {
deck, e := optionalScalar(raw, 1)
if e != nil {
return e
}
if deck == 0 {
return fmt.Errorf("gamedata: empty castle tower deck")
}
d.Towers[[2]uint64{table.mode, id}] = CastleTower{table.mode, id, previous, deck}
previous = id
return d.loadDeck(pack, deck)
})
if err != nil {
return nil, err
}
}
var previous uint64
err = castleRows(db, "EvilCastleTable", func(id uint64, raw []byte) error {
f := CastleFloor{ID: id, Previous: previous, Monsters: map[uint64]uint64{}}
previous = id
boss, e := optionalScalar(raw, 8)
if e != nil {
return e
}
f.Boss = boss
ids, e := packedInts(raw, 18)
if e != nil {
return e
}
ids = append(ids, boss)
for _, monster := range ids {
if monster == 0 {
continue
}
var m []byte
if e = pack.QueryRow("SELECT ProtoBuf FROM FieldMonsterTable WHERE id=?", monster).Scan(&m); e != nil {
return e
}
decks, e := packedInts(m, 2)
if e != nil || len(decks) != 1 {
return fmt.Errorf("gamedata: unsupported castle monster decks")
}
f.Monsters[monster] = decks[0]
if e = d.loadDeck(pack, decks[0]); e != nil {
return e
}
}
timer, e := optionalScalar(raw, 22)
if e != nil {
return e
}
var timing []byte
if e = db.QueryRow("SELECT ProtoBuf FROM EvilCastleTimeAttackTable WHERE id=?", timer).Scan(&timing); e != nil {
return e
}
for n, p := range map[int]*uint64{5: &f.Scoring.Base, 10: &f.Scoring.Retry, 11: &f.Scoring.Survival, 12: &f.Scoring.Turn} {
*p, e = optionalScalar(timing, n)
if e != nil {
return e
}
}
f.Scoring.BossMultiplier, _, e = fixed64Double(timing, 6)
if e != nil {
return e
}
f.Rewards, e = castleRewards(raw, 4, 3, 2)
if e != nil {
return e
}
d.Floors[id] = f
return nil
})
if err != nil {
return nil, err
}
for _, item := range []struct {
table string
dst *[]ScoreReward
score, count, id, typ int
}{{"EvilCastleDailyRewardTable", &d.Daily, 5, 2, 3, 4}, {"TotalWarRewardTable", &d.TotalWarDaily, 6, 3, 4, 5}} {
err = castleRows(db, item.table, func(id uint64, raw []byte) error {
r := ScoreReward{ID: id}
var e error
if item.score == 6 {
r.Score, _, e = fixed64Double(raw, item.score)
} else {
var score uint64
score, e = optionalScalar(raw, item.score)
r.Score = float64(score)
}
if e != nil {
return e
}
r.Reward.Type, e = optionalScalar(raw, item.typ)
if e != nil {
return e
}
r.Reward.ID, e = optionalScalar(raw, item.id)
if e != nil {
return e
}
r.Reward.Count, e = optionalScalar(raw, item.count)
if e != nil {
return e
}
if math.IsNaN(r.Score) || math.IsInf(r.Score, 0) || r.Score <= 0 || r.Reward.Type == 0 || r.Reward.Count == 0 {
return fmt.Errorf("gamedata: invalid castle daily reward")
}
*item.dst = append(*item.dst, r)
return nil
})
if err != nil {
return nil, err
}
sort.Slice(*item.dst, func(i, j int) bool { return (*item.dst)[i].Score < (*item.dst)[j].Score })
}
for _, spec := range []struct {
table string
dst *[]CastleRankReward
}{{"EvilCastleRankTable", &d.FloorRanks}, {"EvilCastleTotalRankTable", &d.TotalRanks}} {
err = castleRows(db, spec.table, func(_ uint64, raw []byte) error {
rank, e := optionalScalar(raw, 6)
if e != nil {
return e
}
rewards, e := castleRewards(raw, 3, 2, 1)
if e != nil {
return e
}
if rank == 0 {
return fmt.Errorf("gamedata: invalid castle reward rank")
}
*spec.dst = append(*spec.dst, CastleRankReward{rank, rewards})
return nil
})
if err != nil {
return nil, err
}
sort.Slice(*spec.dst, func(i, j int) bool { return (*spec.dst)[i].Rank < (*spec.dst)[j].Rank })
}
d.Reset, err = LoadFieldResetSchedule(root, version)
if err != nil {
return nil, err
}
d.TotalWarEnemies, err = loadTotalWarEnemies(root, version)
if err != nil {
return nil, err
}
d.TotalWarPresets, err = loadTotalWarPresetDesign(root, version)
return d, err
}
func castleRows(db *sql.DB, table string, visit func(uint64, []byte) error) error {
rows, e := db.Query("SELECT id,ProtoBuf FROM " + table + " ORDER BY id")
if e != nil {
return e
}
type row struct {
id uint64
raw []byte
}
var records []row
for rows.Next() {
var id uint64
var raw []byte
if e = rows.Scan(&id, &raw); e != nil {
_ = rows.Close()
return e
}
records = append(records, row{id, raw})
}
e = rows.Err()
_ = rows.Close()
if e != nil {
return e
}
for _, r := range records {
if e = visit(r.id, r.raw); e != nil {
return fmt.Errorf("gamedata: %s/%d: %w", table, r.id, e)
}
}
return nil
}
func castleRewards(raw []byte, typ, id, count int) ([]Reward, error) {
ts, e := packedInts(raw, typ)
if e != nil {
return nil, e
}
ids, e := packedInts(raw, id)
if e != nil {
return nil, e
}
cs, e := packedInts(raw, count)
if e != nil {
return nil, e
}
if len(ts) != len(ids) || len(ts) != len(cs) {
return nil, fmt.Errorf("gamedata: castle reward array mismatch")
}
var out []Reward
for i, t := range ts {
if t == 0 && ids[i] == 0 && cs[i] == 0 {
continue
}
if t == 0 || cs[i] == 0 {
return nil, fmt.Errorf("gamedata: invalid castle reward")
}
out = append(out, Reward{Type: t, ID: ids[i], Count: cs[i]})
}
return out, nil
}
func (d *CastleRewardDesign) loadDeck(db *sql.DB, id uint64) error {
if _, ok := d.Decks[id]; ok {
return nil
}
var raw []byte
if e := db.QueryRow("SELECT ProtoBuf FROM BattleDeckTable WHERE id=?", id).Scan(&raw); e != nil {
return e
}
deck := CastleDeck{ID: id}
types, e := packedInts(raw, 6)
if e != nil {
return e
}
arrays := map[int][]uint64{}
for _, n := range []int{7, 8, 9, 10, 11, 12} {
arrays[n], e = packedInts(raw, n)
if e != nil {
return e
}
if len(arrays[n]) != 0 && len(arrays[n]) != len(types) {
return fmt.Errorf("gamedata: castle challenge array mismatch")
}
}
for i, t := range types {
if t < 1 || t > 8 {
return fmt.Errorf("gamedata: unknown castle challenge type")
}
c := CastleChallenge{Type: t}
for n, p := range map[int]*uint64{7: &c.Value1, 8: &c.Value2, 9: &c.Reward.Count, 10: &c.Reward.ID, 11: &c.Reward.Type, 12: &c.Score} {
if len(arrays[n]) > 0 {
*p = arrays[n][i]
}
}
deck.Challenges = append(deck.Challenges, c)
}
deck.Rewards, e = castleRewards(raw, 36, 34, 33)
if e != nil {
return e
}
d.Decks[id] = deck
return nil
}
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more