feat(all): complete social gameplay and streamline client workflows

- Complete friend likes and gifts, supporter rentals, room gameplay, public profiles and rankings.
- Reconcile historical achievements and titles without repeating claims; correct progress counters.
- Fix chapter checkpoints, field reward restoration and map exploration statistics.
- Isolate inventory overrides by account and expose authenticated game UID lookup.
- Add AI translation options, bounded caching and usage diagnostics; fix live toggles, fonts and popup layout.
- Cache unified plugin builds, SDK preparation, version sources and reobfuscation; archive Unity logs and use native C# text formatting.
- Add Python game/resource downloads with automatic Client Studio setup; remove local mail tooling from version control.
This commit is contained in:
Flechazo committed 2026-10-13 12:36:34 +08:00
1 parent 8d5d7dfb76
commit 3e7aa33cf4
122 files changed
+8306 -699

No files matched your search

+17 -1
View File
@@ -6,6 +6,8 @@ import (
"os"
"os/exec"
"strings"
clientplugin "bd2server/internal/client/plugin"
)
func main() {
@@ -24,6 +26,7 @@ func usage() {
bd2w build [-GameDir directory] [-SkipTests] [-SchedulesOnly]
bd2w runClient [client options]
bd2w runClient2 [--instance player2] [--game-dir directory]
bd2w plugins [--game-dir directory]
bd2w runServer [server options]
bd2w check-csharp [GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment]
bd2w sdk pack [--game-dir directory] [--package-version version] [--output-directory directory]
@@ -42,7 +45,7 @@ func run(args []string) error {
usage()
return nil
}
if args[0] != "build" && args[0] != "runClient" && args[0] != "runClient2" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" {
if args[0] != "build" && args[0] != "runClient" && args[0] != "runClient2" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" && args[0] != "plugins" {
return fmt.Errorf("unknown task %q; use --help for available commands", args[0])
}
if len(args) == 2 && isHelp(args[1]) {
@@ -59,6 +62,19 @@ func run(args []string) error {
}
t := task{root, native}
switch args[0] {
case "plugins":
opts, err := parseOptions(args[1:])
if err != nil {
return err
}
if opts.skipTests || opts.schedulesOnly {
return errors.New("plugins accepts only --game-dir")
}
game, _, _, err := t.gameDirectory(opts.gameDir)
if err != nil {
return err
}
return clientplugin.BuildDevelopment(t.root, game, os.Stdout)
case "runClient2":
return t.runClient2(args[1:])
case "runClient":
+5 -6
View File
@@ -3,11 +3,13 @@ package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
clientconfig "bd2server/internal/client/config"
clientinstance "bd2server/internal/client/instance"
clientplugin "bd2server/internal/client/plugin"
clientsetup "bd2server/internal/client/setup"
)
@@ -21,7 +23,7 @@ func (t task) runClient2(args []string) error {
if fs.NArg() != 0 {
return fmt.Errorf("unexpected argument %q", fs.Arg(0))
}
game, managed, bep, err := t.gameDirectory(*gameDir)
game, _, _, err := t.gameDirectory(*gameDir)
if err != nil {
return err
}
@@ -52,11 +54,8 @@ func (t task) runClient2(args []string) error {
return fmt.Errorf("prepare second client's resources: %w", err)
}
if instance.Created {
for _, name := range []string{"LocalIdentity", "LoginUI", "CashShop", "FChat"} {
project := filepath.Join(t.root, "plugins", name, name+".csproj")
if err := t.command("dotnet", "build", project, "-c", "Release", "-p:GameDir="+game, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+bep, "--nologo"); err != nil {
return err
}
if err := clientplugin.BuildDevelopment(t.root, game, os.Stdout); err != nil {
return err
}
plugins := func(name string) string {
return filepath.Join(t.root, "plugins", name, "bin", "Release", "netstandard2.1", "BD2"+name+".dll")
+6 -5
View File
@@ -10,6 +10,8 @@ import (
"regexp"
"sort"
"strings"
clientplugin "bd2server/internal/client/plugin"
)
type buildOptions struct {
@@ -115,7 +117,7 @@ func (t task) build(opts buildOptions) error {
fmt.Println("Built schedule release:", out)
return nil
}
game, managed, bep, err := t.gameDirectory(opts.gameDir)
game, _, _, err := t.gameDirectory(opts.gameDir)
if err != nil {
return err
}
@@ -157,12 +159,11 @@ func (t task) build(opts buildOptions) error {
if err := t.command("go", "build", "-tags", "release,production", "-trimpath", "-ldflags", clientFlags, "-o", filepath.Join(client, "bd2client"+ext), "./cmd/bd2client"); err != nil {
return err
}
if err := clientplugin.BuildDevelopment(t.root, game, os.Stdout); err != nil {
return err
}
var shared []byte
for _, plugin := range []string{"LocalIdentity", "LoginUI", "CashShop", "FChat"} {
project := filepath.Join(t.root, "plugins", plugin, plugin+".csproj")
if err := t.command("dotnet", "build", project, "-c", "Release", "-p:GameDir="+game, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+bep, "--nologo"); err != nil {
return err
}
out := filepath.Join(t.root, "plugins", plugin, "bin", "Release", "netstandard2.1")
raw, err := os.ReadFile(filepath.Join(out, "BD2.GameNames.dll"))
if err != nil {
+3 -129
View File
@@ -1,32 +1,12 @@
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
)
type versionSourceConfig struct {
GameVersion string `json:"game_version"`
ClientVersion string `json:"client_version"`
ServerVersion string `json:"server_version"`
GameDataVersion string `json:"game_data_version"`
BundleVersion string `json:"bundle_version"`
SeedDirectory string `json:"seed_directory"`
Plugins struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
} `json:"plugins"`
}
"bd2server/internal/buildversion"
)
func (t task) generateVersionSource(args []string) error {
options := flag.NewFlagSet("version-source", flag.ContinueOnError)
@@ -40,111 +20,5 @@ func (t task) generateVersionSource(args []string) error {
if options.NArg() != 0 || *config == "" || *output == "" || *plugin == "" {
return errors.New("version-source requires --config, --output and --plugin, with no positional arguments")
}
var versions versionSourceConfig
if err := readJSON(*config, &versions, true); err != nil {
return err
}
pluginVersion, err := versions.validate(*plugin)
if err != nil {
return fmt.Errorf("%s: %w", *config, err)
}
configPath, err := filepath.Abs(*config)
if err != nil {
return err
}
outputPath, err := filepath.Abs(*output)
if err != nil {
return err
}
if outputPath == configPath {
return errors.New("version-source output must not replace the version configuration")
}
configInfo, err := os.Stat(configPath)
if err != nil {
return err
}
if outputInfo, statErr := os.Stat(outputPath); statErr == nil && os.SameFile(configInfo, outputInfo) {
return errors.New("version-source output must not replace the version configuration")
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
source := fmt.Sprintf(`// Generated from versions.json. Do not edit.
namespace Bd2Build
{
internal static class Versions
{
internal const string Game = "%s";
internal const string ClientRelease = "%s";
internal const string GameData = "%s";
internal const string Bundle = "%s";
internal const string Plugin = "%s";
}
}
`, versions.GameVersion, versions.ClientVersion, versions.GameDataVersion, versions.BundleVersion, pluginVersion)
return writeVersionSource(outputPath, []byte(source))
}
func (c versionSourceConfig) validate(plugin string) (string, error) {
plugins := map[string]string{"local_identity": c.Plugins.LocalIdentity, "capture_environment": c.Plugins.CaptureEnvironment, "login_ui": c.Plugins.LoginUI, "cash_shop": c.Plugins.CashShop, "fchat": c.Plugins.FChat}
selected, found := plugins[plugin]
if !found {
return "", fmt.Errorf("unsupported plugin %q", plugin)
}
semver := regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
resource := regexp.MustCompile(`^[0-9]{14}$`)
if !semver.MatchString(c.GameVersion) {
return "", errors.New("game_version must be a numeric three-part version")
}
for _, key := range []string{"local_identity", "capture_environment", "login_ui", "cash_shop", "fchat"} {
if !semver.MatchString(plugins[key]) {
return "", fmt.Errorf("plugins.%s must be a numeric three-part version", key)
}
}
for _, release := range []struct{ name, value, component string }{{"client_version", c.ClientVersion, "client"}, {"server_version", c.ServerVersion, "server"}} {
prefix := c.GameVersion + "+" + release.component + "."
if suffix, found := strings.CutPrefix(release.value, prefix); !found || !semver.MatchString(suffix) {
return "", fmt.Errorf("%s must be %sX.Y.Z", release.name, prefix)
}
}
for _, version := range []struct{ name, value string }{{"game_data_version", c.GameDataVersion}, {"bundle_version", c.BundleVersion}} {
if !resource.MatchString(version.value) {
return "", fmt.Errorf("%s must be a 14-digit version", version.name)
}
}
seed := filepath.Clean(filepath.FromSlash(strings.ReplaceAll(c.SeedDirectory, `\`, "/")))
if c.SeedDirectory == "" || filepath.IsAbs(seed) || strings.Contains(c.SeedDirectory, ":") || seed == ".." || strings.HasPrefix(seed, ".."+string(filepath.Separator)) {
return "", errors.New("seed_directory must be a non-empty relative path below the version file")
}
return selected, nil
}
func writeVersionSource(path string, source []byte) (err error) {
current, err := os.ReadFile(path)
if err == nil && bytes.Equal(current, source) {
return nil
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
file, err := os.CreateTemp(filepath.Dir(path), ".version-source-*")
if err != nil {
return err
}
temporary := file.Name()
defer func() {
if removeErr := os.Remove(temporary); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
err = errors.Join(err, removeErr)
}
}()
_, writeErr := file.Write(source)
if writeErr == nil {
writeErr = file.Sync()
}
if closeErr := file.Close(); writeErr != nil || closeErr != nil {
return errors.Join(writeErr, closeErr)
}
return os.Rename(temporary, path)
return buildversion.Generate(*config, *output, *plugin)
}
+3 -33
View File
@@ -3,7 +3,6 @@
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
@@ -14,6 +13,7 @@ import (
"strings"
clientlayout "bd2server/internal/client/layout"
clientplugin "bd2server/internal/client/plugin"
)
type clientDevelopmentConfig struct {
@@ -174,36 +174,6 @@ func buildDevelopmentPlugins(root, gameDir string) error {
if !clientDevelopmentFile(filepath.Join(installation.BepInEx, "core", "BepInEx.dll")) {
return nil
}
projects := []string{
filepath.Join(root, "plugins", "LocalIdentity", "LocalIdentity.csproj"),
filepath.Join(root, "plugins", "LoginUI", "LoginUI.csproj"),
filepath.Join(root, "plugins", "CashShop", "CashShop.csproj"),
filepath.Join(root, "plugins", "FChat", "FChat.csproj"),
}
for _, project := range projects {
fmt.Fprintf(os.Stderr, "bd2client: preparing development plugin %s; first-time game source generation may take several minutes\n", filepath.Base(project))
command := exec.Command(
"dotnet", "build", project, "-c", "Release",
"-p:GameDir="+filepath.Clean(gameDir),
"-p:BD2ManagedDir="+filepath.Join(installation.Data, "Managed"),
"-p:BD2BepInExDir="+installation.BepInEx,
"--nologo",
)
command.Dir = root
// SDK preparation can decompile the entire game before the window opens.
// Stream progress immediately, while retaining diagnostics for failures.
var output bytes.Buffer
writer := io.MultiWriter(os.Stderr, &output)
command.Stdout = writer
command.Stderr = writer
err := command.Run()
if err != nil {
message := strings.TrimSpace(output.String())
if message == "" {
message = err.Error()
}
return fmt.Errorf("build development plugin %s: %s", filepath.Base(project), message)
}
}
return nil
fmt.Fprintln(os.Stderr, "bd2client: preparing four development plugins; cached inputs will be reused")
return clientplugin.BuildDevelopment(root, gameDir, os.Stderr)
}
+7
View File
@@ -19,6 +19,13 @@ type clientRunOptions struct {
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "prepare" {
if err := prepareClient(os.Args[2:]); err != nil {
fmt.Fprintln(os.Stderr, "bd2client prepare:", err)
os.Exit(1)
}
return
}
relaunched, err := relaunchDevelopmentIfNeeded(os.Args[1:])
if err != nil {
clientapp.ShowFatalError(err)
+49
View File
@@ -0,0 +1,49 @@
package main
import (
"context"
"flag"
"fmt"
"time"
clientconfig "bd2server/internal/client/config"
clientsetup "bd2server/internal/client/setup"
)
func prepareClient(args []string) error {
fs := flag.NewFlagSet("bd2client prepare", flag.ContinueOnError)
gameDir := fs.String("game-dir", "", "game installation directory")
origin := fs.String("server-origin", "", "game server HTTPS origin")
resources := fs.String("resource-dir", "", "directory containing ServerData and GameData")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() != 0 || *gameDir == "" || *origin == "" || *resources == "" {
return fmt.Errorf("prepare requires --game-dir, --server-origin and --resource-dir")
}
versions, err := clientconfig.ReleaseVersionsBesideExecutable()
if err != nil {
return err
}
settings, err := clientconfig.Normalize(clientconfig.Settings{ServerOrigin: *origin, CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: *resources})
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if _, err := clientsetup.FetchResourcePolicy(ctx, nil, settings, versions); err != nil {
return err
}
if _, err := clientsetup.Patch(*gameDir, settings, versions); err != nil {
return err
}
if _, err := clientsetup.InstallPlugins(*gameDir, settings, versions, "", "", "", ""); err != nil {
return err
}
if err := clientconfig.SavePreferences(*gameDir); err != nil {
return err
}
fmt.Println("Client prepared:", versions.GameVersion)
fmt.Println("Server:", settings.ServerOrigin)
return nil
}
+167
View File
@@ -0,0 +1,167 @@
package buildversion
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
)
type Config struct {
GameVersion string `json:"game_version"`
ClientVersion string `json:"client_version"`
ServerVersion string `json:"server_version"`
GameDataVersion string `json:"game_data_version"`
BundleVersion string `json:"bundle_version"`
SeedDirectory string `json:"seed_directory"`
Plugins struct {
LocalIdentity string `json:"local_identity"`
CaptureEnvironment string `json:"capture_environment"`
LoginUI string `json:"login_ui"`
CashShop string `json:"cash_shop"`
FChat string `json:"fchat"`
} `json:"plugins"`
}
func readConfig(path string, config *Config) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
if err := decoder.Decode(config); err != nil {
return err
}
var trailing any
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
return errors.New("version configuration must contain exactly one JSON object")
}
return nil
}
func GameVersion(path string) (string, error) {
var config Config
if err := readConfig(path, &config); err != nil {
return "", err
}
if _, err := config.validate("local_identity"); err != nil {
return "", err
}
return config.GameVersion, nil
}
func Generate(config, output, plugin string) error {
var versions Config
if err := readConfig(config, &versions); err != nil {
return err
}
pluginVersion, err := versions.validate(plugin)
if err != nil {
return fmt.Errorf("%s: %w", config, err)
}
configPath, err := filepath.Abs(config)
if err != nil {
return err
}
outputPath, err := filepath.Abs(output)
if err != nil {
return err
}
if outputPath == configPath {
return errors.New("version-source output must not replace the version configuration")
}
configInfo, err := os.Stat(configPath)
if err != nil {
return err
}
if outputInfo, statErr := os.Stat(outputPath); statErr == nil && os.SameFile(configInfo, outputInfo) {
return errors.New("version-source output must not replace the version configuration")
} else if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return statErr
}
source := fmt.Sprintf(`// Generated from versions.json. Do not edit.
namespace Bd2Build
{
internal static class Versions
{
internal const string Game = "%s";
internal const string ClientRelease = "%s";
internal const string GameData = "%s";
internal const string Bundle = "%s";
internal const string Plugin = "%s";
}
}
`, versions.GameVersion, versions.ClientVersion, versions.GameDataVersion, versions.BundleVersion, pluginVersion)
return writeVersionSource(outputPath, []byte(source))
}
func (c Config) validate(plugin string) (string, error) {
plugins := map[string]string{"local_identity": c.Plugins.LocalIdentity, "capture_environment": c.Plugins.CaptureEnvironment, "login_ui": c.Plugins.LoginUI, "cash_shop": c.Plugins.CashShop, "fchat": c.Plugins.FChat}
selected, found := plugins[plugin]
if !found {
return "", fmt.Errorf("unsupported plugin %q", plugin)
}
semver := regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
resource := regexp.MustCompile(`^[0-9]{14}$`)
if !semver.MatchString(c.GameVersion) {
return "", errors.New("game_version must be a numeric three-part version")
}
for _, key := range []string{"local_identity", "capture_environment", "login_ui", "cash_shop", "fchat"} {
if !semver.MatchString(plugins[key]) {
return "", fmt.Errorf("plugins.%s must be a numeric three-part version", key)
}
}
for _, release := range []struct{ name, value, component string }{{"client_version", c.ClientVersion, "client"}, {"server_version", c.ServerVersion, "server"}} {
prefix := c.GameVersion + "+" + release.component + "."
if suffix, found := strings.CutPrefix(release.value, prefix); !found || !semver.MatchString(suffix) {
return "", fmt.Errorf("%s must be %sX.Y.Z", release.name, prefix)
}
}
for _, version := range []struct{ name, value string }{{"game_data_version", c.GameDataVersion}, {"bundle_version", c.BundleVersion}} {
if !resource.MatchString(version.value) {
return "", fmt.Errorf("%s must be a 14-digit version", version.name)
}
}
seed := filepath.Clean(filepath.FromSlash(strings.ReplaceAll(c.SeedDirectory, `\`, "/")))
if c.SeedDirectory == "" || filepath.IsAbs(seed) || strings.Contains(c.SeedDirectory, ":") || seed == ".." || strings.HasPrefix(seed, ".."+string(filepath.Separator)) {
return "", errors.New("seed_directory must be a non-empty relative path below the version file")
}
return selected, nil
}
func writeVersionSource(path string, source []byte) (err error) {
current, err := os.ReadFile(path)
if err == nil && bytes.Equal(current, source) {
return nil
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
file, err := os.CreateTemp(filepath.Dir(path), ".version-source-*")
if err != nil {
return err
}
temporary := file.Name()
defer func() {
if removeErr := os.Remove(temporary); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
err = errors.Join(err, removeErr)
}
}()
_, writeErr := file.Write(source)
if writeErr == nil {
writeErr = file.Sync()
}
if closeErr := file.Close(); writeErr != nil || closeErr != nil {
return errors.Join(writeErr, closeErr)
}
return os.Rename(temporary, path)
}
+10 -2
View File
@@ -29,7 +29,13 @@ func (i Instance) WriteLauncher() (string, error) {
command.WriteByte('"')
}
var body strings.Builder
body.WriteString("Option Explicit\r\nDim shell, environment\r\nSet shell = CreateObject(\"WScript.Shell\")\r\nSet environment = shell.Environment(\"Process\")\r\n")
body.WriteString("Option Explicit\r\nDim shell, environment, files, processes, process, previousLog, pendingLog\r\nSet shell = CreateObject(\"WScript.Shell\")\r\nSet environment = shell.Environment(\"Process\")\r\n")
body.WriteString(`Set processes = GetObject("winmgmts:\\.\root\cimv2").ExecQuery("SELECT ExecutablePath FROM Win32_Process WHERE Name = 'BrownDust II.exe'")`)
body.WriteString("\r\nFor Each process In processes\r\nIf Not IsNull(process.ExecutablePath) Then\r\nIf LCase(process.ExecutablePath) = LCase(")
body.WriteString(quote(installation.Executable))
body.WriteString(") Then\r\nMsgBox \"This client instance is already running.\", 48, \"BD2\"\r\nWScript.Quit 1\r\nEnd If\r\nEnd If\r\nNext\r\nSet files = CreateObject(\"Scripting.FileSystemObject\")\r\npreviousLog = ")
body.WriteString(quote(filepath.Join(i.Root, "logs", "Player.log")))
body.WriteString("\r\nIf files.FileExists(previousLog) Then\r\npendingLog = files.BuildPath(files.GetParentFolderName(previousLog), \"bd2-previous.\" & files.GetTempName & \".Player-prev.log\")\r\nfiles.MoveFile previousLog, pendingLog\r\nEnd If\r\n")
body.WriteString(`environment("BD2_CLIENT_INSTANCE_ID") = `)
body.WriteString(quote(i.ID))
body.WriteString("\r\n")
@@ -72,7 +78,9 @@ func (i Instance) WriteLauncher() (string, error) {
body.WriteByte('\n')
body.WriteString("cd ")
body.WriteString(quote(installation.Root))
body.WriteString("\nexec ")
body.WriteString("\nprevious_log=")
body.WriteString(quote(filepath.Join(i.Root, "logs", "Player.log")))
body.WriteString("\nif [ -f \"$previous_log\" ]; then\n pending_log=\"$(dirname \"$previous_log\")/bd2-previous.$(date +%Y%m%d%H%M%S).$$.Player-prev.log\"\n ln \"$previous_log\" \"$pending_log\"\n rm \"$previous_log\"\nfi\nexec ")
body.WriteString(quote(installation.Executable))
for _, arg := range args {
body.WriteByte(' ')
+229
View File
@@ -0,0 +1,229 @@
package plugin
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"bd2server/internal/buildversion"
clientlayout "bd2server/internal/client/layout"
)
var developmentProjects = []struct{ name, key string }{
{"LocalIdentity", "local_identity"}, {"LoginUI", "login_ui"}, {"CashShop", "cash_shop"}, {"FChat", "fchat"},
}
// BuildDevelopment compiles the client plugins as one dependency graph, sharing
// the game SDK and version preparation across the four entry projects.
func BuildDevelopment(root, gameDir string, progress io.Writer) error {
started := time.Now()
installation, err := clientlayout.Resolve(gameDir)
if err != nil {
return err
}
root, err = filepath.Abs(root)
if err != nil {
return err
}
managed := filepath.Join(installation.Data, "Managed")
identity := sha256.Sum256([]byte(root + "\x00" + managed + "\x00" + installation.BepInEx))
work := filepath.Join(root, ".build", "client-plugins", hex.EncodeToString(identity[:12]))
if err := os.MkdirAll(work, 0o755); err != nil {
return err
}
unlock, err := acquireBuildLock(filepath.Dir(work), progress)
if err != nil {
return err
}
defer unlock()
digestPath := filepath.Join(work, "file-digests.json")
digests := loadFileDigestCache(digestPath)
defer func() { _ = digests.save(digestPath) }()
_, _ = fmt.Fprintln(progress, "Client plugins: checking source, game DLL and output fingerprints...")
cacheStarted := time.Now()
inputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
if err != nil {
return err
}
fingerprint := digestInputs(inputs)
manifestPath := filepath.Join(work, "build.json")
if currentBuild(manifestPath, fingerprint, digests) {
_, _ = fmt.Fprintf(progress, "Client plugins: inputs and outputs unchanged; SDK, versions, compilation and reobfuscation reused (%s)\n", time.Since(started).Round(time.Millisecond))
return nil
}
_, _ = fmt.Fprintf(progress, "Client plugins: cache check completed in %s; preparing changed inputs...\n", time.Since(cacheStarted).Round(time.Millisecond))
versionConfig := filepath.Join(root, "versions.json")
gameVersion, err := buildversion.GameVersion(versionConfig)
if err != nil {
return err
}
sdkDir := filepath.Join(work, "sdk")
versionDir := filepath.Join(work, "versions")
compileInputsDir := filepath.Join(work, "compile-inputs")
sdkInputs := filepath.Join(compileInputsDir, "sdk.g.cs")
namesInputs := filepath.Join(compileInputsDir, "names.g.cs")
sdkFingerprint := dependencyFingerprint(root, inputs, "GameSdk")
namesFingerprint := dependencyFingerprint(root, inputs, "GameNames")
sdkInputsKey := map[string]string{"sdk": sdkFingerprint, "game_version": gameVersion}
for file, sum := range inputs {
if strings.HasPrefix(file, managed+string(filepath.Separator)) || strings.HasPrefix(file, installation.BepInEx+string(filepath.Separator)) {
sdkInputsKey[file] = sum
}
}
sdkKey := digestInputs(sdkInputsKey)
sdkManifestPath := filepath.Join(work, "sdk-build.json")
if err := writeBuildInput(sdkInputs, sdkFingerprint); err != nil {
return err
}
if err := writeBuildInput(namesInputs, namesFingerprint); err != nil {
return err
}
prepareStarted := time.Now()
sdkTool := filepath.Join(root, "plugins", "GameSdk", "bin", "Release", "net8.0", "GameSdk.dll")
if !currentBuild(sdkManifestPath, sdkKey, digests) {
_, _ = fmt.Fprintln(progress, "Client plugins: preparing the shared game SDK...")
if err := runPluginBuild(root, progress, "build", filepath.Join(root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-v:quiet", "-clp:NoSummary", "-p:BD2SdkCompileInputsFile="+sdkInputs); err != nil {
return err
}
if err := runPluginBuild(root, progress, sdkTool, "prepare-embedded", filepath.Join(managed, "Assembly-CSharp.dll"), sdkDir, "--game-version", gameVersion); err != nil {
return err
}
_, _ = fmt.Fprintf(progress, "Client plugins: SDK preparation completed in %s\n", time.Since(prepareStarted).Round(time.Millisecond))
} else {
_, _ = fmt.Fprintf(progress, "Client plugins: shared SDK reused (%s)\n", time.Since(prepareStarted).Round(time.Millisecond))
}
sharedRaw, err := os.ReadFile(filepath.Join(sdkDir, "shared-sdk.txt"))
if err != nil {
return err
}
shared := strings.TrimSpace(string(sharedRaw))
versionStarted := time.Now()
_, _ = fmt.Fprintln(progress, "Client plugins: generating version and compilation fingerprints...")
for _, project := range developmentProjects {
if err := buildversion.Generate(versionConfig, filepath.Join(versionDir, project.key+".g.cs"), project.key); err != nil {
return err
}
inputStamp, err := projectFingerprint(root, inputs, project.name, filepath.Join(versionDir, project.key+".g.cs"))
if err != nil {
return err
}
if err := writeBuildInput(filepath.Join(compileInputsDir, project.key+".g.cs"), inputStamp); err != nil {
return err
}
}
_, _ = fmt.Fprintf(progress, "Client plugins: version sources prepared in %s\n", time.Since(versionStarted).Round(time.Millisecond))
compileStarted := time.Now()
_, _ = fmt.Fprintln(progress, "Client plugins: compiling all four plugins as one parallel dependency graph...")
if err := runPluginBuild(root, progress, "build", filepath.Join(root, "plugins", "ClientPlugins.proj"), "-m", "-c", "Release", "--nologo",
"-p:GameDir="+installation.Root, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+installation.BepInEx,
"-p:BD2SdkPrepared=true", "-p:BD2SdkDir="+sdkDir, "-p:BD2SharedSdkDir="+shared,
"-p:BD2PreparedVersionDir="+versionDir, "-p:BD2CompileInputsDir="+compileInputsDir, "-p:BD2NamesCompileInputsFile="+namesInputs, "-v:quiet", "-clp:NoSummary"); err != nil {
return err
}
_, _ = fmt.Fprintf(progress, "Client plugins: compilation and reobfuscation completed in %s\n", time.Since(compileStarted).Round(time.Millisecond))
outputs := []string{sdkTool, sdkInputs, namesInputs, strings.TrimSuffix(sdkTool, ".dll") + ".deps.json", strings.TrimSuffix(sdkTool, ".dll") + ".runtimeconfig.json",
filepath.Join(sdkDir, "GameSdkIdentity.g.cs"), filepath.Join(sdkDir, "shared-sdk.txt"), filepath.Join(sdkDir, "GameSourceNavigation.props"),
filepath.Join(shared, "ref", "Assembly-CSharp.Readable.dll"), filepath.Join(shared, "names.json"), filepath.Join(shared, "names.json.gz")}
for _, name := range []string{"ready.txt", "navigation.json", "GameSourceNavigation.props", "Assembly-CSharp.Readable.dll", "Assembly-CSharp.Readable.xml",
"ref/Assembly-CSharp.Readable.xml", "lib/Assembly-CSharp.Readable.dll", "lib/Assembly-CSharp.Readable.pdb", "lib/Assembly-CSharp.Readable.xml", "lib/navigation.json"} {
outputs = append(outputs, filepath.Join(shared, filepath.FromSlash(name)))
}
toolDependencies, err := filepath.Glob(filepath.Join(filepath.Dir(sdkTool), "*.dll"))
if err != nil {
return err
}
outputs = append(outputs, toolDependencies...)
sdkOutputs := append([]string(nil), outputs...)
for _, project := range developmentProjects {
output := filepath.Join(root, "plugins", project.name, "bin", "Release", "netstandard2.1")
outputs = append(outputs, filepath.Join(output, "BD2"+project.name+".dll"), filepath.Join(output, GameNames.fileName), filepath.Join(versionDir, project.key+".g.cs"), filepath.Join(compileInputsDir, project.key+".g.cs"))
}
sums := make(map[string]string, len(outputs))
for _, output := range outputs {
sum, err := digests.digest(output)
if err != nil {
return err
}
sums[output] = sum
}
finalInputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
if err != nil {
return err
}
if digestInputs(finalInputs) != fingerprint {
return errors.New("client plugin inputs changed during compilation; run preparation again")
}
if err := saveBuildManifest(manifestPath, buildManifest{Input: fingerprint, Outputs: sums}); err != nil {
return err
}
sdkSums := make(map[string]string, len(sdkOutputs))
for _, output := range sdkOutputs {
sdkSums[output] = sums[output]
}
if err := saveBuildManifest(sdkManifestPath, buildManifest{Input: sdkKey, Outputs: sdkSums}); err != nil {
return err
}
_, _ = fmt.Fprintf(progress, "Client plugins: all four ready in %s\n", time.Since(started).Round(time.Millisecond))
return nil
}
func acquireBuildLock(work string, progress io.Writer) (func(), error) {
lock := filepath.Join(work, "build.lock")
file, err := os.OpenFile(lock, os.O_CREATE|os.O_RDWR, 0o644)
if err != nil {
return nil, err
}
started := time.Now()
announced := false
lastNotice := started
for {
locked, err := tryBuildFileLock(file)
if err != nil {
_ = file.Close()
return nil, err
}
if locked {
return func() { _ = file.Close() }, nil
}
if time.Since(started) > 30*time.Minute {
_ = file.Close()
return nil, fmt.Errorf("client plugin build lock still held at %s", lock)
}
if !announced {
_, _ = fmt.Fprintln(progress, "Client plugins: waiting for the current build to finish...")
announced = true
lastNotice = time.Now()
} else if time.Since(lastNotice) >= time.Minute {
_, _ = fmt.Fprintf(progress, "Client plugins: still waiting for the current build (%s)...\n", time.Since(started).Round(time.Second))
lastNotice = time.Now()
}
time.Sleep(250 * time.Millisecond)
}
}
func runPluginBuild(root string, progress io.Writer, args ...string) error {
command := exec.Command("dotnet", args...)
command.Dir = root
for _, entry := range os.Environ() {
key, _, _ := strings.Cut(entry, "=")
if !strings.EqualFold(key, "BD2_GAME_SDK_CACHE") {
command.Env = append(command.Env, entry)
}
}
command.Env = append(command.Env, "BD2_GAME_SDK_CACHE="+filepath.Join(root, ".build", "game-sdk"))
var output bytes.Buffer
command.Stdout = io.MultiWriter(progress, &output)
command.Stderr = command.Stdout
if err := command.Run(); err != nil {
return fmt.Errorf("build client plugins: %w\n%s", err, strings.TrimSpace(output.String()))
}
return nil
}
+264
View File
@@ -0,0 +1,264 @@
package plugin
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
)
type buildManifest struct {
Input string `json:"input"`
Outputs map[string]string `json:"outputs"`
}
type cachedFileDigest struct {
Stamp string `json:"stamp"`
Hash string `json:"hash"`
}
type fileDigestCache map[string]cachedFileDigest
func loadFileDigestCache(path string) fileDigestCache {
cache := make(fileDigestCache)
data, err := os.ReadFile(path)
if err == nil && (json.Unmarshal(data, &cache) != nil || cache == nil) {
return make(fileDigestCache)
}
return cache
}
func (cache fileDigestCache) digest(path string) (string, error) {
info, err := os.Stat(path)
if err != nil {
return "", err
}
if info.Size() < 1024*1024 {
return fileDigest(path)
}
stamp, reliable := fileChangeStamp(path, info)
if reliable {
if previous, ok := cache[path]; ok && previous.Stamp == stamp {
return previous.Hash, nil
}
}
sum, err := fileDigest(path)
if err == nil && reliable {
cache[path] = cachedFileDigest{Stamp: stamp, Hash: sum}
}
return sum, err
}
func (cache fileDigestCache) save(path string) error {
data, err := json.Marshal(cache)
if err != nil {
return err
}
if current, err := os.ReadFile(path); err == nil && bytes.Equal(current, data) {
return nil
}
return saveBuildJSON(path, data)
}
func snapshotInputs(root, managed, bep string, cache fileDigestCache) (map[string]string, error) {
files, err := developmentInputs(root, managed, bep)
if err != nil {
return nil, err
}
inputs := make(map[string]string, len(files))
for _, file := range files {
sum, err := cache.digest(file)
if err != nil {
return nil, err
}
inputs[file] = sum
}
return inputs, nil
}
func projectFingerprint(root string, inputs map[string]string, project, versionSource string) (string, error) {
relevant := make(map[string]string)
for file, sum := range inputs {
if strings.HasSuffix(file, ".go") || file == filepath.Join(root, "go", "go.mod") || file == filepath.Join(root, "go", "go.sum") {
continue
}
relative, err := filepath.Rel(filepath.Join(root, "plugins"), file)
folder, _, nested := strings.Cut(filepath.ToSlash(relative), "/")
if err != nil {
nested = false
}
isPlugin := folder == "LocalIdentity" || folder == "LoginUI" || folder == "CashShop" || folder == "FChat"
needsLoginUI := project == "CashShop" || project == "FChat"
isDependency := folder == project || folder == "LoginUI" && needsLoginUI
if nested && isPlugin && !isDependency {
continue
}
if file == filepath.Join(root, "versions.json") {
continue
}
relevant[file] = sum
}
sum, err := fileDigest(versionSource)
if err != nil {
return "", err
}
relevant[versionSource] = sum
return digestInputs(relevant), nil
}
func dependencyFingerprint(root string, inputs map[string]string, project string) string {
relevant := make(map[string]string)
for file, sum := range inputs {
if strings.HasSuffix(file, ".go") || file == filepath.Join(root, "versions.json") || file == filepath.Join(root, "go", "go.mod") || file == filepath.Join(root, "go", "go.sum") {
continue
}
relative, err := filepath.Rel(filepath.Join(root, "plugins"), file)
if err != nil {
continue
}
folder, _, nested := strings.Cut(filepath.ToSlash(relative), "/")
if !nested || folder == ".." || folder == project || project == "GameSdk" && folder == "GameNames" {
relevant[file] = sum
}
}
return digestInputs(relevant)
}
func developmentInputs(root, managed, bep string) ([]string, error) {
var files []string
for _, directory := range []string{filepath.Join(root, "plugins"), filepath.Join(root, "go", "internal", "client", "plugin"), filepath.Join(root, "go", "internal", "buildversion")} {
err := filepath.WalkDir(directory, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
if entry.Name() == "bin" || entry.Name() == "obj" || entry.Name() == ".git" || entry.Name() == "CaptureEnvironment" || entry.Name() == "samples" {
return filepath.SkipDir
}
return nil
}
switch strings.ToLower(filepath.Ext(path)) {
case ".cs", ".go", ".csproj", ".props", ".targets", ".proj", ".json", ".gz", ".xml", ".resx", ".resources", ".editorconfig":
files = append(files, path)
}
return nil
})
if err != nil {
return nil, err
}
}
for _, directory := range []string{managed, filepath.Join(bep, "core")} {
err := filepath.WalkDir(directory, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if !entry.IsDir() && strings.EqualFold(filepath.Ext(path), ".dll") {
files = append(files, path)
}
return nil
})
if err != nil {
return nil, err
}
}
for _, name := range []string{"versions.json", ".editorconfig", "global.json", "NuGet.Config", "Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props", "go/go.mod", "go/go.sum"} {
path := filepath.Join(root, filepath.FromSlash(name))
if _, err := os.Stat(path); err == nil {
files = append(files, path)
} else if !errors.Is(err, os.ErrNotExist) {
return nil, err
}
}
return files, nil
}
func digestInputs(inputs map[string]string) string {
files := make([]string, 0, len(inputs))
for file := range inputs {
files = append(files, file)
}
sort.Strings(files)
hash := sha256.New()
for _, file := range files {
_, _ = fmt.Fprintf(hash, "%s\x00%s\n", file, inputs[file])
}
return hex.EncodeToString(hash.Sum(nil))
}
func writeBuildInput(path, fingerprint string) error {
content := []byte("// Client plugin compilation inputs: " + fingerprint + "\n")
current, err := os.ReadFile(path)
if err == nil && bytes.Equal(current, content) {
return nil
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
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 {
return false
}
var manifest buildManifest
if json.Unmarshal(raw, &manifest) != nil || manifest.Input != fingerprint || len(manifest.Outputs) == 0 {
return false
}
for output, expected := range manifest.Outputs {
sum, err := cache.digest(output)
if err != nil || sum != expected {
return false
}
}
return true
}
func saveBuildManifest(path string, manifest buildManifest) error {
raw, err := json.Marshal(manifest)
if err != nil {
return err
}
return saveBuildJSON(path, raw)
}
func saveBuildJSON(path string, raw []byte) error {
temporary, err := os.CreateTemp(filepath.Dir(path), ".build-*.json")
if err != nil {
return err
}
defer func() { _ = os.Remove(temporary.Name()) }()
if _, err := temporary.Write(raw); err != nil {
_ = temporary.Close()
return err
}
if err := temporary.Close(); err != nil {
return err
}
return replaceFile(temporary.Name(), path)
}
@@ -0,0 +1,18 @@
//go:build !windows
package plugin
import (
"errors"
"os"
"golang.org/x/sys/unix"
)
func tryBuildFileLock(file *os.File) (bool, error) {
err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB)
if errors.Is(err, unix.EWOULDBLOCK) {
return false, nil
}
return err == nil, err
}
@@ -0,0 +1,19 @@
//go:build windows
package plugin
import (
"errors"
"os"
"golang.org/x/sys/windows"
)
func tryBuildFileLock(file *os.File) (bool, error) {
var overlapped windows.Overlapped
err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overlapped)
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) {
return false, nil
}
return err == nil, err
}
@@ -0,0 +1,9 @@
//go:build !windows
package plugin
import "os"
func fileChangeStamp(_ string, _ os.FileInfo) (string, bool) {
return "", false
}
@@ -0,0 +1,28 @@
//go:build windows
package plugin
import (
"encoding/binary"
"fmt"
"os"
"golang.org/x/sys/windows"
)
func fileChangeStamp(path string, info os.FileInfo) (string, bool) {
name, err := windows.UTF16PtrFromString(path)
if err != nil {
return "", false
}
handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, 0, 0)
if err != nil {
return "", false
}
defer func() { _ = windows.CloseHandle(handle) }()
var basic [40]byte
if windows.GetFileInformationByHandleEx(handle, windows.FileBasicInfo, &basic[0], uint32(len(basic))) != nil {
return "", false
}
return fmt.Sprintf("%d:%d:%d:%d", info.Size(), info.ModTime().UnixNano(), binary.LittleEndian.Uint64(basic[:8]), binary.LittleEndian.Uint64(basic[24:32])), true
}
@@ -0,0 +1,122 @@
//go:build integration
package app
import (
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/protocol/wire"
"context"
"encoding/json"
"os"
"testing"
)
func TestUnlimitedInventoryIsAccountScopedAndPreservesPurchases(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
open := func(account string) *puzzleGameplay {
t.Helper()
instance, err := factory.open(account)
if err != nil {
t.Fatal(err)
}
g := &puzzleGameplay{t: t, factory: factory, account: account, owner: instance}
t.Cleanup(func() {
if g.owner != nil {
if err := g.owner.Close(); err != nil {
t.Error(err)
}
}
})
return g
}
a, b := open(accounts[0]), open(accounts[1])
// UserDBInfo capacity fields 5/6/10/15 are defined in the 2.36.7 client;
// limits and prices come from the current repository GameDefaultTable.
login := func(g *puzzleGameplay) assets.InventorySlotCounts {
t.Helper()
user := profileBytes(t, g.call("/LoginUser", nil), 1)
return assets.InventorySlotCounts{
Items: profileVarint(t, user, 5), Storage: profileVarint(t, user, 6),
Equipment: profileVarint(t, user, 10), EquipmentStorage: profileVarint(t, user, 15),
}
}
aBaseline, bBaseline := login(a), login(b)
design := factory.design.slotDesign
if aBaseline.Items+1 >= design.Items.Maximum || aBaseline.Equipment+1 >= design.Equipment.Maximum ||
bBaseline.Items >= design.Items.Maximum || bBaseline.Equipment >= design.Equipment.Maximum {
t.Fatal("test seed must distinguish purchased and advertised maximum capacity")
}
a.call("/InvenAddSlot", wire.AppendVarint(nil, 2, 1))
a.call("/EquipAddSlot", wire.AppendVarint(nil, 2, 1))
purchased := aBaseline
purchased.Items++
purchased.Equipment++
if got := login(a); got != purchased {
t.Fatalf("purchase login = %+v, want %+v", got, purchased)
}
writeSettings := func(unlimited bool) {
t.Helper()
document := map[string]any{"version": 2, "accounts": map[string]any{
a.account: map[string]any{"inventory": map[string]bool{"unlimited": unlimited}},
}}
data, err := json.Marshal(document)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(factory.options.devToolsConfig, data, 0o600); err != nil {
t.Fatal(err)
}
}
writeSettings(true)
maximum := purchased
maximum.Items, maximum.Equipment = design.Items.Maximum, design.Equipment.Maximum
if got := login(a); got != maximum {
t.Fatalf("enabled A login = %+v, want %+v", got, maximum)
}
if got := login(b); got != bBaseline {
t.Fatalf("A override changed B login: %+v, want %+v", got, bBaseline)
}
a.reopen()
b.reopen()
if got := login(a); got != maximum {
t.Fatalf("reloaded A login = %+v, want %+v", got, maximum)
}
if got := login(b); got != bBaseline {
t.Fatalf("reloaded B login = %+v, want %+v", got, bBaseline)
}
assertPurchasedState := func() {
t.Helper()
tx, err := a.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
data, found, err := a.owner.assembly.scope.LoadEntry(tx, "items", "slots", "capacity")
if err != nil || !found {
t.Fatalf("durable purchased capacity missing: %v", err)
}
var saved assets.InventorySlotCounts
if err := json.Unmarshal(data, &saved); err != nil {
t.Fatal(err)
}
if saved != purchased {
t.Fatalf("advertised override changed durable purchases: %+v, want %+v", saved, purchased)
}
if got, err := a.owner.assembly.inventorySlots.InventorySlotCounts(command.Context{Identity: command.Identity{AccountID: a.account}}); err != nil || got != maximum {
t.Fatalf("account context did not select override: %+v %v", got, err)
}
}
assertPurchasedState()
writeSettings(false)
if got := login(a); got != purchased {
t.Fatalf("disabled A login lost purchased capacity: %+v, want %+v", got, purchased)
}
if got := login(b); got != bBaseline {
t.Fatalf("disabled A switch changed B: %+v, want %+v", got, bBaseline)
}
a.reopen()
if got := login(a); got != purchased {
t.Fatalf("reloaded disabled A login = %+v, want %+v", got, purchased)
}
}
@@ -0,0 +1,265 @@
//go:build integration
package app
import (
"context"
"encoding/json"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/protocol/wire"
)
func achievementInfoRow(t *testing.T, body []byte, group, content uint64) (value, claimed uint64) {
t.Helper()
for _, row := range profileRows(t, body, 1) {
if profileVarint(t, row, 1) == group && profileVarint(t, row, 4) == content {
return profileVarint(t, row, 2), profileVarint(t, row, 3)
}
}
return 0, 0
}
func achievementClaimFields(group, id uint64) []byte {
info := wire.AppendVarint(wire.AppendVarint(nil, 1, group), 2, id)
return wire.AppendBytes(wire.AppendVarint(nil, 2, 1), 3, info)
}
func achievementWallet(g *puzzleGameplay) assets.Currency {
g.t.Helper()
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
g.t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
return g.owner.assembly.wallet.Snapshot(command.Context{State: tx})
}
// Current GameData group6004 is Lathel's four-part title, with child
// conditions112–115 for UniqueChar1 and a Type26 reward. The saved fixture
// predates counters; native claims must remain explicit and idempotent.
func TestAchievementReconcileHistoricalCompoundTitleRequiresClaim(t *testing.T) {
g := profileGameplay(t)
p := g.owner.assembly
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
c := command.Context{State: tx}
var costume roster.Costume
for _, owned := range p.collection.Costumes() {
if p.design.costumePotentialDesign.CostumeUnique[owned.ID] == 1 {
costume = owned
break
}
}
if costume.ID == 0 {
if _, err := p.collection.GrantCostumes(c, "historical-title-lathel", []uint64{101}, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
var found bool
costume, found = p.collection.CostumeByID(101)
if !found {
t.Fatal("historical Lathel grant missing")
}
}
var duplicates []uint64
for level := costume.Level; level < p.design.achievementGrades.CostumeMaximum[costume.ID]; level++ {
duplicates = append(duplicates, costume.ID)
}
if _, err := p.collection.GrantCostumes(c, "historical-title-costume", duplicates, p.design.rewardCostumes); err != nil {
t.Fatal(err)
}
var nodes []uint64
for id := range p.design.costumePotentialDesign.Nodes[costume.ID] {
nodes = append(nodes, id)
}
if err := p.collection.ActivateCostumePotential(c, costume.InvenIndex, nodes); err != nil {
t.Fatal(err)
}
awake := roster.CharAwakeProgress{IsAwake: true}
for slot, growth := range p.design.charAwakeDesign.Characters[1].ImprintGrowth {
awake.ImprintLevels[slot] = uint64(len(growth))
}
if err := p.collection.UpdateCharAwake(c, 1, roster.CharAwakeProgress{}, awake); err != nil {
t.Fatal(err)
}
var equipmentID uint64
for id, unique := range p.design.achievementGrades.EquipmentPrivate {
if unique == 1 && p.design.achievementGrades.Equipment[id] == 4 && (equipmentID == 0 || id < equipmentID) {
equipmentID = id
}
}
if equipmentID == 0 {
t.Fatal("GameData has no Lathel UR private weapon")
}
if _, err := p.ownedEquipment.GrantOnce(c, "historical-title-weapon", equipmentID); err != nil {
t.Fatal(err)
}
if _, err := tx.DeleteEntry("missions", "achievement_counts", "6004"); err != nil {
t.Fatal(err)
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
key := gamedata.AchievementKey{ContentsGroup: 1, GroupID: 6004, ID: 1001}
reward := p.design.missionDesign.Achievements[key].Rewards
var titleID uint64
for _, item := range reward {
if item.Type == 26 {
titleID = item.ID
}
}
if titleID == 0 {
t.Fatal("versioned compound achievement has no title reward")
}
beforeWallet := achievementWallet(g)
g.reopen()
info := g.call("/AchievementInfo", nil)
if value, claimed := achievementInfoRow(t, info, 6004, 1); value != 4 || claimed != 1000 {
t.Fatalf("historical title eligibility=%d claimed=%d", value, claimed)
}
if g.itemCount(26, titleID) != 0 || achievementWallet(g) != beforeWallet {
t.Fatal("reconciliation granted an unclaimed reward")
}
if value, _ := achievementInfoRow(t, info, 6009, 1); value >= 4 {
t.Fatal("Lathel's saved conditions completed another character's title")
}
g.call("/AchievementClear", achievementClaimFields(6004, 1001))
if got := g.itemCount(26, titleID); got != 1 {
t.Fatalf("native claim granted %d titles", got)
}
g.call("/AchievementClear", achievementClaimFields(6004, 1001))
g.reopen()
if got := g.itemCount(26, titleID); got != 1 {
t.Fatalf("claim retry/startup granted %d titles", got)
}
if value, claimed := achievementInfoRow(t, g.call("/AchievementInfo", nil), 6004, 1); value != 4 || claimed != 1001 {
t.Fatalf("claimed historical title lost progress/claim=%d/%d", value, claimed)
}
}
func TestAchievementReconcilePreservesLargerHistoryAndCountsNewGrantOnce(t *testing.T) {
g := profileGameplay(t)
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
if err := tx.PutEntry("missions", "achievement_counts", "100", json.RawMessage("50")); err != nil {
t.Fatal(err)
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
g.reopen()
if value, _ := achievementInfoRow(t, g.call("/AchievementInfo", nil), 100, 0); value != 50 {
t.Fatalf("remaining costumes replaced larger history: %d", value)
}
var costumeID uint64
owned := map[uint64]bool{}
for _, c := range g.owner.assembly.collection.Costumes() {
owned[c.ID] = true
}
for id, grade := range g.factory.design.achievementGrades.Costumes {
if grade == 5 && !owned[id] && (costumeID == 0 || id < costumeID) {
costumeID = id
}
}
if costumeID == 0 {
t.Fatal("GameData has no additional costume fixture")
}
apply := func(commit bool) {
t.Helper()
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
defer func() { _ = tx.Rollback() }()
c := command.Context{Identity: command.Identity{AccountID: g.account, SessionID: "history-grant"}, State: tx}
request := wire.AppendVarint(nil, 1, 77)
observer := g.owner.assembly.achievementObserver
if err := observer.BeforeDispatch(c, "/GachaBuy", request); err != nil {
t.Fatal(err)
}
if _, err := g.owner.assembly.collection.GrantCostumes(c, "new-real-costume", []uint64{costumeID}, g.factory.design.rewardCostumes); err != nil {
t.Fatal(err)
}
if _, err := observer.AfterDispatch(c, "/GachaBuy", request, nil); err != nil {
t.Fatal(err)
}
if commit {
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
}
}
apply(false)
g.reopen()
if value, _ := achievementInfoRow(t, g.call("/AchievementInfo", nil), 100, 0); value != 50 {
t.Fatalf("rolled-back grant increased history: %d", value)
}
apply(true)
g.reopen()
if value, _ := achievementInfoRow(t, g.call("/AchievementInfo", nil), 100, 0); value != 51 {
t.Fatalf("new grant/floor increased history incorrectly: %d", value)
}
apply(true)
g.reopen()
if value, _ := achievementInfoRow(t, g.call("/AchievementInfo", nil), 100, 0); value != 51 {
t.Fatalf("replayed grant increased history: %d", value)
}
}
// LocalText81081000 says "Used Slimes to grow Characters: {0} times".
// CommonPacket sends one CharGrowthRequest containing all selected slimes.
func TestAchievementSlimeGrowthCountsNativeActionInsteadOfGainedLevels(t *testing.T) {
g := profileGameplay(t)
var character roster.Character
for _, owned := range g.owner.assembly.worldService.CharacterService().RawAll() {
if !roster.IsStoryCharacter(owned) && !roster.IsCharmCharacter(owned) && owned.Level == 1 {
character = owned
break
}
}
if character.InvenIndex == 0 {
t.Fatal("fixture has no level-one permanent character")
}
profileGrant(g, gamedata.Reward{Type: 8, ID: 9, Count: 10})
before, _ := achievementInfoRow(t, g.call("/AchievementInfo", nil), 81, 0)
tx, err := g.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
var material assets.Item
for _, item := range g.owner.assembly.ownedItems.All(command.Context{State: tx}) {
if item.Type == 8 && item.ID == 9 {
material = item
break
}
}
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
material.Count = 5
fields := wire.AppendBytes(wire.AppendVarint(nil, 2, character.InvenIndex), 3, assets.ItemWire(material))
response := g.call("/CharGrowth", fields)
grown := profileBytes(t, response, 1)
if level := profileVarint(t, grown, 4); level <= character.Level+1 {
t.Fatalf("real GameData fixture gained too few levels to distinguish contract: %d", level)
}
if count, _ := achievementInfoRow(t, g.call("/AchievementInfo", nil), 81, 0); count != before+1 {
t.Fatalf("one native slime-growth action counted %d instead of1", count-before)
}
material.Count = g.itemCount(8, 9) + 1
bad := wire.AppendBytes(wire.AppendVarint(nil, 2, character.InvenIndex), 3, assets.ItemWire(material))
g.execute(g.request("/CharGrowth", bad), true)
g.reopen()
if count, _ := achievementInfoRow(t, g.call("/AchievementInfo", nil), 81, 0); count != before+1 {
t.Fatalf("failed growth/startup fabricated historical actions: %d", count-before)
}
}
+2
View File
@@ -14,6 +14,8 @@ import (
type designCatalog struct {
friends gamedata.FriendRules
rooms *gamedata.RoomDesign
roomCommerce *gamedata.RoomCommerceDesign
chat *gamedata.ChatDesign
pvp *pvp.Rules
guild *gamedata.GuildDesign
+8
View File
@@ -14,6 +14,14 @@ func (d *designCatalog) loadSharedDesign(c *configuration) error {
return fmt.Errorf("load friend design: %w", err)
}
d.friends = friendRules
d.rooms, err = gamedata.LoadRoomDesign(c.gameData, c.gameDataVersion)
if err != nil {
return fmt.Errorf("load room social design: %w", err)
}
d.roomCommerce, err = gamedata.LoadRoomCommerceDesign(c.gameData, c.gameDataVersion)
if err != nil {
return fmt.Errorf("load room commerce design: %w", err)
}
d.chat, err = gamedata.LoadChatDesign(c.gameData, c.gameDataVersion)
if err != nil {
return fmt.Errorf("load chat design: %w", err)
@@ -281,25 +281,126 @@ func TestNativeFriendRequestsAreBilateralDurableAndRetrySafe(t *testing.T) {
// actual SQLite store before retrying the identical operation identity.
durableSend := command.Identity{AccountID: accounts[0], SessionID: "durable-friend", RequestID: "send"}
durableAccept := command.Identity{AccountID: accounts[1], SessionID: "durable-friend", RequestID: "accept"}
if _, _, err := shared.friends.Execute(context.Background(), durableSend, a.owner, "/FriendSend", append(appScalar(1, 1), appScalar(2, b.owner)...)); err != nil {
if _, _, err := shared.friends.Execute(context.Background(), durableSend, a.owner, "/FriendSend", append(appScalar(1, 1), appScalar(2, b.owner)...), 0); err != nil {
t.Fatal(err)
}
acceptWire := append(appScalar(1, 1), appScalar(2, a.owner)...)
_, acceptedBeforeRestart, err := shared.friends.Execute(context.Background(), durableAccept, b.owner, "/FriendAccept", acceptWire)
_, acceptedBeforeRestart, err := shared.friends.Execute(context.Background(), durableAccept, b.owner, "/FriendAccept", acceptWire, 0)
if err != nil {
t.Fatal(err)
}
// UserInfoUI allows one global Like per reset, and BattlePacket consumes
// one lender's daily quota across their registered supporter slots.
a.send("/LikeUser", appScalar(2, a.owner), 203, 9003)
a.send("/LikeUser", appScalar(2, 9223372036854775807), 203, 9003)
durableLike := command.Identity{AccountID: accounts[0], SessionID: "durable-social", RequestID: "like"}
likeWire := append(appScalar(1, 1), appScalar(2, b.owner)...)
if _, _, err := shared.friends.Execute(context.Background(), durableLike, a.owner, "/LikeUser", likeWire, 0); err != nil {
t.Fatal(err)
}
a.send("/LikeUser", appScalar(2, b.owner), 203, 9003)
if got := appValue(a.send("/MyLikeInfo", nil, 218, 0), 1); got != b.owner {
t.Fatalf("daily like target=%d want%d", got, b.owner)
}
profile = a.send("/UserContentsInfo", appScalar(2, b.owner), 215, 0)
if appValue(profile, 10) != 1 || appValue(profile, 13) != 1 {
t.Fatal("liked friend profile omitted received total or relation")
}
picker := command.Identity{AccountID: accounts[0], SessionID: "durable-social", RequestID: "picker"}
if _, _, err := shared.friends.Execute(context.Background(), picker, a.owner, "/SupporterBattleInfo", append(appScalar(1, 1), appScalar(2, 1)...), 1000); err != nil {
t.Fatal(err)
}
durableBorrow := command.Identity{AccountID: accounts[0], SessionID: "durable-social", RequestID: "borrow"}
borrowWire := append(append(appScalar(1, 1), appScalar(2, b.owner)...), appScalar(3, 1)...)
_, borrowBeforeRestart, err := shared.friends.Execute(context.Background(), durableBorrow, a.owner, "/SupporterBorrow", borrowWire, 1000)
if err != nil {
t.Fatal(err)
}
borrowedCharacters := appRows(appRows(borrowBeforeRestart, 3)[0], 1)
if len(borrowedCharacters) != 1 || appValue(borrowedCharacters[0], 1) != supporters[1].character {
t.Fatal("borrow returned another account's supporter bundle")
}
close()
open()
code, acceptedAfterRestart, err := shared.friends.Execute(context.Background(), durableAccept, b.owner, "/FriendAccept", acceptWire)
code, acceptedAfterRestart, err := shared.friends.Execute(context.Background(), durableAccept, b.owner, "/FriendAccept", acceptWire, 0)
if err != nil || code != 206 || !slices.Equal(acceptedBeforeRestart, acceptedAfterRestart) {
t.Fatalf("durable accept retry code=%d error=%v changed=%v", code, err, !slices.Equal(acceptedBeforeRestart, acceptedAfterRestart))
}
_, borrowAfterRestart, err := shared.friends.Execute(context.Background(), durableBorrow, a.owner, "/SupporterBorrow", borrowWire, 1000)
if err != nil || !slices.Equal(borrowBeforeRestart, borrowAfterRestart) {
t.Fatalf("durable borrow retry changed result: %v", err)
}
if _, _, err := shared.friends.Execute(context.Background(), durableLike, a.owner, "/LikeUser", likeWire, 0); err != nil {
t.Fatal(err)
}
a, b = friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
drainFriendPublications(t, registry, shared, accounts[0])
drainFriendPublications(t, registry, shared, accounts[1])
assertRows(a, "/FriendInfoList", 204, 1, b.owner)
assertRows(b, "/FriendInfoList", 204, 1, a.owner)
if appValue(b.loginBody, 8) != 1 {
t.Fatal("relogin omitted outstanding supporter reward badge")
}
if appValue(a.send("/MyLikeInfo", nil, 218, 0), 1) != b.owner {
t.Fatal("daily like quota was lost across database reopen")
}
if appValue(a.send("/UserContentsInfo", appScalar(2, b.owner), 215, 0), 10) != 1 {
t.Fatal("durable like retry incremented received count")
}
battleRows := appRows(a.send("/SupporterBattleInfo", appScalar(2, 1), 439, 0), 1)
if len(battleRows) != 1 || appValue(battleRows[0], 1) != b.owner || appValue(battleRows[0], 10) != 1 || len(appRows(battleRows[0], 9)) != 1 {
t.Fatal("battle supporter picker omitted lender, slot or durable usage count")
}
status := b.send("/SupporterStatus", appScalar(2, 50), 438, 0)
history := appRows(status, 1)
if len(history) != 1 || appValue(history[0], 2) != a.owner || appValue(history[0], 7) != b.owner || appValue(history[0], 8) != 1 || appValue(history[0], 11) != 1 || appValue(history[0], 12) != 0 {
t.Fatal("rental history did not preserve borrower/lender, slot, friend type and claim status")
}
historyID := appValue(history[0], 1)
a.send("/SupporterReward", appScalar(2, historyID), 442, 9003)
b.send("/SupporterReward", append(appScalar(2, historyID), appScalar(2, historyID)...), 442, 9003)
claim := b.send("/SupporterReward", appScalar(2, historyID), 442, 0)
b.seq--
if replay := b.send("/SupporterReward", appScalar(2, historyID), 442, 0); !slices.Equal(claim, replay) {
t.Fatal("same claim identity changed its reward result")
}
b.send("/SupporterReward", appScalar(2, historyID), 442, 9003)
if appValue(claim, 1) != historyID || len(appRows(claim, 2)) != 1 {
t.Fatal("claim omitted rental ID or reward bundle")
}
status = b.send("/SupporterStatus", appScalar(2, 50), 438, 0)
if appValue(status, 4) != 1 || appValue(appRows(status, 1)[0], 12) != 1 {
t.Fatal("committed claim did not update daily claim count and history")
}
// Read-only GameData query: SupportCharacterDefaultTable 0 fields3/2/1/7/8
// =3 friend uses,3 recommended uses,10 claims,type44,count2 (version20261008155037).
for range 2 {
a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 0)
}
a.send("/SupporterBorrow", append(appScalar(2, b.owner), appScalar(3, 1)...), 437, 9003)
status = b.send("/SupporterStatus", appScalar(2, 50), 438, 0)
history = appRows(status, 1)
if len(history) != 3 {
t.Fatalf("friend rental quota produced%d histories want3", len(history))
}
nextPage := b.send("/SupporterStatus", append(appScalar(2, 1), appScalar(3, appValue(history[0], 1))...), 438, 0)
nextRows := appRows(nextPage, 1)
if len(nextRows) != 1 || appValue(nextRows[0], 1) != appValue(history[1], 1) {
t.Fatal("rental history cursor skipped or repeated a row")
}
baselineCurrency := appValue(appRows(b.loginBody, 1)[0], 54)
close()
open()
a, b = friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
if got := appValue(appRows(b.loginBody, 1)[0], 54); got != baselineCurrency+2 {
t.Fatalf("durable supporter reward currency=%d want%d", got, baselineCurrency+2)
}
if appValue(b.send("/SupporterStatus", appScalar(2, 50), 438, 0), 4) != 1 {
t.Fatal("daily reward claim count was lost across reopen")
}
b.send("/FriendAccept", appScalar(2, a.owner), 206, 1)
a.send("/FriendRemove", appScalar(2, b.owner), 208, 0)
assertRows(a, "/FriendInfoList", 204, 1)
@@ -82,7 +82,8 @@ func TestNewPlayerGuildBootstrapDoesNotRequireGuildUnlock(t *testing.T) {
}
g.member(0)
_, err = g.execute(registryCommand(g.account, "still-locked-raid-deck", "/GuildRaidDeckSave", appScalar(1, 5)))
if !errors.Is(err, social.ErrIneligible) {
var rejection *command.GameError
if !errors.As(err, &rejection) || rejection.PacketCode != 313 || rejection.ErrorType != 9003 {
t.Fatalf("locked guild mutation accepted after bootstrap: %v", err)
}
g.seq = 5
@@ -0,0 +1,109 @@
//go:build integration
package app
import (
"encoding/binary"
"testing"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/world/progress"
"bd2server/internal/server/protocol/wire"
)
// 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.
func TestExplorationDetailKeepsInteriorResearchAndChestMapsSeparateAfterRejoin(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) {
if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
if _, err := p.ownedItems.GrantOnce(ctx, "map-exploration-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
t.Fatal(err)
}
}
})
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
assertMaps := func(research55, research57, chests52 uint64) {
t.Helper()
detail := s.protocol(t, "/PackDetailInfo", trapRequest(10, 5))
var got55, got57, got52 uint64
checkResearch := func(id uint64) {
switch id {
case 5501, 5502:
got55++
case 5601:
got57++
default:
t.Fatalf("unvisited research point leaked into detail:%d", id)
}
}
if err := wire.Walk(detail, func(f wire.Field) error {
if f.Number != 3 {
return nil
}
for raw := f.Value; len(raw) > 0; {
id, size := binary.Uvarint(raw)
if size <= 0 {
t.Fatal("invalid research ID encoding")
}
checkResearch(id)
raw = raw[size:]
}
return nil
}); err != nil {
t.Fatal(err)
}
for _, row := range appRows(detail, 2) {
if id := appValue(row, 1); id == 5240 {
got52++
} else {
t.Fatalf("unopened chest leaked into detail:%d", id)
}
}
if got55 != research55 || got57 != research57 || got52 != chests52 {
t.Fatalf("map completion55=%d/7 57=%d/8 chest52=%d/6; want%d %d %d", got55, got57, got52, research55, research57, chests52)
}
summary := s.protocol(t, "/PackSummaryInfoList", wire.AppendVarint(nil, 1, 11))
found := false
for _, row := range appRows(summary, 1) {
if appValue(row, 1) == 5 {
found = true
if appValue(row, 2) != chests52 || appValue(row, 5) != research55+research57 {
t.Fatalf("pack summary disagrees with separate map progress:%x", row)
}
}
}
if !found {
t.Fatal("chapter missing from exploration summary")
}
}
assertMaps(0, 0, 0)
s.position(t, 5, 55)
s.protocol(t, "/FieldObjectResearch", wire.AppendVarint(trapRequest(2, 5), 3, 5501))
assertMaps(1, 0, 0)
s.protocol(t, "/FieldObjectResearch", wire.AppendVarint(trapRequest(3, 5), 3, 5502))
s.position(t, 5, 57)
s.protocol(t, "/FieldObjectResearch", wire.AppendVarint(trapRequest(4, 5), 3, 5601))
s.position(t, 5, 52)
s.protocol(t, "/FieldObjectReward", wire.AppendVarint(wire.AppendVarint(trapRequest(5, 5), 3, 23), 4, 5240))
assertMaps(2, 1, 1)
closeNicknamePlayer(t, s.owner)
s.owner = openNicknamePlayer(t, factory, s.account)
s.protocol(t, "/PackInGameInfo", trapRequest(6, 5))
field := s.protocol(t, "/FieldObjectInfo", trapRequest(7, 5))
if rows := appRows(field, 1); len(rows) != 1 || appValue(rows[0], 1) != 5240 {
t.Fatal("native field entry did not restore the opened chest")
}
assertMaps(2, 1, 1)
s.run(t, true, func(ctx command.Context, p *playerAssembly) {
if err := p.progressState.SelectQuest(ctx, 5, progress.QuestSelection{Difficulty: 2}); err != nil {
t.Fatal(err)
}
})
assertMaps(2, 1, 1)
}
@@ -0,0 +1,96 @@
package app
import (
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/progression/achievements"
"context"
)
func (p *playerAssembly) attachAchievementProjection(provider *achievements.OwnedGameplayAchievementProvider) {
world := provider.Project
provider.Project = func(ctx command.Context, snapshot *achievements.GameplayAchievementSnapshot) error {
if err := world(ctx, snapshot); err != nil {
return err
}
add := func(kind, sub, value uint64) {
snapshot.Conditions = append(snapshot.Conditions, achievements.GameplayAchievementCondition{Type: kind, SubType: sub, Value: value, LowerBound: true})
}
recipes := map[uint64]bool{}
for _, id := range p.starter.CookingRecipes {
recipes[id] = true
}
for key, count := range snapshot.Items {
if count == 0 {
continue
}
switch key[0] {
case 7:
if p.design.recipeDesign.IDs[key[1]] {
recipes[key[1]] = true
}
case 45:
add(137, key[1], 1)
case 61:
add(147, key[1], 1)
}
}
add(6, 0, uint64(len(recipes)))
currency := p.wallet.Snapshot(ctx)
add(1, 4, currency.Gold)
add(1, 22, currency.HopePowder)
add(79, 0, currency.FreeJewelry+currency.Jewelry)
add(53, 0, p.missionService.ClaimedMissionCount())
exp, err := p.missionService.AchievementExperience()
if err != nil {
return err
}
add(70, 0, p.design.levelDesign.Level(exp))
var friendship uint64
for _, entry := range p.collection.FriendshipEntries() {
if entry.State != nil && entry.State.Level >= p.design.friendshipDesign.Default.MaxLevels[0] {
friendship++
}
}
add(105, 0, friendship)
if p.huntingService != nil {
clears, err := p.huntingService.RecordedClearCounts(ctx)
if err != nil {
return err
}
for difficulty, count := range clears {
add(47+difficulty, 0, count)
}
}
if p.fishingService != nil {
values, err := p.fishingService.AchievementProgress()
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)
}
}
if p.monsterHuntService != nil {
add(84, 0, p.monsterHuntService.RecordedBattleCount())
}
if p.shared != nil && p.shared.friends != nil {
owner, err := p.ProfileOwner(ctx)
if err != nil {
return err
}
counts, err := p.shared.friends.GameplayCounts(context.Background(), ctx.AccountID, owner)
if err != nil {
return err
}
add(101, 0, counts.RentalClaims)
add(109, 0, counts.BorrowCount)
add(119, 0, counts.RoomLikes)
}
return nil
}
}
+13
View File
@@ -33,6 +33,19 @@ func (p *playerAssembly) chat() error {
out = wire.AppendBytes(out, 7, base)
}
}
if p.shared != nil && p.shared.friends != nil {
owner, err := p.ProfileOwner(ctx)
if err != nil {
return nil, err
}
available, err := p.shared.friends.SupporterRewardAvailable(context.Background(), owner)
if err != nil {
return nil, err
}
if available {
out = wire.AppendVarint(out, 8, 1)
}
}
return out, nil
})
}
+2 -3
View File
@@ -201,14 +201,13 @@ func (p *playerAssembly) events(ctx command.Context) error {
return fmt.Errorf("attach persisted achievement experience: %w", err)
}
achievementProvider := p.worldService.GameplayAchievementProvider(ctx, p.design.achievementCounterDesign, p.design.achievementGrades)
achievementProvider.Potential = p.design.costumePotentialDesign
p.attachAchievementProjection(achievementProvider)
achievementProvider.StateVersion = p.stateRepository.ObservationVersion
p.achievementObserver, err = achievements.NewGameplayAchievementObserver(p.achievementCounters, achievementProvider)
if err != nil {
return fmt.Errorf("initialize achievement gameplay observer: %w", err)
}
if err := p.achievementObserver.SyncRecordedHistory(ctx); err != nil {
return fmt.Errorf("restore recorded achievement history: %w", err)
}
p.eventTasksService.AttachInventoryProvider(&eventtasks.InventoryProjection{Items: p.ownedItems, Equipment: p.ownedEquipment, Costumes: p.collection, StateVersion: p.stateRepository.ObservationVersion})
p.worldService.AttachSkyWayProgress(p.eventTasksService.RecordSkyWayClear, func(ctx command.Context, group uint64) error {
return p.missionService.RecordEvent(ctx, 227, group, 1, p.worldService.MissionsUnlocked)
+19 -1
View File
@@ -2,6 +2,7 @@ package app
import (
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/runtime/player"
accountstate "bd2server/internal/server/storage/account"
"bd2server/internal/server/storage/outbox"
@@ -33,7 +34,8 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
if err != nil {
return reply, err
}
if len(request.Requests) == 1 && len(friendResponses) == 1 {
friendProgress := len(request.Requests) == 1 && len(friendResponses) == 1 && social.FriendMutates(request.Requests[0].Path)
if len(request.Requests) == 1 && len(friendResponses) == 1 && !friendProgress {
reply.Responses = []player.Response{friendResponses[0]}
return reply, nil
}
@@ -153,6 +155,9 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
}
}
assembly := p.assembly
if friendProgress {
assembly.achievementObserver.BeginLogin(identity)
}
transientBefore := assembly.transientVersion()
failCommand := func(cause error) error {
changed := tx.Dirty() || assembly.transientVersion() != transientBefore
@@ -192,6 +197,9 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
reply.Timing.Execute += time.Since(started)
} else {
started := time.Now()
if item.Path == "/AchievementInfo" || item.Path == "/AchievementClear" {
assembly.achievementObserver.BeginLogin(identity)
}
for _, observer := range assembly.observers {
if err = observer.BeforeDispatch(identity, item.Path, item.Body); err != nil {
break
@@ -204,6 +212,11 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
response = friendResponse
} else if plan := socialPlans[index]; plan != nil {
response.PacketCode, response.Body, err = socialService.Apply(identity, plan)
if err == nil && plan.Reservation != nil && plan.Reservation.Kind == social.SupporterClaim {
_, err = assembly.achievementCounters.RecordEvent(identity, "supporter-claim:"+plan.ID, 101, 0, uint64(len(plan.Reservation.UsageIDs)))
}
} else if item.Path == "/TotalRanking" {
response.PacketCode, response.Body, err = p.totalRanking(identity, item.Body)
} else {
response.PacketCode, response.Body, err = assembly.dispatch(identity, item.Path, item.Body)
}
@@ -230,6 +243,11 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
reply.Responses = append(reply.Responses, response)
}
if !isSystem && (tx.Dirty() || isLogin) {
if isLogin || huntRankingChanged(request.Requests) {
if err := assembly.publishHuntRanking(identity); err != nil {
return reply, failCommand(err)
}
}
if isLogin || friendProfileChanged(request.Requests) {
if err := assembly.publishFriendProfile(identity, isLogin); err != nil {
return reply, failCommand(err)
+48 -1
View File
@@ -29,6 +29,16 @@ func (p *playerAssembly) publicFriendProfile(ctx command.Context) (social.Friend
return profile, err
}
}
for _, item := range p.ownedItems.All(ctx) {
if item.Type == 27 || item.Type == 28 {
profile.RoomItems = append(profile.RoomItems, item)
}
}
profile.RoomCostumes = p.collection.Costumes()
profile.RoomIDs, err = (social.RoomCommerce{}).OwnedRooms(ctx)
if err != nil {
return profile, err
}
profile.SupporterDetails, err = p.profileService.PublicSupporterDetails(ctx)
if err != nil {
return profile, err
@@ -94,7 +104,42 @@ func (p *playerInstance) prepareFriends(ctx context.Context, request player.Comm
return nil, err
}
}
code, body, err := p.factory.shared.friends.Execute(ctx, request.Identity, own.OwnerIndex, item.Path, item.Body)
if strings.HasPrefix(item.Path, "/MyRoom") {
var current social.FriendProfile
if err := p.readLocal(ctx, request.Identity, func(c command.Context) error {
var err error
current, err = p.assembly.publicFriendProfile(c)
return err
}); err != nil {
return nil, err
}
if err := p.factory.shared.friends.Publish(ctx, current); err != nil {
return nil, err
}
}
if err := p.factory.shared.friends.PrepareRoomText(ctx, request.Identity, item.Path, item.Body, func(text string) error {
return p.assembly.checkText(ctx, request.Identity.AccountID, "room_name", text, map[string]int{"/MyRoomNameChange": 234, "/MyRoomSave": 229, "/MyRoomPresetSave": 642, "/MyRoomPresetNameChange": 643}[item.Path])
}); err != nil {
return nil, err
}
var contentType uint64
if item.Path == "/SupporterBattleInfo" || item.Path == "/SupporterBorrow" {
if err := p.readLocal(ctx, request.Identity, func(c command.Context) error {
pack, err := p.assembly.worldService.CurrentPackID(c)
if err != nil {
return err
}
typ, found := p.assembly.design.recovery.Types[pack]
if !found {
return social.ErrInvalid
}
contentType = typ
return nil
}); err != nil {
return nil, err
}
}
code, body, err := p.factory.shared.friends.Execute(ctx, request.Identity, own.OwnerIndex, item.Path, item.Body, contentType)
if errors.Is(err, social.ErrConflict) {
return nil, player.ErrIdentityConflict
}
@@ -117,6 +162,8 @@ func friendProfileChanged(requests []player.Request) bool {
}
}
switch r.Path {
case "/MyRoomExpand", "/MyRoomShopBuy", "/MyRoomShopMultiBuy":
return true
case "/UserPortraitChange", "/UserTitleChange", "/UserNicknameChange", "/SupporterRegister", "/SupporterRemove", "/UpdateUserContentsInfoOption", "/UserGreetingChange", "/IdCardSave", "/IdCardRecovery", "/AvatarUse", "/AvatarSave", "/GuildCreate", "/GuildJoin", "/GuildLeave", "/GuildMemberBan", "/GuildInfoEdit", "/GuildNameChange", "/CharLevelUp", "/CostumeLevelUp", "/CharAwake", "/EquipUse", "/EquipUpgrade", "/CostumePotentialUpgrade", "/PrestigeSkinUse":
return true
}
+103 -4
View File
@@ -2,6 +2,7 @@ package app
import (
"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/profile"
@@ -12,6 +13,7 @@ import (
"errors"
"fmt"
"slices"
"time"
)
func (p *playerAssembly) profile(ctx command.Context) error {
@@ -35,7 +37,15 @@ func (p *playerAssembly) PublicProfile(ctx command.Context, target uint64) (prof
if p.shared != nil && p.shared.friends != nil {
published, err := p.shared.friends.Profile(context.Background(), target)
if err == nil {
return published.Snapshot, nil
published.Snapshot.IsFriend, err = p.shared.friends.IsFriend(context.Background(), owner, target)
if err != nil {
return profile.Snapshot{}, err
}
published.Snapshot.RoomInfo, published.Snapshot.RoomLikeCount, err = p.shared.friends.RoomProfile(context.Background(), owner, target)
if err == nil {
err = p.profileRankings(target, &published.Snapshot)
}
return published.Snapshot, err
}
if !errors.Is(err, social.ErrNotFound) {
return profile.Snapshot{}, err
@@ -68,13 +78,102 @@ func (p *playerAssembly) PublicProfile(ctx command.Context, target uint64) (prof
if err != nil {
return profile.Snapshot{}, err
}
return profile.Snapshot{
OwnerIndex: owner, UserID: p.nicknameService.CurrentNickname(), TitleID: settings.TitleID,
var guildBase []byte
if p.shared != nil && p.shared.guild != nil {
_, guildBase, err = p.shared.guild.LoginInfo(context.Background(), ctx.AccountID)
if err != nil {
return profile.Snapshot{}, err
}
}
var roomInfo []byte
var roomLikes uint64
var likes uint64
if p.shared != nil && p.shared.friends != nil {
roomInfo, roomLikes, err = p.shared.friends.RoomProfile(context.Background(), owner, owner)
if err != nil {
return profile.Snapshot{}, err
}
likes, err = p.shared.friends.LikeCount(context.Background(), owner)
if err != nil {
return profile.Snapshot{}, err
}
}
snapshot := profile.Snapshot{
RoomInfo: roomInfo, RoomLikeCount: roomLikes, GuildBase: guildBase, LikeCount: likes, OwnerIndex: owner, UserID: p.nicknameService.CurrentNickname(), TitleID: settings.TitleID,
PortraitCostumeID: portrait, PortraitDesignID: portraitDesign,
AchievementLevel: p.design.levelDesign.Level(exp), TotalBattlePower: p.deckStateStore.HighestTotalBattlePower(),
MonsterHuntRank: rank, MonsterHuntTopPercent: percent, Card: settings.Card,
Greeting: settings.Greeting, IsAllPrivate: settings.IsAllPrivate, Options: settings.Options, SortIDs: settings.SortIDs, Supporters: supporters, AvatarUse: &avatar,
}, nil
}
if err := p.profileRankings(owner, &snapshot); err != nil {
return profile.Snapshot{}, err
}
return snapshot, nil
}
func (p *playerAssembly) profileRankings(owner uint64, snapshot *profile.Snapshot) error {
if p.shared == nil {
return nil
}
for _, mode := range []pvp.Mode{pvp.Mirror, pvp.Colosseum} {
var current pvp.Season
now := uint64(time.Now().UnixMilli())
for _, season := range p.design.pvp.Seasons {
if season.Mode == mode && season.Start <= now && (current.ID == 0 || season.Start > current.Start) {
current = season
}
}
if current.ID == 0 {
continue
}
rows, err := p.shared.pvp.Ranking(pvp.RankQuery{Mode: mode, Season: current.ID, OwnerIndex: owner, Limit: 1})
if err != nil {
return err
}
if mode == pvp.Mirror {
snapshot.PvpSeason = current.ID
} else {
snapshot.ColosseumSeason = current.ID
}
if len(rows) == 0 {
continue
}
row := rows[0]
if mode == pvp.Mirror {
snapshot.PvpVP, snapshot.PvpRank = row.VP, row.Rank
} else {
snapshot.ColosseumVP, snapshot.ColosseumRank, snapshot.ColosseumTopPercent = row.VP, row.Rank, row.TopPercent
}
}
for _, schedule := range p.options.calendars.RegularService.Contents {
if schedule.ID != 6 {
continue
}
guild, _, err := wire.Varint(snapshot.GuildBase, 1)
if err != nil {
return err
}
if guild == 0 {
break
}
rows, err := p.shared.guild.Standings(context.Background(), schedule.Current.ID)
if err != nil {
return err
}
for _, row := range rows {
if row.Guild.ID == guild {
snapshot.GuildRaidRank, snapshot.GuildRaidScore = row.Rank, row.Score
break
}
}
}
if owner != 0 && p.shared.huntRanks != nil {
season := p.monsterHuntService.CurrentSeason()
if entry, found := p.shared.huntRanks.OwnerRank(season, owner); found {
snapshot.MonsterHuntRank, snapshot.MonsterHuntTopPercent = entry.Rank, entry.TopPercent
}
}
return nil
}
func (p *playerAssembly) OwnedItems(ctx command.Context) []assets.Item { return p.ownedItems.All(ctx) }
+147
View File
@@ -0,0 +1,147 @@
package app
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"bd2server/internal/server/domain/battle/monsterhunt"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/runtime/player"
"bd2server/internal/server/storage/outbox"
)
func huntRankingChanged(requests []player.Request) bool {
for _, request := range requests {
switch request.Path {
case "/BattleEnd", "/MonsterHuntQuickBattle", "/UserNicknameChange", "/UserTitleChange", "/UserPortraitChange", "/AchievementClear":
return true
}
}
return false
}
func (p *playerAssembly) publishHuntRanking(ctx command.Context) error {
if p.shared == nil || p.shared.huntRanks == nil {
return nil
}
owner, err := p.ProfileOwner(ctx)
if err != nil {
return err
}
records, err := p.monsterHuntService.RankRecords()
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 := monsterhunt.RankPublication{Account: ctx.AccountID, Records: records, Profile: monsterhunt.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", "hunt_publication", "current")
if err != nil {
return err
}
if found {
var old monsterhunt.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("hunt publication version exhausted")
}
next.Version++
raw, err := json.Marshal(next)
if err != nil {
return err
}
if err := ctx.Publish(command.Event{ID: fmt.Sprintf("hunt-ranking:%d", next.Version), Topic: "monster_hunt.ranking", Payload: raw}); err != nil {
return err
}
return ctx.State.PutEntry("directory", "hunt_publication", "current", raw)
}
func (s *sharedRuntime) consumeHuntRanking(ctx context.Context, event outbox.Pending) error {
var publication monsterhunt.RankPublication
if err := json.Unmarshal(event.Envelope.Event.Payload, &publication); err != nil {
return err
}
if publication.Account != event.Envelope.Source {
return errors.New("hunt ranking source mismatch")
}
return s.huntRanks.Publish(ctx, publication)
}
func (p *playerInstance) totalRanking(ctx command.Context, request []byte) (int, []byte, error) {
const code = 518
if err := wire.Walk(request, func(field wire.Field) error {
if field.Number != 1 || field.Type != 0 {
return errors.New("ranking: invalid request")
}
return nil
}); err != nil {
return code, nil, err
}
var out []byte
appendRows := func(field int, rows [][]byte) {
for _, row := range rows {
out = wire.AppendBytes(out, field, row)
}
}
if service := p.assembly.pvpService; service != nil {
season, rows, err := service.RankingSnapshot(pvp.Mirror, 3)
if err != nil {
return code, nil, err
}
appendRows(1, rows)
out = wire.AppendVarint(out, 6, season)
season, rows, err = service.RankingSnapshot(pvp.Colosseum, 3)
if err != nil {
return code, nil, err
}
appendRows(5, rows)
out = wire.AppendVarint(out, 9, season)
}
season := p.assembly.monsterHuntService.CurrentSeason()
out = wire.AppendVarint(out, 7, season)
if shared := p.factory.shared; shared != nil && shared.huntRanks != nil {
for _, entry := range shared.huntRanks.Top(season, 3) {
out = wire.AppendBytes(out, 2, monsterhunt.RankWire(entry))
}
service, err := p.socialService()
if err != nil {
return code, nil, err
}
cancel := ctx.Cancellation
if cancel == nil {
cancel = context.Background()
}
season, rows, history, err := service.RankingSnapshot(cancel, 3)
if err != nil {
return code, nil, err
}
out = wire.AppendVarint(out, 8, season)
appendRows(3, rows)
appendRows(4, history)
}
return code, out, nil
}
+12
View File
@@ -7,6 +7,7 @@ import (
"bd2server/internal/server/domain/commerce/gacha"
"bd2server/internal/server/domain/events"
"bd2server/internal/server/domain/profile"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/gateway/session"
"bd2server/internal/server/protocol/defaults"
scheduleadapter "bd2server/internal/server/protocol/schedule"
@@ -18,6 +19,13 @@ import (
)
func (p *playerAssembly) session(ctx command.Context) error {
if p.shared != nil && p.shared.huntRanks != nil {
owner, err := p.ProfileOwner(ctx)
if err != nil {
return err
}
p.monsterHuntService.AttachRanking(owner, p.shared.huntRanks)
}
if err := p.nickname(ctx); err != nil {
return err
}
@@ -33,6 +41,9 @@ func (p *playerAssembly) session(ctx command.Context) error {
if err := p.multiplayerPVP(ctx); err != nil {
return err
}
if err := p.achievementObserver.SyncRecordedHistory(ctx); err != nil {
return fmt.Errorf("restore recorded achievement history: %w", err)
}
p.handlers = []session.Handler{
p.chatService,
p.nicknameService,
@@ -45,6 +56,7 @@ func (p *playerAssembly) session(ctx command.Context) error {
return published.SupporterDetails, err
}},
p.profileService,
social.RoomCommerce{Design: p.design.roomCommerce, Rooms: p.design.rooms, Economy: p.eventEconomy},
commerce.PackInfoHandler{World: p.worldService, Claims: p.clearPackages},
p.worldService,
p.progressState,
+1 -1
View File
@@ -102,7 +102,7 @@ func (p *playerInstance) readLocal(ctx context.Context, identity command.Identit
}
func (p *playerInstance) guildQualification(ctx context.Context, identity command.Identity, path string) error {
if !social.Mutates(path) || path == "/GuildInfo" {
if !social.Mutates(path) || path == "/GuildInfo" || path == "/SupporterReward" {
return nil
}
return p.readLocal(ctx, identity, func(c command.Context) error {
@@ -0,0 +1,211 @@
//go:build integration
package app
import (
"context"
"slices"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
// MyRoomPacket consumes the returned inventory bundle and adds the expanded
// room. LocalText140040 says purchases are delivered to My Room inventory.
func TestNativeRoomPurchasesAndExpansionAreAtomicAndDurable(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
actor := openNicknamePlayer(t, factory, accounts[0])
tx, err := actor.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
_, err = actor.assembly.eventEconomy.Apply(command.Context{State: tx}, "room-commerce-fixture", nil, []gamedata.Reward{{Type: 4, Count: 3000000}, {Type: 44, Count: 300}})
if err != nil {
_ = tx.Rollback()
t.Fatal(err)
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
closeNicknamePlayer(t, actor)
var shared *sharedRuntime
var registry *playerRegistry
open := func() {
var err error
shared, err = openSharedRuntime(context.Background(), factory.options, factory.design)
if err != nil {
t.Fatal(err)
}
factory.shared, factory.pvpSource = shared, shared.pvp
registry = newPlayerRegistry(factory, time.Minute)
}
close := func() {
if registry != nil {
if err := registry.Close(context.Background()); err != nil {
t.Fatal(err)
}
registry = nil
}
if shared != nil {
if err := shared.store.Close(); err != nil {
t.Fatal(err)
}
shared = nil
}
}
t.Cleanup(close)
open()
client := friendHTTPLogin(t, registry, accounts[0])
type balances struct{ gold, coins, furniture, secondFurniture uint64 }
read := func() balances {
t.Helper()
client = friendHTTPLogin(t, registry, accounts[0])
user := rankingRows(t, client.loginBody, 1)
if len(user) != 1 {
t.Fatal("missing own balances")
}
gold, _, err := wire.Varint(user[0], 7)
if err != nil {
t.Fatal(err)
}
coins, _, err := wire.Varint(user[0], 54)
if err != nil {
t.Fatal(err)
}
body := client.send("/MyRoomUserInfo", wire.AppendVarint(nil, 2, client.owner), 228, 0)
rooms := rankingRows(t, body, 1)
if len(rooms) != 1 {
t.Fatal("missing owned room inventory")
}
var furniture, secondFurniture uint64
for _, row := range rankingRows(t, rooms[0], 5) {
id, _, err := wire.Varint(row, 2)
if err != nil {
t.Fatal(err)
}
if id == 101 {
n, _, err := wire.Varint(row, 4)
if err != nil {
t.Fatal(err)
}
furniture += n
}
if id == 102 {
n, _, err := wire.Varint(row, 4)
if err != nil {
t.Fatal(err)
}
secondFurniture += n
}
}
return balances{gold: gold, coins: coins, furniture: furniture, secondFurniture: secondFurniture}
}
initial := read()
payment := func(typ, n uint64) []byte { return wire.AppendVarint(wire.AppendVarint(nil, 3, typ), 4, n) }
buy := func(id, n, typ, cost uint64) []byte {
p := wire.AppendVarint(nil, 2, id)
p = wire.AppendVarint(p, 3, n)
return wire.AppendBytes(p, 4, payment(typ, cost))
}
roomIDs := func() []uint64 {
t.Helper()
body := client.send("/MyRoomUserInfo", wire.AppendVarint(nil, 2, client.owner), 228, 0)
users := rankingRows(t, body, 1)
if len(users) != 1 {
t.Fatal("no owned room info")
}
var ids []uint64
for _, row := range rankingRows(t, users[0], 8) {
id, _, err := wire.Varint(row, 1)
if err != nil {
t.Fatal(err)
}
ids = append(ids, id)
}
slices.Sort(ids)
return ids
}
initialRooms := roomIDs()
client.send("/MyRoomExpand", wire.AppendBytes(wire.AppendVarint(nil, 2, 4), 3, payment(44, 200)), 418, 0)
expectedRooms := append(slices.Clone(initialRooms), 4)
slices.Sort(expectedRooms)
if got := roomIDs(); !slices.Equal(got, expectedRooms) {
t.Fatalf("paid room unavailable immediately: %v want%v", got, expectedRooms)
}
client.send("/MyRoomExpand", wire.AppendBytes(wire.AppendVarint(nil, 2, 4), 3, payment(44, 200)), 418, 9003)
client.send("/MyRoomShopBuy", buy(1, 1, 4, 500000), 246, 0)
client.seq--
client.send("/MyRoomShopBuy", buy(1, 1, 4, 500000), 246, 0)
client.send("/MyRoomShopBuy", buy(1, 1, 44, 50), 246, 0)
beforeFailure := read()
if beforeFailure.gold != initial.gold-500000 || beforeFailure.coins != initial.coins-250 || beforeFailure.furniture != initial.furniture+2 {
t.Fatalf("purchases did not exchange exact currency for furniture: before%+v after%+v", initial, beforeFailure)
}
row := func(id, n, typ, cost uint64) []byte {
p := wire.AppendVarint(nil, 1, id)
p = wire.AppendVarint(p, 2, n)
return wire.AppendBytes(p, 3, payment(typ, cost))
}
batch := wire.AppendBytes(nil, 2, row(1, 1, 4, 500000))
batch = wire.AppendBytes(batch, 2, row(2, 2, 44, 100))
client.send("/MyRoomShopMultiBuy", batch, 646, 9003)
if got := read(); got != beforeFailure {
t.Fatalf("insufficient mixed-currency batch changed assets: %+v want%+v", got, beforeFailure)
}
info := client.send("/MyRoomShopInfo", nil, 245, 0)
historyFound := false
for _, row := range rankingRows(t, info, 1) {
id, _, _ := wire.Varint(row, 1)
count, _, _ := wire.Varint(row, 2)
if id == 1 {
historyFound = true
if count != 2 {
t.Fatalf("failed batch changed purchase count%d", count)
}
}
if id == 2 {
t.Fatal("failed batch recorded unbought second furniture")
}
}
if !historyFound {
t.Fatal("failed batch removed previous purchase history")
}
client.send("/MyRoomShopBuy", buy(1, 1, 4, 1), 246, 9003)
if got := read(); got != beforeFailure {
t.Fatalf("tampered price changed assets: %+v", got)
}
bulk := wire.AppendBytes(nil, 2, row(1, 1, 4, 500000))
bulk = wire.AppendBytes(bulk, 2, row(2, 1, 44, 50))
client.send("/MyRoomShopMultiBuy", bulk, 646, 0)
committed := read()
if committed.gold != beforeFailure.gold-500000 || committed.coins != beforeFailure.coins-50 || committed.furniture != beforeFailure.furniture+1 || committed.secondFurniture != beforeFailure.secondFurniture+1 {
t.Fatalf("successful bulk purchase changed wrong assets: %+v", committed)
}
close()
open()
client = friendHTTPLogin(t, registry, accounts[0])
if got := roomIDs(); !slices.Equal(got, expectedRooms) {
t.Fatalf("expanded room lost on restart: %v", got)
}
info = client.send("/MyRoomShopInfo", nil, 245, 0)
found := false
for _, row := range rankingRows(t, info, 1) {
id, _, _ := wire.Varint(row, 1)
count, _, _ := wire.Varint(row, 2)
if id == 1 {
found = true
if count != 3 {
t.Fatalf("purchase count after restart%d", count)
}
}
}
if !found {
t.Fatal("purchase history missing after restart")
}
if got := read(); got != committed {
t.Fatalf("purchase assets changed after restart: %+v want%+v", got, committed)
}
}
@@ -0,0 +1,228 @@
//go:build integration
package app
import (
"context"
"slices"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
func TestNativeRoomVisitPrivacyOwnedLayoutAndPopularityAreDurable(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
actor := openNicknamePlayer(t, factory, accounts[1])
tx, err := actor.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
if _, err := actor.assembly.collection.GrantCostumes(command.Context{State: tx}, "room-costume-fixture", []uint64{101}, factory.design.rewardCostumes); err != nil {
_ = tx.Rollback()
t.Fatal(err)
}
items, err := actor.assembly.ownedItems.GrantOnce(command.Context{State: tx}, "room-decoration-fixture", []gamedata.BattleReward{{Type: 27, ID: 101, Count: 1}})
if err != nil {
_ = tx.Rollback()
t.Fatal(err)
}
if len(items) != 1 {
_ = tx.Rollback()
t.Fatal("fixture decoration not granted")
}
decorationIndex := items[0].InvenIndex
var costumeIndex uint64
for _, costume := range actor.assembly.collection.Costumes() {
if costume.ID == 101 {
costumeIndex = costume.InvenIndex
}
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
closeNicknamePlayer(t, actor)
if costumeIndex == 0 {
t.Fatal("fixture has no owned costume")
}
var shared *sharedRuntime
var registry *playerRegistry
open := func() {
var err error
shared, err = openSharedRuntime(context.Background(), factory.options, factory.design)
if err != nil {
t.Fatal(err)
}
factory.shared, factory.pvpSource = shared, shared.pvp
registry = newPlayerRegistry(factory, time.Minute)
}
close := func() {
if registry != nil {
if err := registry.Close(context.Background()); err != nil {
t.Fatal(err)
}
registry = nil
}
if shared != nil {
if err := shared.store.Close(); err != nil {
t.Fatal(err)
}
shared = nil
}
}
t.Cleanup(close)
open()
a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
drainFriendPublications(t, registry, shared, accounts[0])
drainFriendPublications(t, registry, shared, accounts[1])
self := appRows(b.send("/MyRoomUserInfo", append(appScalar(2, b.owner), appScalar(3, 1)...), 228, 0), 1)
if len(self) != 1 || appValue(self[0], 1) != b.owner {
t.Fatal("own room view omitted actual owner")
}
rooms := appRows(self[0], 8)
// Read-only current MyRoomExpandTable1/2/3 each has field3(defaultRoom)=1.
if len(rooms) != 3 {
t.Fatalf("native default rooms=%d want3", len(rooms))
}
primary := appValue(self[0], 4)
position := wire.AppendVarint(nil, 1, costumeIndex)
position = wire.AppendVarint(position, 2, 1)
position = wire.AppendVarint(position, 3, 1)
room := wire.AppendVarint(nil, 1, primary)
room = wire.AppendString(room, 2, "Quiet Room")
room = wire.AppendBytes(room, 3, position)
decorationPosition := wire.AppendVarint(nil, 1, decorationIndex)
decorationPosition = wire.AppendVarint(decorationPosition, 3, 1)
room = wire.AppendBytes(room, 3, decorationPosition)
b.send("/MyRoomSave", appMessage(2, room), 229, 0)
foreign := wire.AppendVarint(nil, 1, primary)
foreignPosition := wire.AppendVarint(nil, 1, 9223372036854775807)
foreignPosition = wire.AppendVarint(foreignPosition, 2, 1)
foreignPosition = wire.AppendVarint(foreignPosition, 3, 1)
foreign = wire.AppendBytes(foreign, 3, foreignPosition)
b.send("/MyRoomSave", appMessage(2, foreign), 229, 9003)
view := appRows(a.send("/MyRoomUserInfo", appScalar(2, b.owner), 228, 0), 1)[0]
if appValue(view, 1) != b.owner || len(appRows(view, 6)) == 0 || len(appRows(view, 8)) != 3 {
t.Fatal("visitor did not receive target's actual costumes and visible default rooms")
}
var chosen []byte
for _, v := range appRows(view, 8) {
if appValue(v, 1) == primary {
chosen = v
}
}
hasCostumePlacement := false
for _, placement := range appRows(chosen, 3) {
if appValue(placement, 1) == costumeIndex && appValue(placement, 2) == 1 {
hasCostumePlacement = true
}
}
if nicknameField(t, chosen, 2) != "Quiet Room" || !hasCostumePlacement {
t.Fatal("visitor layout did not match owner's persisted save")
}
profile := a.send("/UserContentsInfo", appScalar(2, b.owner), 215, 0)
if len(appRows(appRows(profile, 14)[0], 8)) != 1 {
t.Fatal("profile click omitted representative owned room")
}
like := a.send("/MyRoomLike", appScalar(2, b.owner), 420, 0)
if appValue(like, 1) != 1 || appValue(like, 2) != 1 || appValue(like, 3) == 0 {
t.Fatal("monthly popularity omitted month,total or viewer date")
}
a.seq--
if replay := a.send("/MyRoomLike", appScalar(2, b.owner), 420, 0); !slices.Equal(like, replay) {
t.Fatal("popularity retry changed response")
}
a.send("/MyRoomLike", appScalar(2, b.owner), 420, 9003)
b.send("/MyRoomLike", appScalar(2, b.owner), 420, 9003)
if appValue(a.send("/UserContentsInfo", appScalar(2, b.owner), 215, 0), 18) != 1 {
t.Fatal("profile room popularity was not projected")
}
if rows := appRows(a.send("/MyRoomSearchRecommend", appScalar(2, 1), 231, 0), 1); len(rows) != 1 || appValue(rows[0], 1) != b.owner {
t.Fatal("popular visitor list omitted liked owner")
}
if rows := appRows(a.send("/MyRoomSearchRecommend", nil, 231, 0), 1); len(rows) != 1 || appValue(rows[0], 1) != b.owner {
t.Fatal("random visitor list omitted populated liked room")
}
templateItem := wire.AppendVarint(nil, 1, decorationIndex)
templateItem = wire.AppendVarint(templateItem, 2, 101)
templateItem = wire.AppendVarint(templateItem, 4, 1)
templateRoom := wire.AppendVarint(nil, 1, primary)
templateRoom = wire.AppendBytes(templateRoom, 3, decorationPosition)
template := wire.AppendVarint(nil, 1, 1)
template = wire.AppendString(template, 2, "Visited Layout")
template = wire.AppendBytes(template, 3, templateItem)
template = wire.AppendBytes(template, 4, templateRoom)
templateRequest := wire.AppendVarint(nil, 2, b.owner)
templateRequest = wire.AppendBytes(templateRequest, 3, template)
callerBeforeCopy := appRows(a.send("/MyRoomUserInfo", appScalar(2, a.owner), 228, 0), 1)[0]
itemsBeforeCopy := appRows(callerBeforeCopy, 5)
a.send("/MyRoomPresetSave", templateRequest, 642, 0)
copied := appRows(a.send("/MyRoomPresetInfo", nil, 641, 0), 2)
if len(copied) != 1 || appValue(copied[0], 1) != 1 || nicknameField(t, copied[0], 2) != "Visited Layout" || appValue(appRows(appRows(copied[0], 4)[0], 3)[0], 1) != decorationIndex {
t.Fatal("visitor template did not retain exact source layout")
}
ownAfterCopy := appRows(a.send("/MyRoomUserInfo", appScalar(2, a.owner), 228, 0), 1)[0]
itemsAfterCopy := appRows(ownAfterCopy, 5)
if !slices.EqualFunc(itemsBeforeCopy, itemsAfterCopy, func(a, b []byte) bool { return slices.Equal(a, b) }) {
t.Fatal("saving visitor template granted source furnishings to caller")
}
b.send("/MyRoomShareOptionUpdate", appScalar(2, 2), 645, 0)
a.send("/MyRoomUserInfo", appScalar(2, b.owner), 228, 9003)
a.send("/MyRoomPresetSave", templateRequest, 642, 9003)
if rows := appRows(a.send("/MyRoomSearchRecommend", appScalar(2, 1), 231, 0), 1); len(rows) != 0 {
t.Fatal("private room leaked into popular visits")
}
a.send("/FriendSend", appScalar(2, b.owner), 205, 0)
b.send("/FriendAccept", appScalar(2, a.owner), 206, 0)
if rows := appRows(a.send("/MyRoomSearchFriend", nil, 230, 0), 1); len(rows) != 1 {
t.Fatal("accepted friend could not visit friend-only room")
}
hidden := wire.AppendVarint(room, 4, 1)
b.send("/MyRoomSave", appMessage(2, hidden), 229, 0)
a.send("/MyRoomUserInfo", appScalar(2, b.owner), 228, 9003)
if rows := appRows(a.send("/MyRoomSearchFriend", nil, 230, 0), 1); len(rows) != 0 {
t.Fatal("hidden representative room remained in friend visit list")
}
b.send("/MyRoomSave", appMessage(2, room), 229, 0)
close()
open()
a, b = friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
drainFriendPublications(t, registry, shared, accounts[0])
drainFriendPublications(t, registry, shared, accounts[1])
view = appRows(a.send("/MyRoomUserInfo", appScalar(2, b.owner), 228, 0), 1)[0]
if appValue(view, 9) != 1 || appValue(view, 10) == 0 || appValue(view, 12) != 2 {
t.Fatal("reopen lost popularity, viewer timestamp or share scope")
}
copied = appRows(a.send("/MyRoomPresetInfo", nil, 641, 0), 2)
if len(copied) != 1 || nicknameField(t, copied[0], 2) != "Visited Layout" {
t.Fatal("visitor template lost across database reopen")
}
a.send("/MyRoomPresetNameChange", append(append(appScalar(2, 2), appScalar(3, 1)...), appMessage(4, []byte("Saved Visit"))...), 643, 0)
copied = appRows(a.send("/MyRoomPresetInfo", nil, 641, 0), 2)
if len(copied) != 1 || nicknameField(t, copied[0], 2) != "Saved Visit" {
t.Fatal("template rename did not persist")
}
a.send("/MyRoomPresetDelete", append(appScalar(2, 2), appScalar(3, 1)...), 644, 0)
if len(appRows(a.send("/MyRoomPresetInfo", nil, 641, 0), 2)) != 0 {
t.Fatal("deleted template remained in visitor saved list")
}
b.send("/MyRoomNameChange", append(appScalar(2, primary), appMessage(3, []byte("Renamed Room"))...), 234, 0)
view = appRows(a.send("/MyRoomUserInfo", appScalar(2, b.owner), 228, 0), 1)[0]
var renamed []byte
for _, v := range appRows(view, 8) {
if appValue(v, 1) == primary {
renamed = v
}
}
if len(renamed) == 0 || nicknameField(t, renamed, 2) != "Renamed Room" {
t.Fatal("room name change was not visible to friend")
}
a.send("/FriendRemove", appScalar(2, b.owner), 208, 0)
a.send("/MyRoomUserInfo", appScalar(2, b.owner), 228, 9003)
privateProfile := a.send("/UserContentsInfo", appScalar(2, b.owner), 215, 0)
if len(appRows(appRows(privateProfile, 14)[0], 8)) != 0 {
t.Fatal("profile click bypassed room privacy after friend removal")
}
}
@@ -660,4 +660,28 @@ func TestNativePVPGameplayUsesOwnedSnapshotsAndTickets(t *testing.T) {
if got := appValue(login[0], 58); got != want {
t.Fatalf("arena battle ticket debit=%d want %d", got, want)
}
profile := attacker.pvpCall("/UserContentsInfo", appScalar(2, appValue(login[0], 1)))
if appValue(profile, 8) == 0 || appValue(profile, 33) == 0 || appValue(profile, 7) == 0 || appValue(profile, 32) == 0 {
t.Fatal("settled PvP achievements disappeared from own social profile")
}
board := attacker.pvpCall("/TotalRanking", nil)
for _, section := range []struct{ field, season, boardSeason, score, rank int }{{1, 6, 6, 7, 8}, {5, 31, 9, 32, 33}} {
if appValue(profile, section.season) != appValue(board, section.boardSeason) {
t.Fatal("profile season disagrees with displayed leaderboard")
}
found := false
for _, row := range appRows(board, section.field) {
if appValue(row, 1) != appValue(profile, 1) {
continue
}
found = true
base := appRows(row, 7)
if len(base) != 1 || appValue(base[0], 1) != appValue(profile, section.score) || appValue(base[0], 2) != appValue(profile, section.rank) {
t.Fatal("profile PvP score/rank disagrees with actual shared leaderboard")
}
}
if !found {
t.Fatal("settled player absent from social leaderboard")
}
}
}
+10 -2
View File
@@ -24,6 +24,7 @@ type sharedRuntime struct {
rooms *roomResults
store *shared.Store
pvp *ranking.PVP
huntRanks *ranking.MonsterHunt
guild *social.Owner
friends *social.Friends
delivery atomic.Pointer[delivery.Dispatcher]
@@ -40,11 +41,15 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
if err != nil {
return nil, errors.Join(err, store.Close())
}
huntRanks, err := ranking.NewMonsterHunt(ctx, rankingStore{store})
if err != nil {
return nil, errors.Join(err, store.Close())
}
guild, err := social.New(socialStore{store}, design.guild)
if err != nil {
return nil, errors.Join(err, store.Close())
}
friends, err := social.NewFriends(socialStore{store}, design.friends)
friends, err := social.NewFriends(socialStore{store}, design.friends, design.guild.Supporters, design.rooms, time.Now)
if err != nil {
return nil, errors.Join(err, store.Close())
}
@@ -56,7 +61,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, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
return &sharedRuntime{store: store, pvp: pvp, huntRanks: huntRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
}
func (s *sharedRuntime) wake(account string) {
@@ -69,6 +74,9 @@ 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 == "monster_hunt.ranking" {
return s.consumeHuntRanking(ctx, event)
}
if event.Envelope.Event.Topic == "fishing.projection" {
return s.rooms.updateFishing(ctx, event)
}
@@ -10,6 +10,7 @@ import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/world"
"bd2server/internal/server/protocol/wire"
)
@@ -96,6 +97,9 @@ func newSkyWayPlayerScenario(t *testing.T) *skyWayPlayerScenario {
s.call(t, "/QuestUpdate", update)
clear := s.request(step.quest, 3004)
response := s.call(t, "/QuestClear", clear)
if pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint; pending != nil {
storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: pending.ID})
}
if step.quest == 3 {
complete := false
for _, row := range appRows(response, 11) {
+4 -1
View File
@@ -66,7 +66,10 @@ func (h storyCheckpoints) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
reply, err := future.Wait(r.Context())
if err != nil {
slog.Warn("Story checkpoint request failed", "phase", "execute", "operation", request.Operation, "error", err)
slog.Warn("Story checkpoint request failed", "phase", "execute", "operation", request.Operation,
"pack", request.PackID, "quest", request.QuestID, "difficulty", request.Difficulty,
"story_phase", request.Phase, "map", request.MapID, "timeline", request.Timeline,
"object", request.ObjectID, "talk_group", request.SimpleTalkGroupID, "error", err)
status := http.StatusServiceUnavailable
if errors.Is(err, world.ErrInvalidRequest) {
status = http.StatusBadRequest
@@ -39,6 +39,94 @@ func storyCheckpointCall(t *testing.T, owner *playerInstance, operation string,
return out
}
// 2.36.7 GameFieldManager starts QuestTable6/1's accept cinema from map629.
// GameData 20261008155037 MapTable assigns629 to pack6, while PackTable6's
// field21 lists only601,606,608,615,630,631. It is not the full map catalog.
func TestStoryChapterEntryCheckpointAcceptsInteriorMapAndSurvivesReload(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) {
if rule := p.design.world.Story.Packs[6].Open; rule != nil && rule.TicketID != 0 {
if _, err := p.ownedItems.GrantOnce(ctx, "chapter6-entry-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
t.Fatal(err)
}
}
})
s.protocol(t, "/PackInGameInfo", trapRequest(1, 6))
s.position(t, 6, 629)
beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
checkpoint := world.StoryCheckpoint{ID: "chapter6-entry", PackID: 6, QuestID: 1, Phase: "accept", Timeline: "Quest_Main_01_01", MapID: 629}
foreignMap := checkpoint
foreignMap.MapID = 51
body, err := json.Marshal(world.StoryCheckpointRequest{StoryCheckpoint: foreignMap, Operation: "begin"})
if err != nil {
t.Fatal(err)
}
_, err = s.owner.Execute(context.Background(), player.Command{Identity: command.Identity{AccountID: s.account, SessionID: "story-presentation", RequestID: fmt.Sprint(systemSequence.Add(1))}, Digest: sha256.Sum256(body), System: &player.SystemRequest{Kind: player.StoryCheckpoint, Body: body}})
if !errors.Is(err, world.ErrInvalidRequest) {
t.Fatalf("checkpoint in a different chapter's map was accepted: %v", err)
}
if pending := storyCheckpointCall(t, s.owner, "begin", checkpoint).Checkpoint; pending == nil || *pending != checkpoint {
t.Fatalf("chapter entry cinema did not begin: %+v", pending)
}
closeNicknamePlayer(t, s.owner)
s.owner = openNicknamePlayer(t, factory, s.account)
if pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint; pending == nil || *pending != checkpoint {
t.Fatalf("chapter entry cinema was lost after restart: %+v", pending)
}
storyCheckpointCall(t, s.owner, "complete", world.StoryCheckpoint{ID: checkpoint.ID})
if pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint; pending != nil {
t.Fatalf("finished entry cinema remained pending: %+v", pending)
}
if s.owner.assembly.progressState.QuestCleared(1, 6, 0) || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold {
t.Fatal("entry cinema recovery awarded a quest-clear reward or advanced the quest")
}
}
// Native FieldResearchObjectController grants a research reward only when
// CommonPacket.IsClearResearchObject is false; PackInGameInfo restores that
// set from field11. GameData pack5/5501 in map55 grants830 gold and collection504.
func TestResearchPointRestoresCollectedStateWithoutRepeatingRewardDelta(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) {
if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
if _, err := p.ownedItems.GrantOnce(ctx, "research-point-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
t.Fatal(err)
}
}
})
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
s.position(t, 5, 55)
beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
response := s.protocol(t, "/FieldObjectResearch", wire.AppendVarint(trapRequest(2, 5), 3, 5501))
collection := false
for _, item := range appRows(response, 2) {
collection = collection || appValue(item, 2) == 504 && appValue(item, 3) == 17 && appValue(item, 4) == 1
}
if !collection || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold+830 {
t.Fatal("research point did not grant its gold and collection reward")
}
closeNicknamePlayer(t, s.owner)
s.owner = openNicknamePlayer(t, factory, s.account)
entry := s.protocol(t, "/PackInGameInfo", trapRequest(3, 5))
if id, found, err := wire.Varint(entry, 11); err != nil || !found || id != 5501 {
t.Fatalf("rejoined field did not restore researched point: id%d found%v err%v", id, found, err)
}
preview := s.protocol(t, "/FieldObjectPreview", trapRequest(4, 5))
if id, found, err := wire.Varint(preview, 2); err != nil || !found || id != 5501 {
t.Fatalf("reward preview did not restore researched point: id%d found%v err%v", id, found, err)
}
response = s.protocol(t, "/FieldObjectResearch", wire.AppendVarint(trapRequest(5, 5), 3, 5501))
if len(appRows(response, 2)) != 0 || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold+830 {
t.Fatal("research retry after rejoin repeated a client reward delta or paid gold twice")
}
}
func TestStoryCheckpointHTTPNativeSessionReachesActorAndPersistsCompletion(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
s := &trapPlayerScenario{factory: factory, account: accounts[0]}
@@ -0,0 +1,198 @@
//go:build integration
package app
import (
"context"
"crypto/sha256"
"fmt"
"math"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/battle/monsterhunt"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/runtime/player"
"bd2server/internal/server/storage/outbox"
)
// LocalText1300023 ranks highest cleared difficulty, then damage. TotalRankUI
// consumes the same identity-bearing hunt rows as MonsterHuntRankInfo.
func TestTotalRankingSharesDurableHuntResultsAcrossPlayers(t *testing.T) {
factory, accounts := newIntegrationFactory(t)
design, err := factory.design.source.MonsterHunt(75)
if err != nil {
t.Fatal(err)
}
presets, err := gamedata.LoadMonsterHuntPresetDesign(factory.options.gameData, factory.options.gameDataVersion)
if err != nil {
t.Fatal(err)
}
now := time.Now()
factory.design.monsterHunt, err = monsterhunt.NewRules([]monsterhunt.Season{{ID: 81, Hunt: 75, Start: uint64(now.Add(-time.Hour).UnixMilli()), End: uint64(now.Add(time.Hour).UnixMilli())}}, factory.seeds.defaults, presets, factory.design.source.MonsterHunt)
if err != nil {
t.Fatal(err)
}
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
if err != nil {
t.Fatal(err)
}
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 err := s.owner.Close(); err != nil {
t.Error(err)
}
}
}
if err := shared.store.Close(); err != nil {
t.Error(err)
}
})
var owners [2]uint64
for i, s := range scenarios {
s.command(t, func(c command.Context) ([]byte, error) {
var err error
owners[i], err = s.owner.assembly.ProfileOwner(c)
return nil, err
})
}
request := func(s *monsterHuntScenario, path, id string) []byte {
t.Helper()
body := wire.AppendVarint(nil, 1, 1)
c := player.Command{Identity: command.Identity{AccountID: s.account, SessionID: "ranking-client", RequestID: id}, Digest: sha256.Sum256(append([]byte(path), body...)), Requests: []player.Request{{Path: path, Body: body}}}
if path == "/LoginUser" {
c.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
}
reply, err := s.owner.Execute(context.Background(), c)
if err != nil {
t.Fatal(err)
}
if len(reply.Responses) != 1 {
t.Fatal("ranking client received no response")
}
return reply.Responses[0].Body
}
publish := func(s *monsterHuntScenario, id string) {
t.Helper()
request(s, "/LoginUser", id)
tx, err := s.owner.repository.BeginCommand(context.Background())
if err != nil {
t.Fatal(err)
}
events, readErr := outbox.Read(tx, 128)
if err := tx.Rollback(); err != nil {
t.Fatal(err)
}
if readErr != nil {
t.Fatal(readErr)
}
for _, event := range events {
if err := shared.Consume(context.Background(), event); err != nil {
t.Fatal(err)
}
if err := shared.Consume(context.Background(), event); err != nil {
t.Fatal(err)
}
}
}
assertOrder := func(id string, first, second uint64) {
t.Helper()
body := request(scenarios[0], "/TotalRanking", id)
rows := rankingRows(t, body, 2)
if len(rows) != 2 {
t.Fatalf("shared board has %d players, want2", len(rows))
}
for i, expected := range []uint64{first, second} {
if owner, _, err := wire.Varint(rows[i], 1); err != nil || owner != expected {
t.Fatalf("ranking order owner%d want%d: %v", owner, expected, err)
}
if name, found, err := wire.Bytes(rows[i], 2); err != nil || !found || len(name) == 0 {
t.Fatal("ranking row cannot open identified player's profile")
}
if rank, _, _ := wire.Varint(rows[i], 7); rank != uint64(i+1) {
t.Fatalf("rank%d for place%d", rank, i+1)
}
}
if season, _, _ := wire.Varint(body, 7); season != 81 {
t.Fatalf("hunt board uses season%d", season)
}
personal := request(scenarios[0], "/MonsterHuntRankInfo", id+"-personal")
own := rankingRows(t, personal, 2)
if len(own) != 1 {
t.Fatal("personal hunt rank missing")
}
expectedRank := uint64(1)
if first != owners[0] {
expectedRank = 2
}
if rank, _, _ := wire.Varint(own[0], 7); rank != expectedRank {
t.Fatalf("personal rank%d disagrees with shared place%d", rank, expectedRank)
}
}
hp3, err := design.HP(3)
if err != nil {
t.Fatal(err)
}
hp5, err := design.HP(5)
if err != nil {
t.Fatal(err)
}
scenarios[0].battle(t, "first-clear", 3, true, 100, hp3)
scenarios[1].battle(t, "second-clear", 3, true, 200, hp3)
publish(scenarios[0], "first-publication")
publish(scenarios[1], "second-publication")
assertOrder("same-difficulty", owners[1], owners[0])
scenarios[0].battle(t, "higher-failure", 5, false, 1000000, hp5)
publish(scenarios[0], "failed-publication")
assertOrder("failed-attempt", owners[1], owners[0])
scenarios[0].battle(t, "higher-clear", 5, true, 1, hp5/2)
publish(scenarios[0], "higher-publication")
assertOrder("cleared-difficulty", owners[0], owners[1])
for _, s := range scenarios {
if err := s.owner.Close(); err != nil {
t.Fatal(err)
}
s.owner = nil
}
if err := shared.store.Close(); err != nil {
t.Fatal(err)
}
shared, err = openSharedRuntime(context.Background(), factory.options, factory.design)
if err != nil {
t.Fatal(err)
}
factory.shared, factory.pvpSource = shared, shared.pvp
for _, s := range scenarios {
s.open(t)
}
assertOrder("after-process-restart", owners[0], owners[1])
rows := shared.huntRanks.Top(81, 2)
if len(rows) != 2 || math.Abs(rows[1].TopPercent-100) > 0.0001 {
t.Fatal("rank percentage denominator lost the second player")
}
}
func rankingRows(t *testing.T, body []byte, field int) [][]byte {
t.Helper()
var rows [][]byte
if err := wire.Walk(body, func(f wire.Field) error {
if f.Number == field {
if f.Type != 2 {
return fmt.Errorf("ranking message wire type%d", f.Type)
}
rows = append(rows, f.Value)
}
return nil
}); err != nil {
t.Fatal(err)
}
return rows
}
@@ -46,7 +46,7 @@ func DefaultTextModeration() TextModerationConfig {
Type: "off", APIKeyHeader: "Authorization", Scopes: []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", "chat",
"guild_name", "guild_message", "guild_notice", "room_name", "chat",
},
TimeoutMS: 1500, FailurePolicy: "deny", SeverityThreshold: 4,
}}
@@ -13,6 +13,7 @@ type AchievementCondition struct{ Type, SubType, ParentGroup uint64 }
type AchievementCounterDesign struct {
Groups map[int][]int
Conditions map[int]AchievementCondition
Children map[int][]AchievementCondition
}
func LoadAchievementCounterDesign(root, version string) (*AchievementCounterDesign, error) {
@@ -32,6 +33,7 @@ func loadAchievementCounterDesign(db *sql.DB) (*AchievementCounterDesign, error)
defer func() { _ = rows.Close() }()
sets := map[int]map[int]bool{}
conditions := map[int]AchievementCondition{}
children := map[int][]AchievementCondition{}
for rows.Next() {
var raw []byte
if err := rows.Scan(&raw); err != nil {
@@ -51,6 +53,7 @@ func loadAchievementCounterDesign(db *sql.DB) (*AchievementCounterDesign, error)
// The wire update carries no content group.
if fields[13] != 0 {
children[fields[13]] = append(children[fields[13]], AchievementCondition{Type: uint64(fields[2]), SubType: uint64(fields[1]), ParentGroup: uint64(fields[13])})
continue
}
group, content := fields[9], fields[4]
@@ -70,7 +73,7 @@ func loadAchievementCounterDesign(db *sql.DB) (*AchievementCounterDesign, error)
if err := rows.Err(); err != nil {
return nil, err
}
design := &AchievementCounterDesign{Groups: map[int][]int{}, Conditions: conditions}
design := &AchievementCounterDesign{Groups: map[int][]int{}, Conditions: conditions, Children: children}
for group, contents := range sets {
for content := range contents {
design.Groups[group] = append(design.Groups[group], content)
@@ -4,10 +4,14 @@ import "fmt"
// GameplayAchievementGrades resolves subtype rarity from the current tables.
// Instances contain design IDs, never inferred numeric ID ranges.
type GameplayAchievementGrades struct{ Characters, Equipment map[uint64]uint64 }
type GameplayAchievementGrades struct {
Characters, Equipment, Costumes map[uint64]uint64
CharacterGrowth, EquipmentPrivate map[uint64]uint64
CostumeMaximum map[uint64]uint64
}
func LoadGameplayAchievementGrades(root, version string) (GameplayAchievementGrades, error) {
d := GameplayAchievementGrades{Characters: map[uint64]uint64{}, Equipment: map[uint64]uint64{}}
d := GameplayAchievementGrades{Characters: map[uint64]uint64{}, Equipment: map[uint64]uint64{}, Costumes: map[uint64]uint64{}, CharacterGrowth: map[uint64]uint64{}, EquipmentPrivate: map[uint64]uint64{}, CostumeMaximum: map[uint64]uint64{}}
db, closeDB, err := openStatDatabase(root, version)
if err != nil {
return d, err
@@ -35,6 +39,17 @@ func LoadGameplayAchievementGrades(root, version string) (GameplayAchievementGra
return d, fmt.Errorf("gamedata: invalid achievement grade %s/%d", spec.table, id)
}
spec.target[id] = grade[0]
field := 10
target := d.CharacterGrowth
if spec.table == "EquipmentTable" {
field, target = 16, d.EquipmentPrivate
}
value, err := optionalScalar(raw, field)
if err != nil {
_ = rows.Close()
return d, err
}
target[id] = value
}
err = rows.Err()
_ = rows.Close()
@@ -42,5 +57,74 @@ func LoadGameplayAchievementGrades(root, version string) (GameplayAchievementGra
return d, err
}
}
rows, err := db.Query("SELECT ProtoBuf FROM CharTable")
if err != nil {
return d, err
}
uniqueGrades := map[uint64]uint64{}
for rows.Next() {
var raw []byte
if err := rows.Scan(&raw); err != nil {
_ = rows.Close()
return d, err
}
kind, err := optionalScalar(raw, 19)
if err != nil {
_ = rows.Close()
return d, err
}
if kind != 0 {
continue
}
unique, err := optionalScalar(raw, 20)
if err != nil {
_ = rows.Close()
return d, err
}
grade, err := optionalScalar(raw, 9)
if err != nil {
_ = rows.Close()
return d, err
}
if previous, found := uniqueGrades[unique]; found && previous != grade {
_ = rows.Close()
return d, fmt.Errorf("gamedata: character rarity mismatch")
}
uniqueGrades[unique] = grade
}
err = rows.Err()
_ = rows.Close()
if err != nil {
return d, err
}
rows, err = db.Query("SELECT id,ProtoBuf FROM CostumeTable")
if err != nil {
return d, err
}
for rows.Next() {
var id uint64
var raw []byte
if err := rows.Scan(&id, &raw); err != nil {
_ = rows.Close()
return d, err
}
unique, err := optionalScalar(raw, 27)
if err != nil {
_ = rows.Close()
return d, err
}
d.Costumes[id] = uniqueGrades[unique]
maximum, err := optionalScalar(raw, 15)
if err != nil {
_ = rows.Close()
return d, err
}
d.CostumeMaximum[id] = maximum
}
err = rows.Err()
_ = rows.Close()
if err != nil {
return d, err
}
return d, nil
}
@@ -0,0 +1,68 @@
package gamedata
import (
"fmt"
"math"
)
type RoomProduct struct {
ID, Limit uint64
Reward Reward
Prices []Reward
}
type RoomCommerceDesign struct {
Products map[uint64]RoomProduct
Expansion map[uint64]Reward
}
func LoadRoomCommerceDesign(root, version string) (*RoomCommerceDesign, error) {
db, release, err := openStatDatabase(root, version)
if err != nil {
return nil, err
}
defer release()
d := &RoomCommerceDesign{Products: map[uint64]RoomProduct{}, Expansion: map[uint64]Reward{}}
if err := readCashMetadata(db, "MyRoomItemShopTable", func(raw []byte) error {
v, err := cashScalars(raw, 5, 1, 4, 3, 2)
if err != nil {
return err
}
types, err := packedInts(raw, 8)
if err != nil {
return err
}
ids, err := packedInts(raw, 7)
if err != nil {
return err
}
counts, err := packedInts(raw, 6)
if err != nil || len(types) == 0 || len(types) != len(ids) || len(types) != len(counts) || v[0] == 0 || v[1] == 0 || v[4] == 0 {
return fmt.Errorf("gamedata: invalid room product")
}
p := RoomProduct{ID: v[0], Limit: v[1], Reward: Reward{Type: v[2], ID: v[3], Count: v[4]}}
for i, typ := range types {
if typ > math.MaxInt32 || ids[i] > math.MaxInt32 || counts[i] > math.MaxInt32 {
return fmt.Errorf("gamedata: invalid room price")
}
p.Prices = append(p.Prices, Reward{Type: typ, ID: ids[i], Count: counts[i]})
}
d.Products[p.ID] = p
return nil
}); err != nil {
return nil, err
}
if err := readCashMetadata(db, "MyRoomExpandTable", func(raw []byte) error {
v, err := cashScalars(raw, 4, 3, 8, 7, 6)
if err != nil {
return err
}
if v[1] == 0 {
d.Expansion[v[0]] = Reward{Type: v[2], ID: v[3], Count: v[4]}
}
return nil
}); err != nil {
return nil, err
}
return d, nil
}
@@ -0,0 +1,64 @@
package gamedata
import "fmt"
type RoomLimits struct{ Objects, Carpets, Characters uint64 }
type RoomItem struct{ Kind, ObjectType, Location, MaxCount uint64 }
type RoomDesign struct {
Defaults []uint64
Limits map[uint64]RoomLimits
Items map[uint64]RoomItem
ListCount, MyPresets, UserPresets uint64
}
func LoadRoomDesign(root, version string) (*RoomDesign, error) {
db, done, err := openStatDatabase(root, version)
if err != nil {
return nil, err
}
defer done()
d := &RoomDesign{Limits: map[uint64]RoomLimits{}, Items: map[uint64]RoomItem{}}
var raw []byte
if err := db.QueryRow("SELECT ProtoBuf FROM MyRoomDefaultTable WHERE id=0").Scan(&raw); err != nil {
return nil, err
}
d.MyPresets, err = optionalScalar(raw, 6)
if err != nil {
return nil, err
}
d.UserPresets, err = optionalScalar(raw, 12)
if err != nil {
return nil, err
}
d.ListCount, err = optionalScalar(raw, 7)
if err != nil || d.ListCount == 0 || d.ListCount > 256 {
return nil, fmt.Errorf("gamedata: invalid room recommendation count")
}
if err := readCashMetadata(db, "MyRoomExpandTable", func(raw []byte) error {
v, err := cashScalars(raw, 4, 3, 5, 1, 2)
if err != nil {
return err
}
d.Limits[v[0]] = RoomLimits{Objects: v[2], Carpets: v[3], Characters: v[4]}
if v[1] != 0 {
d.Defaults = append(d.Defaults, v[0])
}
return nil
}); err != nil {
return nil, err
}
if len(d.Defaults) == 0 {
return nil, fmt.Errorf("gamedata: no default rooms")
}
if err := readCashMetadata(db, "MyRoomItemTable", func(raw []byte) error {
v, err := cashScalars(raw, 7, 23, 19, 15, 16)
if err != nil {
return err
}
d.Items[v[0]] = RoomItem{Kind: v[1], ObjectType: v[2], Location: v[3], MaxCount: v[4]}
return nil
}); err != nil {
return nil, err
}
return d, nil
}
@@ -0,0 +1,89 @@
package hunting
import (
"bd2server/internal/server/domain/command"
"bytes"
"encoding/json"
"fmt"
"maps"
"strconv"
)
type achievementProgressSnapshot struct {
History, Highest []byte
Counts map[uint64]uint64
}
// RecordedClearCounts uses retained boss settlements. Highest stage also
// proves at least one completion when old settlement receipts are absent.
func (s *Service) RecordedClearCounts(ctx command.Context) (map[uint64]uint64, error) {
if err := s.reload(ctx); err != nil {
return nil, err
}
highest := map[string]uint64{}
for key, state := range s.state.Packs {
highest[key] = state.Highest
}
highestRaw, err := json.Marshal(highest)
if err != nil {
return nil, err
}
historyRaw, err := s.storage.Load(ctx.State, "huntingbattle")
if err != nil {
return nil, err
}
if cached := s.achievementProgress; cached != nil && bytes.Equal(historyRaw, cached.History) && bytes.Equal(highestRaw, cached.Highest) {
return maps.Clone(cached.Counts), nil
}
ledger, err := s.loadBattleReceipts(ctx)
if err != nil {
return nil, err
}
counts := map[uint64]uint64{}
byPack := map[int]map[uint64]uint64{}
for _, receipt := range ledger {
var pack int
var mode, monster, deck uint64
if n, err := fmt.Sscanf(receipt.Fingerprint, "%d:%d:%d:%d", &pack, &mode, &monster, &deck); err != nil || n != 4 || mode != BattleMode {
continue
}
d, err := s.load(pack)
if err != nil {
return nil, err
}
for _, ground := range d.Grounds {
if ground.BossID != monster {
continue
}
if byPack[pack] == nil {
byPack[pack] = map[uint64]uint64{}
}
byPack[pack][ground.Difficulty]++
}
}
for key, state := range s.state.Packs {
pack, _ := strconv.Atoi(key)
if state.Highest == 0 {
continue
}
d, err := s.load(pack)
if err != nil {
return nil, err
}
highest, known := ground(d, state.Highest)
if !known {
return nil, fmt.Errorf("hunting: completed stage missing")
}
if byPack[pack] == nil {
byPack[pack] = map[uint64]uint64{}
}
byPack[pack][highest.Difficulty] = max(1, byPack[pack][highest.Difficulty])
}
for _, pack := range byPack {
for difficulty, count := range pack {
counts[difficulty] += count
}
}
s.achievementProgress = &achievementProgressSnapshot{History: append([]byte(nil), historyRaw...), Highest: highestRaw, Counts: maps.Clone(counts)}
return counts, nil
}
@@ -39,6 +39,7 @@ type Rules interface {
}
type Service struct {
achievementProgress *achievementProgressSnapshot
storage stateio.Store
inventory *assets.Inventory
wallet *assets.Wallet
@@ -0,0 +1,20 @@
package monsterhunt
import "strings"
// A settled battle reply remains proof of one completed attempt. Played
// records prove at least one attempt when only season progress was retained.
func (s *Service) RecordedBattleCount() uint64 {
var replies, played uint64
for key := range s.state.Replies {
if strings.HasPrefix(key, "battle:") {
replies++
}
}
for _, user := range s.state.Users {
if user.Played {
played++
}
}
return max(replies, played)
}
@@ -56,6 +56,8 @@ type Service struct {
transientVersion uint64
load func(uint64) (*gamedata.MonsterHunt, error)
rewardGrant func(ctx command.Context, _ string, _ []gamedata.Reward) ([]byte, error)
rankSource RankSource
rankOwner uint64
}
// RuleLoader returns shared immutable hunt rules.
@@ -54,9 +54,7 @@ func (s *Service) rankWire(u user) ([]byte, error) {
if err != nil {
return nil, err
}
b := wire.AppendVarint(nil, 7, rank.Rank)
b = wire.AppendDouble(b, 8, rank.Score)
return wire.AppendDouble(b, 10, rank.TopPercent), nil
return RankWire(rank), nil
}
func (s *Service) grant(ctx command.Context, identity string, rewards []gamedata.BattleReward) ([]byte, error) {
@@ -546,13 +544,20 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
if id == 0 {
id = c.ID
}
if s.rankSource != nil {
for _, entry := range s.rankSource.Top(id, 100) {
out = wire.AppendBytes(out, 1, RankWire(entry))
}
}
if v, ok := s.state.Users[strconv.FormatUint(id, 10)]; ok && v.Played {
b, rankErr := s.rankWire(v)
if rankErr != nil {
e = rankErr
break
}
out = wire.AppendBytes(out, 1, b)
if s.rankSource == nil {
out = wire.AppendBytes(out, 1, b)
}
out = wire.AppendBytes(out, 2, b)
}
case "/MonsterHuntPresetInfo":
@@ -1,23 +1,111 @@
package monsterhunt
import "strconv"
import (
"bd2server/internal/server/protocol/wire"
"slices"
"strconv"
)
type publicRank struct {
Rank uint64
Score, TopPercent float64
type RankProfile struct {
Owner, XP, Portrait, PortraitDesign, Title uint64
Name string
Guild []byte
}
func (s *Service) ranking(u user) (publicRank, error) {
type RankRecord struct {
Season, Level, Damage uint64
Version uint64
Score float64
}
type RankEntry struct {
RankRecord
Profile RankProfile
Rank uint64
TopPercent float64
}
type RankPublication struct {
Account string
Version uint64
Profile RankProfile
Records []RankRecord
}
type RankSource interface {
Top(season uint64, limit int) []RankEntry
Rank(owner uint64, record RankRecord) RankEntry
}
func RankWire(entry RankEntry) []byte {
p := entry.Profile
out := wire.AppendVarint(nil, 1, p.Owner)
out = wire.AppendString(out, 2, p.Name)
out = wire.AppendVarint(out, 3, p.XP)
out = wire.AppendVarint(out, 4, p.Portrait)
out = wire.AppendVarint(out, 5, p.PortraitDesign)
out = wire.AppendBytes(out, 6, p.Guild)
out = wire.AppendVarint(out, 7, entry.Rank)
out = wire.AppendDouble(out, 8, entry.Score)
out = wire.AppendVarint(out, 9, p.Title)
return wire.AppendDouble(out, 10, entry.TopPercent)
}
func (s *Service) AttachRanking(owner uint64, source RankSource) {
s.rankOwner, s.rankSource = owner, source
}
func (s *Service) CurrentSeason() uint64 { return s.current().ID }
func (s *Service) RankRecords() ([]RankRecord, error) {
var records []RankRecord
keys := make([]string, 0, len(s.state.Users))
for key := range s.state.Users {
keys = append(keys, key)
}
slices.Sort(keys)
for _, key := range keys {
u := s.state.Users[key]
if !u.Played || u.RankLevel == 0 {
continue
}
record, err := s.rankRecord(u)
if err != nil {
return nil, err
}
records = append(records, record)
}
return records, nil
}
func (s *Service) rankRecord(u user) (RankRecord, error) {
score, err := s.score(u)
if err != nil {
return publicRank{}, err
return RankRecord{}, err
}
return publicRank{Rank: 1, Score: score, TopPercent: 100}, nil
design, err := s.load(u.Hunt)
if err != nil {
return RankRecord{}, err
}
return RankRecord{Season: u.Season, Level: u.RankLevel, Damage: u.RankDamage, Score: score, Version: design.RankingVersion}, nil
}
func (s *Service) ranking(u user) (RankEntry, error) {
record, err := s.rankRecord(u)
if err != nil {
return RankEntry{}, err
}
if record.Level == 0 {
return RankEntry{RankRecord: record}, nil
}
if s.rankSource != nil {
return s.rankSource.Rank(s.rankOwner, record), nil
}
return RankEntry{RankRecord: record, Rank: 1, TopPercent: 100}, nil
}
func (s *Service) ProfileRank() (uint64, float64, error) {
season := s.current()
u, ok := s.state.Users[strconv.FormatUint(season.ID, 10)]
u, ok := s.state.Users[strconv.FormatUint(s.current().ID, 10)]
if !ok || !u.Played {
return 0, 0, nil
}
@@ -0,0 +1,18 @@
package pvp
// Retained season records prove actual victories and defeats; reset deck
// statistics and the current rank do not substitute for battle history.
func (s *Service) RecordedBattleCounts() map[[2]uint64]uint64 {
out := map[[2]uint64]uint64{}
for mode, state := range s.state.Modes {
win, loss := uint64(37), uint64(38)
if mode == Colosseum {
win, loss = 138, 139
}
for _, progress := range state.Progress {
out[[2]uint64{win, 0}] += progress.Wins + progress.DefenseWins
out[[2]uint64{loss, 0}] += progress.Losses + progress.DefenseLosses
}
}
return out
}
@@ -342,6 +342,22 @@ func rankWire(mode Mode, r RankEntry) []byte {
out = wire.AppendBytes(out, 7, baseInfo(mode, r.VP, r.Rank, r.Wins, r.Losses, r.TopPercent))
return wire.AppendVarint(out, 8, p.Title)
}
func (s *Service) RankingSnapshot(mode Mode, limit int) (uint64, [][]byte, error) {
c, err := s.current(mode)
if err != nil {
return 0, nil, err
}
rows, err := s.source.Ranking(RankQuery{Mode: mode, Season: c.ID, Limit: limit})
if err != nil {
return 0, nil, err
}
out := make([][]byte, len(rows))
for i, row := range rows {
out[i] = rankWire(mode, row)
}
return c.ID, out, nil
}
func (s *Service) ranking(mode Mode, request []byte) ([]byte, error) {
season, e := scalar(request, 2)
if e != nil {
@@ -0,0 +1,76 @@
package fishing
import (
"bd2server/internal/server/protocol/wire"
"math"
"strings"
)
// Catch replies and retained fish instances are deduplicated by inventory
// index. The codex proves one catch of species whose fish was already sold.
func (s *Service) AchievementProgress() (map[[2]uint64]uint64, error) {
values := map[[2]uint64]uint64{{141, 0}: s.state.Level, {142, 0}: uint64(len(s.state.Collection))}
fish := map[uint64]Item{}
for _, item := range s.state.Fish {
fish[item.Index] = item
}
for key, reply := range s.state.Replies {
if !strings.Contains(key, ":/FishingBiteEnd:") && !strings.Contains(key, ":/FishingFishAuto:") {
continue
}
bundle, _, err := wire.Bytes(reply.Body, 1)
if err != nil {
return nil, err
}
if err := wire.Walk(bundle, func(field wire.Field) error {
if field.Number != 11 || field.Type != 2 {
return nil
}
index, _, err := wire.Varint(field.Value, 1)
if err != nil {
return err
}
id, _, err := wire.Varint(field.Value, 2)
if err != nil {
return err
}
size, _, err := wire.Varint(field.Value, 3)
if err != nil {
return err
}
fish[index] = Item{Index: index, ID: id, Size: size, Count: 1}
return nil
}); err != nil {
return nil, err
}
}
counts, maxSizes := map[uint64]uint64{}, map[uint64]uint64{}
for _, item := range fish {
counts[item.ID] += item.Count
row, err := s.design.Row("FishingFishTable", 12, item.ID)
if err != nil {
return nil, err
}
if item.Size >= uint64(math.Round(dbl(row, 14))) {
maxSizes[item.ID] += item.Count
}
}
for id, collection := range s.state.Collection {
counts[id] = max(1, counts[id])
row, err := s.design.Row("FishingFishTable", 12, id)
if err != nil {
return nil, err
}
if collection.Max >= uint64(math.Round(dbl(row, 14))) {
maxSizes[id] = max(1, maxSizes[id])
}
}
for id, count := range counts {
values[[2]uint64{144, id}] = count
values[[2]uint64{146, 0}] += count
}
for _, count := range maxSizes {
values[[2]uint64{143, 0}] += count
}
return values, nil
}
@@ -1,6 +1,14 @@
package identity
import "time"
import (
"context"
"time"
)
type GameProfile struct {
AccountID string `json:"account_id"`
UID string `json:"uid"`
}
type ProviderIdentity struct{ Issuer, Subject string }
type Config struct {
@@ -73,6 +81,7 @@ type Repository interface {
FailAuthorization(id string) error
DecodeDeviceResult(id string, cipher []byte) (TokenSet, error)
AccessToken(token string) (AccessRecord, error)
PublicGameProfile(ctx context.Context, accountID string) (GameProfile, error)
AdministratorAccountID() (string, error)
}
@@ -1,6 +1,7 @@
package identity
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
@@ -416,6 +417,14 @@ func (s *Service) ValidateAccess(token string) (string, error) {
return row.AccountID, nil
}
func (s *Service) SessionProfile(ctx context.Context, token string) (GameProfile, error) {
accountID, err := s.ValidateAccess(token)
if err != nil {
return GameProfile{}, failure(Unauthorized, "access token invalid")
}
return s.store.PublicGameProfile(ctx, accountID)
}
func (s *Service) AuthorizeAdministrator(token string) (string, error) {
accountID, err := s.ValidateAccess(token)
if err != nil {
@@ -0,0 +1,45 @@
package inventory
import (
"os"
"path/filepath"
"testing"
)
func TestDevelopmentSettingsRejectMalformedAccountConfiguration(t *testing.T) {
path := filepath.Join(t.TempDir(), "dev-tools.json")
for _, document := range []string{
`{"version":1,"inventory":{"unlimited":true}}`,
`{"version":2}`,
`{"version":2,"accounts":null}`,
`{"version":2,"accounts":{"A":null}}`,
`{"version":2,"accounts":{"A":{"inventory":null}}}`,
`{"version":2,"accounts":{"A":{"inventory":{}}}}`,
`{"version":2,"accounts":{"A":{"inventory":{"unlimited":null}}}}`,
`{"version":2,"accounts":{"A":{"inventory":{"unlimited":"true"}}}}`,
`{"version":2,"accounts":{"A":{"inventory":{"unlimited":true,"other":false}}}}`,
`{"version":2,"accounts":{"A":{"inventory":{"unlimited":true}}}} {}`,
} {
if err := os.WriteFile(path, []byte(document), 0o600); err != nil {
t.Fatal(err)
}
if _, err := loadUnlimitedInventory(path, "B"); err == nil {
t.Fatalf("malformed settings accepted for unrelated account: %s", document)
}
}
}
func TestMissingDevelopmentSettingsDisableOverride(t *testing.T) {
path := filepath.Join(t.TempDir(), "dev-tools.json")
if unlimited, err := loadUnlimitedInventory(path, "A"); err != nil || unlimited {
t.Fatalf("missing settings: unlimited=%v error=%v", unlimited, err)
}
if err := os.WriteFile(path, []byte(`{"version":2,"accounts":{"A":{"inventory":{"unlimited":true}}}}`), 0o600); err != nil {
t.Fatal(err)
}
for _, account := range []string{"B", ""} {
if unlimited, err := loadUnlimitedInventory(path, account); err != nil || unlimited {
t.Fatalf("missing account %q: unlimited=%v error=%v", account, unlimited, err)
}
}
}
@@ -14,7 +14,7 @@ import (
"os"
)
const developmentSettingsVersion = 1
const developmentSettingsVersion = 2
type InventorySlotCounts struct {
Items uint64 `json:"items"`
@@ -29,9 +29,13 @@ type inventorySlotSnapshot struct {
}
type developmentSettings struct {
Version int `json:"version"`
Version int `json:"version"`
Accounts map[string]*developmentAccountSettings `json:"accounts"`
}
type developmentAccountSettings struct {
Inventory *struct {
Unlimited bool `json:"unlimited"`
Unlimited *bool `json:"unlimited"`
} `json:"inventory"`
}
@@ -117,7 +121,7 @@ func (s *InventorySlots) EnsurePersisted(ctx command.Context) error {
func (s *InventorySlots) InventorySlotCounts(ctx command.Context) (InventorySlotCounts, error) {
counts := s.state.InventorySlotCounts
unlimited, err := loadUnlimitedInventory(s.settingsPath)
unlimited, err := loadUnlimitedInventory(s.settingsPath, ctx.AccountID)
if err != nil {
return InventorySlotCounts{}, err
}
@@ -136,7 +140,7 @@ func (s *InventorySlots) UserInventorySlots(ctx command.Context) (items, storage
return counts.Items, counts.Storage, counts.Equipment, counts.EquipmentStorage, nil
}
func loadUnlimitedInventory(path string) (bool, error) {
func loadUnlimitedInventory(path, accountID string) (bool, error) {
if path == "" {
return false, nil
}
@@ -156,10 +160,19 @@ func loadUnlimitedInventory(path string) (bool, error) {
if err := decoder.Decode(&struct{}{}); err != io.EOF {
return false, errors.New("player: malformed development settings")
}
if settings.Version != developmentSettingsVersion || settings.Inventory == nil {
if settings.Version != developmentSettingsVersion {
return false, errors.New("player: unsupported development settings version")
}
return settings.Inventory.Unlimited, nil
if settings.Accounts == nil {
return false, errors.New("player: malformed development settings")
}
for id, account := range settings.Accounts {
if id == "" || account == nil || account.Inventory == nil || account.Inventory.Unlimited == nil {
return false, errors.New("player: malformed development settings")
}
}
account := settings.Accounts[accountID]
return account != nil && *account.Inventory.Unlimited, nil
}
func inventorySlotPrice(rule gamedata.InventorySlotRule, current, count uint64) (uint64, error) {
+28 -13
View File
@@ -14,16 +14,21 @@ import (
var ErrNotFound = errors.New("profile: target public profile not found")
type Snapshot struct {
OwnerIndex, TitleID, PortraitCostumeID, PortraitDesignID uint64
AchievementLevel, TotalBattlePower, MonsterHuntRank uint64
UserID string
MonsterHuntTopPercent float64
Greeting string
IsAllPrivate bool
Options, SortIDs []uint64
Card Card
Supporters []CostumeBase
AvatarUse *AvatarUse
OwnerIndex, TitleID, PortraitCostumeID, PortraitDesignID uint64
AchievementLevel, TotalBattlePower, MonsterHuntRank, LikeCount uint64
UserID string
MonsterHuntTopPercent float64
Greeting string
IsAllPrivate, IsFriend bool
Options, SortIDs []uint64
Card Card
Supporters []CostumeBase
GuildBase, RoomInfo []byte
RoomLikeCount uint64
PvpSeason, PvpVP, PvpRank, ColosseumSeason, ColosseumVP, ColosseumRank uint64
GuildRaidRank, GuildRaidScore uint64
ColosseumTopPercent float64
AvatarUse *AvatarUse
}
type Source interface {
@@ -79,7 +84,7 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
if p.OwnerIndex != target || p.UserID == "" {
return fail(ErrNotFound)
}
for _, v := range []uint64{p.TitleID, p.PortraitCostumeID, p.PortraitDesignID, p.AchievementLevel, p.TotalBattlePower, p.MonsterHuntRank} {
for _, v := range []uint64{p.TitleID, p.PortraitCostumeID, p.PortraitDesignID, p.AchievementLevel, p.TotalBattlePower, p.MonsterHuntRank, p.LikeCount} {
if v > math.MaxInt32 {
return fail(fmt.Errorf("profile: integer exceeds protocol range"))
}
@@ -99,19 +104,29 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
for _, field := range []struct {
Number int
Value uint64
}{{3, p.TitleID}, {4, p.PortraitCostumeID}, {9, p.MonsterHuntRank}, {16, p.TotalBattlePower}, {19, p.PortraitDesignID}, {26, p.AchievementLevel}} {
}{{3, p.TitleID}, {4, p.PortraitCostumeID}, {6, p.PvpSeason}, {7, p.PvpVP}, {8, p.PvpRank}, {9, p.MonsterHuntRank}, {10, p.LikeCount}, {16, p.TotalBattlePower}, {19, p.PortraitDesignID}, {20, p.GuildRaidRank}, {21, p.GuildRaidScore}, {26, p.AchievementLevel}, {31, p.ColosseumSeason}, {32, p.ColosseumVP}, {33, p.ColosseumRank}} {
if field.Value != 0 {
out = wire.AppendVarint(out, field.Number, field.Value)
}
}
if p.IsFriend {
out = wire.AppendVarint(out, 13, 1)
}
room := wire.AppendVarint(nil, 1, p.OwnerIndex)
room = wire.AppendString(room, 2, p.UserID)
room = wire.AppendVarint(room, 3, p.PortraitCostumeID)
room = wire.AppendVarint(room, 11, p.PortraitDesignID)
if len(p.RoomInfo) > 0 {
room = p.RoomInfo
}
out = wire.AppendBytes(out, 14, room)
out = wire.AppendVarint(out, 18, p.RoomLikeCount)
// UserInfoPacket dereferences GuildBaseInfo.Id even for a guildless user.
out = wire.AppendBytes(out, 17, nil)
out = wire.AppendBytes(out, 17, p.GuildBase)
out = wire.AppendBytes(out, 28, cardWire(p.Card))
if p.ColosseumTopPercent > 0 {
out = wire.AppendDouble(out, 35, p.ColosseumTopPercent)
}
for _, c := range p.Supporters {
out = wire.AppendBytes(out, 30, costumeBaseWire(c))
}
@@ -17,7 +17,7 @@ import (
"unicode/utf8"
)
var profileCodes = map[string]int{"/UserContentsInfo": 215, "/UserContentsInfoOption": 216, "/UpdateUserContentsInfoOption": 217, "/UserGreetingChange": 219, "/UserTitleChange": 225, "/UserPortraitChange": 75, "/IdCardSave": 446, "/IdCardShopInfo": 447, "/IdCardShopBuy": 448, "/IdCardPresetSave": 449, "/IdCardPresetInfo": 450, "/IdCardPresetDelete": 451, "/IdCardRecovery": 452, "/SupporterDetail": 434, "/SupporterRegister": 435, "/SupporterRemove": 436, "/SupporterStatus": 438, "/SupporterInfo": 443, "/SupporterReward": 442}
var profileCodes = map[string]int{"/UserContentsInfo": 215, "/UserContentsInfoOption": 216, "/UpdateUserContentsInfoOption": 217, "/UserGreetingChange": 219, "/UserTitleChange": 225, "/UserPortraitChange": 75, "/IdCardSave": 446, "/IdCardShopInfo": 447, "/IdCardShopBuy": 448, "/IdCardPresetSave": 449, "/IdCardPresetInfo": 450, "/IdCardPresetDelete": 451, "/IdCardRecovery": 452, "/SupporterDetail": 434, "/SupporterRegister": 435, "/SupporterRemove": 436, "/SupporterStatus": 438, "/SupporterInfo": 443}
func (s *Service) handleSettings(ctx command.Context, path string, request []byte, seq uint64) (int, []byte, bool, error) {
code := profileCodes[path]
@@ -55,9 +55,6 @@ func (s *Service) PublicSupporterDetails(ctx command.Context) (map[uint64][]byte
}
func (s *Service) handleSupporters(ctx command.Context, path string, request []byte, settings *Settings) ([]byte, bool, error) {
if path == "/SupporterReward" {
return nil, false, fmt.Errorf("profile: no supporter rental reward history exists")
}
if path == "/SupporterRegister" {
index, err := profileScalar(request, 2, 1)
if err != nil {
@@ -13,11 +13,12 @@ import (
type GameplayAchievementRecordedEvent struct {
Identity string
Type, SubType, Count uint64
RecordedHistory bool
}
// ApplyGameplayProgress keeps one observer boundary on one validated counter
// snapshot. Conditions are applied first and events retain their original
// order. Event receipts and all counter changes are written atomically; the
// snapshot. Exact conditions precede events; retained-state floors follow
// increments. Event receipts and all counter changes are written atomically; the
// next boundary loads fresh state from its transaction, including after retry.
func (s *AchievementService) ApplyGameplayProgress(ctx command.Context, conditions []GameplayAchievementCondition, events []GameplayAchievementRecordedEvent) (map[int]uint64, map[int]uint64, error) {
@@ -42,6 +43,16 @@ func (s *AchievementService) ApplyGameplayProgress(ctx command.Context, conditio
for key := range groups {
sort.Ints(groups[key])
}
conditionGroups := func(c GameplayAchievementCondition) ([]int, error) {
if c.GroupID == 0 {
return groups[[2]uint64{c.Type, c.SubType}], nil
}
group := int(c.GroupID)
if uint64(group) != c.GroupID || s.design.Conditions[group].Type != c.Type || s.design.Conditions[group].SubType != c.SubType {
return nil, fmt.Errorf("achievement: condition group mismatch")
}
return []int{group}, nil
}
var changes []stateio.EntryMutation
set := func(group int, value int64) {
key := strconv.Itoa(group)
@@ -53,7 +64,14 @@ func (s *AchievementService) ApplyGameplayProgress(ctx command.Context, conditio
if condition.Value > math.MaxInt64 {
return nil, nil, fmt.Errorf("achievement: invalid absolute value")
}
for _, group := range groups[[2]uint64{condition.Type, condition.SubType}] {
if condition.LowerBound {
continue
}
targets, err := conditionGroups(condition)
if err != nil {
return nil, nil, err
}
for _, group := range targets {
if state.Counts[strconv.Itoa(group)] != int64(condition.Value) {
set(group, int64(condition.Value))
}
@@ -79,6 +97,9 @@ func (s *AchievementService) ApplyGameplayProgress(ctx command.Context, conditio
continue
}
for _, group := range groups[[2]uint64{event.Type, event.SubType}] {
if event.RecordedHistory {
continue
}
old := state.Counts[strconv.Itoa(group)]
if old > math.MaxInt64-int64(event.Count) {
return nil, nil, fmt.Errorf("achievement: event overflow")
@@ -88,6 +109,22 @@ func (s *AchievementService) ApplyGameplayProgress(ctx command.Context, conditio
pending[event.Identity] = digest
changes = append(changes, stateio.EntryMutation{Bucket: "achievement_events", Key: event.Identity, Payload: []byte(digest)})
}
// A retained-state floor overlaps events from the same operation. Apply it
// after increments so one acquisition cannot be counted twice.
for _, condition := range conditions {
if !condition.LowerBound {
continue
}
targets, err := conditionGroups(condition)
if err != nil {
return nil, nil, err
}
for _, group := range targets {
if state.Counts[strconv.Itoa(group)] < int64(condition.Value) {
set(group, int64(condition.Value))
}
}
}
if len(changes) != 0 {
if err := s.store.SaveWithEntries(ctx.State, "missions", nil, changes); err != nil {
return nil, nil, err
@@ -104,22 +141,3 @@ func (s *AchievementService) AchievementValue(ctx command.Context, groupID uint6
}
return uint64(state.Counts[strconv.FormatUint(groupID, 10)]), nil
}
// SetCondition only accepts exact current-state conditions; cumulative events use RecordEvent.
func (s *AchievementService) CounterValues(ctx command.Context) (map[int]uint64, error) {
state, err := s.load(ctx)
if err != nil {
return nil, err
}
out := map[int]uint64{}
for key, value := range state.Counts {
group, err := strconv.Atoi(key)
if err != nil {
return nil, err
}
out[group] = uint64(value)
}
return out, nil
}
@@ -12,12 +12,6 @@ import (
// GameplayAchievementCounter persists each event in the request transaction.
type GameplayAchievementCounter interface {
RecordEvent(ctx command.Context, _ string, _ uint64, _ uint64, _ uint64) ([][]byte, error)
SetCondition(ctx command.Context, _ uint64, _ uint64, _ uint64) ([][]byte, error)
CounterValues(ctx command.Context) (map[int]uint64, error)
}
type gameplayAchievementProgressBatch interface {
ApplyGameplayProgress(ctx command.Context, _ []GameplayAchievementCondition, _ []GameplayAchievementRecordedEvent) (map[int]uint64, map[int]uint64, error)
}
type GameplayAchievementEvent struct {
@@ -25,15 +19,21 @@ type GameplayAchievementEvent struct {
Identity string
StableIdentity bool
}
type GameplayAchievementCondition struct{ Type, SubType, Value uint64 }
type GameplayAchievementCondition struct {
Type, SubType, Value uint64
LowerBound bool
GroupID uint64
}
type GameplayAchievementSnapshot struct {
Characters map[uint64]roster.Character
Costumes map[uint64]roster.Costume
Equipment map[uint64]assets.Equipment
Items map[[2]uint64]uint64
Conditions []GameplayAchievementCondition
FieldObjects map[string]gamedata.FieldRewardObject
GachaGrants map[string]uint64
Characters map[uint64]roster.Character
Costumes map[uint64]roster.Costume
Equipment map[uint64]assets.Equipment
Items map[[2]uint64]uint64
Conditions []GameplayAchievementCondition
FieldObjects map[string]gamedata.FieldRewardObject
ResearchObjects map[string]gamedata.FieldResearchObject
GachaGrants map[string]uint64
CharAwake map[uint64]roster.CharAwakeProgress
}
type GameplayAchievementProvider interface {
Snapshot(ctx command.Context) (GameplayAchievementSnapshot, error)
@@ -78,20 +78,24 @@ type GameplayItemSource interface {
}
// OwnedGameplayAchievementProvider uses before/after authoritative ownership.
// GET conditions are event counters: existing inventory is never a historical
// acquisition total. Conditions are supplied only by proven state projections.
// Existing possessions prove a lower bound on acquisitions. Before/after
// changes keep counting new operations beyond that bound.
type OwnedGameplayAchievementProvider struct {
Gacha GameplayGachaSource
Characters GameplayCharacterSource
Costumes GameplayCostumeSource
Equipment GameplayEquipmentSource
Items GameplayItemSource
Design *gamedata.AchievementCounterDesign
CharacterGrades, EquipmentGrades map[uint64]uint64
Conditions func(command.Context) ([]GameplayAchievementCondition, error)
FieldObjects func(command.Context) (map[string]gamedata.FieldRewardObject, error)
StateVersion func() uint64
TransientVersion func() string
Gacha GameplayGachaSource
Characters GameplayCharacterSource
Costumes GameplayCostumeSource
Equipment GameplayEquipmentSource
Items GameplayItemSource
Design *gamedata.AchievementCounterDesign
CharacterGrades, EquipmentGrades map[uint64]uint64
CostumeGrades, CharacterGrowth, EquipmentPrivate map[uint64]uint64
CostumeMaximum map[uint64]uint64
Potential *gamedata.CostumePotentialDesign
Conditions func(command.Context) ([]GameplayAchievementCondition, error)
FieldObjects func(command.Context) (map[string]gamedata.FieldRewardObject, error)
StateVersion func() uint64
TransientVersion func() string
Project func(command.Context, *GameplayAchievementSnapshot) error
}
func (p *OwnedGameplayAchievementProvider) ObservationVersion() string {
@@ -132,6 +136,17 @@ func (p *OwnedGameplayAchievementProvider) Snapshot(ctx command.Context) (Gamepl
if p.Gacha != nil {
s.GachaGrants = p.Gacha.GachaGrantSummary()
}
if source, ok := p.Costumes.(interface {
CharAwakeStates() map[uint64]roster.CharAwakeProgress
}); ok {
s.CharAwake = source.CharAwakeStates()
}
if err == nil {
s.Conditions = append(s.Conditions, p.ownedConditions(s)...)
if p.Project != nil {
err = p.Project(ctx, &s)
}
}
return s, err
}
@@ -183,8 +198,8 @@ func (p *OwnedGameplayAchievementProvider) Events(path string, _ []byte, _ []byt
emit(20, grade, 1, id)
}
}
if exists && v.Level > old.Level {
emit(22, 0, v.Level-old.Level, id)
if path == "/CharGrowth" && exists && v.ID == old.ID && (v.Level > old.Level || v.Exp > old.Exp) {
emit(22, 0, 1, id)
}
}
for index, v := range after.Costumes {
@@ -241,6 +256,11 @@ func (p *OwnedGameplayAchievementProvider) Events(path string, _ []byte, _ []byt
}
}
}
for key := range after.ResearchObjects {
if _, found := before.ResearchObjects[key]; !found {
emit(29, 0, 1, key)
}
}
for identity, count := range after.GachaGrants {
if _, exists := before.GachaGrants[identity]; !exists {
emit(54, 0, count, "gacha-grant:"+identity)
@@ -249,6 +269,24 @@ func (p *OwnedGameplayAchievementProvider) Events(path string, _ []byte, _ []byt
}
}
}
eventConditions := map[uint64]bool{1: true, 3: true, 5: true, 6: true, 7: true, 9: true, 10: true, 18: true, 20: true, 21: true, 24: true, 26: true, 27: true, 28: true, 29: true, 30: true, 31: true, 32: true, 37: true, 38: true, 53: true, 54: true, 79: true, 83: true, 84: true, 86: true, 87: true, 101: true, 109: true, 138: true, 139: true, 143: true, 146: true}
prior := map[[2]uint64]uint64{}
for _, c := range before.Conditions {
if c.LowerBound && c.GroupID == 0 {
prior[[2]uint64{c.Type, c.SubType}] = max(prior[[2]uint64{c.Type, c.SubType}], c.Value)
}
}
emitted := map[[2]uint64]bool{}
for _, event := range events {
emitted[[2]uint64{event.Type, event.SubType}] = true
}
for _, c := range after.Conditions {
key := [2]uint64{c.Type, c.SubType}
if c.LowerBound && c.GroupID == 0 && eventConditions[c.Type] && !emitted[key] && c.Value > prior[key] {
emit(c.Type, c.SubType, c.Value-prior[key], fmt.Sprintf("state:%d:%d", c.Type, c.SubType))
emitted[key] = true
}
}
sort.Slice(events, func(i, j int) bool {
a, b := events[i], events[j]
if a.Type != b.Type {
@@ -143,7 +143,7 @@ func (s *AchievementService) Handle(ctx command.Context, path string, request []
}
// SyncRecordedHistory must run within the startup account transaction. Retained
// real grants establish a lower bound; inventory never substitutes for history.
// grants and retained gameplay state establish proven lower bounds.
func (s *GameplayAchievementObserver) SyncRecordedHistory(ctx command.Context) error {
snapshot, err := s.provider.Snapshot(ctx)
if err != nil {
@@ -160,23 +160,14 @@ func (s *GameplayAchievementObserver) SyncRecordedHistory(ctx command.Context) e
if count == 0 {
continue
}
events = append(events, GameplayAchievementRecordedEvent{Identity: "gacha-grant:" + identity, Type: 54, Count: count})
events = append(events, GameplayAchievementRecordedEvent{Identity: "gacha-grant:" + identity, Type: 54, Count: count, RecordedHistory: true})
}
if batch, ok := s.counter.(gameplayAchievementProgressBatch); ok {
_, _, err := batch.ApplyGameplayProgress(ctx, snapshot.Conditions, events)
return err
_, values, err := s.counter.ApplyGameplayProgress(ctx, snapshot.Conditions, events)
if err == nil {
s.before, s.counters, s.conditionValues = snapshot, values, values
s.version, s.ready = s.observationVersion(), true
}
for _, condition := range snapshot.Conditions {
if _, err := s.counter.SetCondition(ctx, condition.Type, condition.SubType, condition.Value); err != nil {
return err
}
}
for _, event := range events {
if _, err := s.counter.RecordEvent(ctx, event.Identity, event.Type, event.SubType, event.Count); err != nil {
return err
}
}
return nil
return err
}
func (s *GameplayAchievementObserver) BeforeDispatch(ctx command.Context, _ string, _ []byte) error {
@@ -190,30 +181,12 @@ func (s *GameplayAchievementObserver) BeforeDispatch(ctx command.Context, _ stri
if err != nil {
return err
}
if batch, ok := s.counter.(gameplayAchievementProgressBatch); ok {
s.counters, s.conditionValues, err = batch.ApplyGameplayProgress(ctx, s.before.Conditions, nil)
if err == nil {
s.version = s.observationVersion()
s.ready = true
}
return err
s.counters, s.conditionValues, err = s.counter.ApplyGameplayProgress(ctx, s.before.Conditions, nil)
if err == nil {
s.version = s.observationVersion()
s.ready = true
}
s.counters, err = s.counter.CounterValues(ctx)
if err != nil {
return err
}
for _, condition := range s.before.Conditions {
if _, err := s.counter.SetCondition(ctx, condition.Type, condition.SubType, condition.Value); err != nil {
return err
}
}
s.conditionValues, err = s.counter.CounterValues(ctx)
if err != nil {
return err
}
s.version = s.observationVersion()
s.ready = true
return nil
return err
}
func (s *GameplayAchievementObserver) AfterDispatch(ctx command.Context, path string, request, response []byte) ([]byte, error) {
@@ -228,14 +201,6 @@ func (s *GameplayAchievementObserver) AfterDispatch(ctx command.Context, path st
if err != nil {
return nil, err
}
batch, batches := s.counter.(gameplayAchievementProgressBatch)
if !batches {
for _, condition := range after.Conditions {
if _, err := s.counter.SetCondition(ctx, condition.Type, condition.SubType, condition.Value); err != nil {
return nil, err
}
}
}
events, err := s.provider.Events(path, request, response, s.before, after)
if err != nil {
return nil, err
@@ -254,17 +219,7 @@ func (s *GameplayAchievementObserver) AfterDispatch(ctx command.Context, path st
recorded = append(recorded, GameplayAchievementRecordedEvent{Identity: identity, Type: event.Type, SubType: event.SubType, Count: event.Count})
}
}
var values map[int]uint64
if batches {
_, values, err = batch.ApplyGameplayProgress(ctx, after.Conditions, recorded)
} else {
for _, event := range recorded {
if _, err = s.counter.RecordEvent(ctx, event.Identity, event.Type, event.SubType, event.Count); err != nil {
return nil, err
}
}
values, err = s.counter.CounterValues(ctx)
}
_, values, err := s.counter.ApplyGameplayProgress(ctx, after.Conditions, recorded)
if err != nil {
return nil, err
}
@@ -341,41 +296,3 @@ func (s *AchievementService) RecordEvent(ctx command.Context, identity string, c
}
return updates, nil
}
func (s *AchievementService) SetCondition(ctx command.Context, conditionType, subType, value uint64) ([][]byte, error) {
if value > math.MaxInt64 {
return nil, fmt.Errorf("achievement: invalid absolute value")
}
state, err := s.load(ctx)
if err != nil {
return nil, err
}
var groups []int
for group, c := range s.design.Conditions {
if c.Type == conditionType && c.SubType == subType {
groups = append(groups, group)
}
}
sort.Ints(groups)
var changes []stateio.EntryMutation
var updates [][]byte
for _, group := range groups {
key := strconv.Itoa(group)
if state.Counts[key] == int64(value) {
continue
}
raw, _ := json.Marshal(value)
changes = append(changes, stateio.EntryMutation{Bucket: "achievement_counts", Key: key, Payload: raw})
update := wire.AppendVarint(nil, 1, uint64(group))
update = wire.AppendVarint(update, 2, value)
updates = append(updates, wire.AppendVarint(update, 3, 1))
}
if len(changes) == 0 {
return nil, nil
}
if err := s.store.SaveWithEntries(ctx.State, "missions", nil, changes); err != nil {
return nil, err
}
return updates, nil
}
@@ -0,0 +1,108 @@
package achievements
import "sort"
// Remaining possessions establish a minimum acquisition history. They never
// replace a larger counter, nor imply consumed items or discarded equipment.
func (p *OwnedGameplayAchievementProvider) ownedConditions(s GameplayAchievementSnapshot) []GameplayAchievementCondition {
values := map[[2]uint64]uint64{}
add := func(kind, sub, count uint64) { values[[2]uint64{kind, sub}] += count }
for _, c := range s.Characters {
add(20, p.CharacterGrades[c.ID], 1)
if grade := p.CharacterGrowth[c.ID]; grade > 0 {
add(21, 0, grade-1)
}
if c.TalentLevel > 0 {
add(24, 0, c.TalentLevel-1)
for level := uint64(2); level <= c.TalentLevel; level++ {
add(25, level, 1)
}
}
}
for _, c := range s.Costumes {
add(26, 0, 1)
add(26, c.ID, 1)
add(27, 0, c.Level)
add(83, p.CostumeGrades[c.ID], c.Level)
}
for _, e := range s.Equipment {
add(7, 0, 1)
if grade := p.EquipmentGrades[e.ID]; grade > 0 {
add(7, grade, 1)
}
add(9, p.EquipmentGrades[e.ID], e.Level)
if e.UpgradeAttempts >= e.Level {
add(10, 0, e.UpgradeAttempts-e.Level)
}
if p.EquipmentPrivate[e.ID] > 0 {
add(86, 0, 1)
add(87, 0, e.Level)
}
}
for key, count := range s.Items {
add(1, key[0], count)
if key[0] == 8 {
add(3, key[1], count)
}
}
for _, count := range s.GachaGrants {
add(54, 0, count)
}
conditions := make([]GameplayAchievementCondition, 0, len(values))
for key, value := range values {
conditions = append(conditions, GameplayAchievementCondition{Type: key[0], SubType: key[1], Value: value, LowerBound: true})
}
if p.Potential != nil && p.Design != nil {
potential, maximum, private := map[uint64]bool{}, map[uint64]bool{}, map[uint64]bool{}
for _, c := range s.Costumes {
unique := p.Potential.CostumeUnique[c.ID]
nodes := p.Potential.Nodes[c.ID]
all := len(nodes) > 0 && len(c.PotentialIDs) == len(nodes)
for _, id := range c.PotentialIDs {
if _, found := nodes[id]; !found {
all = false
}
}
potential[unique] = potential[unique] || all
maximum[unique] = maximum[unique] || p.CostumeMaximum[c.ID] > 0 && c.Level >= p.CostumeMaximum[c.ID]
}
for _, e := range s.Equipment {
if p.EquipmentGrades[e.ID] == 4 {
private[p.EquipmentPrivate[e.ID]] = true
}
}
for group, children := range p.Design.Children {
if p.Design.Conditions[group].Type != 111 {
continue
}
var completed uint64
for _, child := range children {
var satisfied bool
switch child.Type {
case 112:
satisfied = potential[child.SubType]
case 113:
satisfied = s.CharAwake[child.SubType].IsAwake
case 114:
satisfied = maximum[child.SubType]
case 115:
satisfied = private[child.SubType]
}
if satisfied {
completed++
}
}
conditions = append(conditions, GameplayAchievementCondition{Type: 111, GroupID: uint64(group), Value: completed, LowerBound: true})
}
}
sort.Slice(conditions, func(i, j int) bool {
if conditions[i].Type != conditions[j].Type {
return conditions[i].Type < conditions[j].Type
}
if conditions[i].SubType != conditions[j].SubType {
return conditions[i].SubType < conditions[j].SubType
}
return conditions[i].GroupID < conditions[j].GroupID
})
return conditions
}
@@ -4,6 +4,7 @@ import (
"bd2server/internal/server/design/gamedata"
"fmt"
"math"
"strconv"
"strings"
)
@@ -28,19 +29,32 @@ func (s *Service) AchievementExperience() (uint64, error) {
}
func (s *Service) achievementExperienceLocked() (uint64, error) {
var total uint64
known := map[string]bool{}
for key := range s.design.Achievements {
known["achievement:"+achievementName(key)] = true
}
seen := map[string]bool{}
for _, identity := range s.state.Claimed {
if strings.HasPrefix(identity, "achievement:") && !known[identity] {
return 0, fmt.Errorf("missions: incompatible claimed achievement %q missing from current GameData", identity)
}
}
for key, d := range s.design.Achievements {
if !contains(s.state.Claimed, "achievement:"+achievementName(key)) {
if seen[identity] {
continue
}
seen[identity] = true
name, achievement := strings.CutPrefix(identity, "achievement:")
if !achievement {
continue
}
parts := strings.Split(name, "/")
var key gamedata.AchievementKey
if len(parts) != 3 {
return 0, fmt.Errorf("missions: invalid claimed achievement")
}
for i, target := range []*uint64{&key.ContentsGroup, &key.GroupID, &key.ID} {
value, err := strconv.ParseUint(parts[i], 10, 64)
if err != nil {
return 0, fmt.Errorf("missions: invalid claimed achievement")
}
*target = value
}
d, known := s.design.Achievements[key]
if !known || achievementName(key) != name {
return 0, fmt.Errorf("missions: claimed achievement missing from current GameData")
}
if total > math.MaxUint64-d.AddExp {
return 0, fmt.Errorf("missions: achievement experience overflow")
}
@@ -48,3 +62,13 @@ func (s *Service) achievementExperienceLocked() (uint64, error) {
}
return total, nil
}
func (s *Service) ClaimedMissionCount() uint64 {
var count uint64
for _, identity := range s.state.Claimed {
if strings.HasPrefix(identity, "mission:") {
count++
}
}
return count
}
@@ -0,0 +1,224 @@
package ranking
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"slices"
"sort"
"sync"
"bd2server/internal/server/domain/battle/monsterhunt"
)
type MonsterHunt struct {
store Store
writer sync.Mutex
mu sync.RWMutex
players map[uint64]monsterhunt.RankPublication
boards map[uint64][]monsterhunt.RankEntry
}
func NewMonsterHunt(ctx context.Context, store Store) (*MonsterHunt, error) {
if store == nil {
return nil, errors.New("hunt ranking requires persistence")
}
r := &MonsterHunt{store: store, players: map[uint64]monsterhunt.RankPublication{}, boards: map[uint64][]monsterhunt.RankEntry{}}
err := store.View(ctx, func(tx Tx) error {
for cursor := ""; ; {
rows, err := tx.Scan("monster_hunt.players", "", cursor, 256)
if err != nil {
return err
}
if len(rows) == 0 {
return nil
}
for _, row := range rows {
var publication monsterhunt.RankPublication
if err := json.Unmarshal(row.Value, &publication); err != nil {
return err
}
if err := validHuntPublication(publication); err != nil {
return err
}
if _, exists := r.players[publication.Profile.Owner]; exists {
return errors.New("duplicate hunt ranking owner")
}
r.players[publication.Profile.Owner] = publication
for _, record := range publication.Records {
r.boards[record.Season] = append(r.boards[record.Season], monsterhunt.RankEntry{RankRecord: record, Profile: publication.Profile})
}
cursor = row.Key
}
}
})
for season, board := range r.boards {
slices.SortFunc(board, compareHunt)
r.boards[season] = board
}
return r, err
}
func validHuntPublication(p monsterhunt.RankPublication) error {
if p.Account == "" || p.Profile.Owner == 0 || p.Version == 0 {
return errors.New("invalid hunt ranking identity")
}
seen := map[uint64]bool{}
for _, row := range p.Records {
if row.Season == 0 || row.Level == 0 || row.Version > 1 || row.Score <= 0 || math.IsNaN(row.Score) || math.IsInf(row.Score, 0) || seen[row.Season] {
return errors.New("invalid hunt ranking result")
}
seen[row.Season] = true
}
return nil
}
func compareHunt(a, b monsterhunt.RankEntry) int {
if a.Version == 0 && a.Score != b.Score {
if a.Score > b.Score {
return -1
}
return 1
}
if a.Level != b.Level {
if a.Level > b.Level {
return -1
}
return 1
}
if a.Version == 1 && a.Damage != b.Damage {
if a.Damage > b.Damage {
return -1
}
return 1
}
if a.Profile.Owner < b.Profile.Owner {
return -1
}
if a.Profile.Owner > b.Profile.Owner {
return 1
}
return 0
}
func (r *MonsterHunt) apply(p monsterhunt.RankPublication) {
for _, record := range p.Records {
board := r.boards[record.Season]
board = slices.DeleteFunc(board, func(row monsterhunt.RankEntry) bool { return row.Profile.Owner == p.Profile.Owner })
entry := monsterhunt.RankEntry{RankRecord: record, Profile: p.Profile}
i := sort.Search(len(board), func(i int) bool { return compareHunt(board[i], entry) >= 0 })
board = slices.Insert(board, i, entry)
r.boards[record.Season] = board
}
r.players[p.Profile.Owner] = p
}
func (r *MonsterHunt) Publish(ctx context.Context, p monsterhunt.RankPublication) error {
if err := validHuntPublication(p); err != nil {
return err
}
r.writer.Lock()
defer r.writer.Unlock()
r.mu.RLock()
old := r.players[p.Profile.Owner]
r.mu.RUnlock()
if old.Account != "" && old.Account != p.Account {
return errors.New("hunt ranking owner conflict")
}
if old.Version >= p.Version {
return nil
}
for _, previous := range old.Records {
found := false
for _, next := range p.Records {
if next.Season != previous.Season {
continue
}
found = true
if compareHunt(monsterhunt.RankEntry{RankRecord: next}, monsterhunt.RankEntry{RankRecord: previous}) > 0 {
return errors.New("hunt ranking result regressed")
}
}
if !found {
return errors.New("hunt ranking publication lost season")
}
}
raw, err := json.Marshal(p)
if err != nil {
return err
}
var owned monsterhunt.RankPublication
if err := json.Unmarshal(raw, &owned); err != nil {
return err
}
if err := r.store.Update(ctx, func(tx Tx) error {
return tx.Put("monster_hunt.players", fmt.Sprintf("%020d", p.Profile.Owner), raw)
}); err != nil {
return err
}
r.mu.Lock()
r.apply(owned)
r.mu.Unlock()
return nil
}
func huntPlaced(entry monsterhunt.RankEntry, rank, count int) monsterhunt.RankEntry {
entry.Profile.Guild = slices.Clone(entry.Profile.Guild)
entry.Rank = uint64(rank)
entry.TopPercent = float64(rank) * 100 / float64(count)
return entry
}
func (r *MonsterHunt) Top(season uint64, limit int) []monsterhunt.RankEntry {
r.mu.RLock()
defer r.mu.RUnlock()
board := r.boards[season]
out := make([]monsterhunt.RankEntry, min(max(limit, 0), len(board)))
for i := range out {
out[i] = huntPlaced(board[i], i+1, len(board))
}
return out
}
func (r *MonsterHunt) Rank(owner uint64, record monsterhunt.RankRecord) monsterhunt.RankEntry {
r.mu.RLock()
defer r.mu.RUnlock()
profile := r.players[owner].Profile
profile.Owner = owner
entry := monsterhunt.RankEntry{RankRecord: record, Profile: profile}
board := r.boards[record.Season]
count := len(board) + 1
position := sort.Search(len(board), func(i int) bool { return compareHunt(board[i], entry) >= 0 })
for _, old := range r.players[owner].Records {
if old.Season != record.Season {
continue
}
count--
previous := monsterhunt.RankEntry{RankRecord: old, Profile: profile}
oldPosition := sort.Search(len(board), func(i int) bool { return compareHunt(board[i], previous) >= 0 })
if oldPosition < position {
position--
}
break
}
return huntPlaced(entry, position+1, count)
}
func (r *MonsterHunt) OwnerRank(season, owner uint64) (monsterhunt.RankEntry, bool) {
r.mu.RLock()
p := r.players[owner]
var record monsterhunt.RankRecord
for _, row := range p.Records {
if row.Season == season {
record = row
break
}
}
r.mu.RUnlock()
if record.Season == 0 {
return monsterhunt.RankEntry{}, false
}
return r.Rank(owner, record), true
}
@@ -22,6 +22,14 @@ func (s *Store) ActivatedWaypoint(pack, id uint64) bool {
return hasWaypoint(s.state.Waypoints[pack], id)
}
func (s *Store) ActivatedWaypointCount() uint64 {
var count uint64
for _, points := range s.state.Waypoints {
count += uint64(len(points))
}
return count
}
func hasWaypoint(points []uint64, id uint64) bool {
return slices.Contains(points, id)
}
@@ -0,0 +1,195 @@
package social_test
import (
"context"
"encoding/base64"
"errors"
"fmt"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/profile"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/protocol/wire"
)
func TestProfileLikesAndRentalClaimsAcrossDailyReset(t *testing.T) {
ctx := context.Background()
store := &memoryStore{rows: map[string]map[string][]byte{}}
// Independently inspected 20261008155037 SupportCharacterDefaultTable 0:
// fields3/2/1=3/3/10, reward fields7/6/8=44/0/2. LocalText6711
// explicitly preserves unclaimed rentals after the daily reset.
rules := gamedata.SupporterRules{DailyUses: 3, DailyRecommendedUses: 3, DailyRewardClaims: 10, Reward: gamedata.Reward{Type: 44, Count: 2}}
now := time.Date(2026, 10, 12, 23, 59, 0, 0, time.UTC)
friends, err := social.NewFriends(store, gamedata.FriendRules{Friends: 50, Sent: 50, Received: 50, Recommended: 10, ExpireDays: 7}, rules, nil, func() time.Time { return now })
if err != nil {
t.Fatal(err)
}
owner, err := social.New(store, &gamedata.GuildDesign{Guild: gamedata.GuildRules{MaxMembers: 20}, Supporters: rules})
if err != nil {
t.Fatal(err)
}
for index := uint64(1); index <= 5; index++ {
slot := wire.AppendVarint(nil, 1, index)
slot = wire.AppendVarint(slot, 3, 101)
slot = wire.AppendString(slot, 6, base64.StdEncoding.EncodeToString(wire.AppendBytes(nil, 1, wire.AppendVarint(nil, 1, index+10))))
if err := friends.Publish(ctx, social.FriendProfile{AccountID: fmt.Sprint(index), OwnerIndex: index, Version: 1, Snapshot: profile.Snapshot{OwnerIndex: index, UserID: fmt.Sprint(index), Supporters: []profile.CostumeBase{{ID: 101, DesignID: 5}, {ID: 201, DesignID: 6}}}, SupporterDetails: map[uint64][]byte{0: wire.AppendBytes(nil, 1, slot)}}); err != nil {
t.Fatal(err)
}
}
seq := uint64(0)
call := func(actor uint64, path string, fields []byte) ([]byte, error) {
seq++
_, body, err := friends.Execute(ctx, command.Identity{AccountID: fmt.Sprint(actor), SessionID: "daily", RequestID: fmt.Sprint(seq)}, actor, path, append(wire.AppendVarint(nil, 1, seq), fields...), 0)
return body, err
}
for actor := uint64(1); actor <= 5; actor++ {
if actor == 2 {
continue
}
if _, err := call(actor, "/SupporterBattleInfo", wire.AppendVarint(nil, 2, 1)); err != nil {
t.Fatal(err)
}
}
if _, err := call(1, "/LikeUser", wire.AppendVarint(nil, 2, 2)); err != nil {
t.Fatal(err)
}
if _, err := call(1, "/LikeUser", wire.AppendVarint(nil, 2, 3)); err == nil {
t.Fatal("daily quota was per target instead of global")
}
// Two earlier unclaimed uses remain eligible after the reset; today's
// twelfth use must remain visible without creating an extra entitlement.
for range 2 {
if _, err := call(1, "/SupporterBorrow", wire.AppendVarint(nil, 2, 2)); err != nil {
t.Fatal(err)
}
}
now = now.Add(24 * time.Hour)
var histories []uint64
var totalHistories int
for actor := uint64(1); actor <= 5; actor++ {
if actor == 2 {
continue
}
for range 3 {
if _, err := call(actor, "/SupporterBorrow", wire.AppendVarint(nil, 2, 2)); err != nil {
t.Fatal(err)
}
}
}
if _, err := call(1, "/SupporterBorrow", wire.AppendVarint(nil, 2, 2)); err == nil {
t.Fatal("recommended rental quota was not enforced")
}
// Path of Adventure has an independent allowance for the same lender.
independent := command.Identity{AccountID: "1", SessionID: "daily", RequestID: "adventure-picker"}
if _, _, err := friends.Execute(ctx, independent, 1, "/SupporterBattleInfo", wire.AppendVarint(wire.AppendVarint(nil, 1, 1000), 2, 9), 5); err != nil {
t.Fatal(err)
}
independent.RequestID = "adventure-borrow"
if _, _, err := friends.Execute(ctx, independent, 1, "/SupporterBorrow", wire.AppendVarint(wire.AppendVarint(nil, 1, 1001), 2, 2), 5); err != nil {
t.Fatalf("story quota blocked independent adventure allowance: %v", err)
}
if _, err := call(1, "/SupporterBattleInfo", wire.AppendVarint(nil, 2, 1)); err != nil {
t.Fatal(err)
}
status, err := call(2, "/SupporterStatus", wire.AppendVarint(nil, 2, 50))
if err != nil {
t.Fatal(err)
}
if err := wire.Walk(status, func(f wire.Field) error {
if f.Number == 1 {
totalHistories++
id, _, err := wire.Varint(f.Value, 1)
if err != nil {
return err
}
received, _, err := wire.Varint(f.Value, 12)
if err != nil {
return err
}
if received == 0 {
histories = append(histories, id)
}
return err
}
return nil
}); err != nil {
t.Fatal(err)
}
if totalHistories != 15 {
t.Fatalf("visible rental history=%d want15", totalHistories)
}
if len(histories) != 12 {
t.Fatalf("history count=%d want12 eligible", len(histories))
}
claim := func(account string, index uint64, id string, ids []uint64) (social.Reservation, error) {
return owner.Prepare(ctx, social.Operation{ID: id, Kind: social.SupporterClaim, Actor: member(account, index), AtMS: now.UnixMilli(), Day: now.Format("2006-01-02"), UsageIDs: ids})
}
if _, err := claim("1", 1, "steal", histories[:1]); !errors.Is(err, social.ErrIneligible) {
t.Fatalf("other lender's rental claim error=%v", err)
}
r, err := claim("2", 2, "daily-ten", histories[:10])
if err != nil {
t.Fatal(err)
}
if len(r.Grants) != 1 || r.Grants[0] != (gamedata.Reward{Type: 44, Count: 20}) {
t.Fatalf("ten rental rewards=%+v", r.Grants)
}
if _, err := claim("2", 2, "parallel", histories[10:]); !errors.Is(err, social.ErrPending) {
t.Fatalf("prepared claim did not isolate simultaneous rewards: %v", err)
}
if _, err := owner.Cancel(ctx, proof(r)); err != nil {
t.Fatal(err)
}
r, err = claim("2", 2, "daily-ten-retry", histories[:10])
if err != nil {
t.Fatal(err)
}
if _, err := owner.Confirm(ctx, proof(r)); err != nil {
t.Fatal(err)
}
if _, err := owner.Confirm(ctx, proof(r)); err != nil {
t.Fatal(err)
}
if _, err := claim("2", 2, "daily-overflow", histories[10:]); !errors.Is(err, social.ErrCapacity) {
t.Fatalf("daily reward ceiling error=%v", err)
}
if available, err := friends.SupporterRewardAvailable(ctx, 2); err != nil || available {
t.Fatalf("reward badge ignored daily ceiling available=%v error=%v", available, err)
}
now = now.Add(2 * time.Minute)
like, err := call(1, "/MyLikeInfo", nil)
if err != nil {
t.Fatal(err)
}
if len(like) != 0 {
t.Fatal("daily like target did not reset")
}
if _, err := call(1, "/LikeUser", wire.AppendVarint(nil, 2, 2)); err != nil {
t.Fatal(err)
}
if count, err := friends.LikeCount(ctx, 2); err != nil || count != 2 {
t.Fatalf("received total lost across daily reset count=%d error=%v", count, err)
}
if available, err := friends.SupporterRewardAvailable(ctx, 2); err != nil || !available {
t.Fatalf("unclaimed history did not survive daily reset available=%v error=%v", available, err)
}
r, err = claim("2", 2, "old-unclaimed", histories[10:])
if err != nil {
t.Fatal(err)
}
if len(r.Grants) != 1 || r.Grants[0].Count != 4 {
t.Fatal("old unclaimed rentals lost their reward entitlement")
}
if _, err := owner.Confirm(ctx, proof(r)); err != nil {
t.Fatal(err)
}
if _, err := claim("2", 2, "already-claimed", histories[:1]); !errors.Is(err, social.ErrIneligible) {
t.Fatalf("claimed history reused across reset: %v", err)
}
if _, err := call(1, "/SupporterBorrow", wire.AppendVarint(nil, 2, 2)); err != nil {
t.Fatalf("lender rental uses did not reset: %v", err)
}
}
@@ -0,0 +1,371 @@
package social
import (
"context"
"encoding/base64"
"encoding/json"
"math"
"slices"
"bd2server/internal/server/protocol/wire"
)
const supporterHistoryBucket = "friend.supporter_history"
const supporterClaimsBucket = "friend.supporter_claims"
func (f *Friends) SupporterRewardAvailable(ctx context.Context, owner uint64) (bool, error) {
available := false
err := f.store.View(ctx, func(tx Tx) error {
var claims uint64
if _, err := load(tx, supporterClaimsBucket, numberKey(owner)+":"+socialDay(f.now().UnixMilli()), &claims); err != nil {
return err
}
if claims >= f.supporters.DailyRewardClaims {
return nil
}
for cursor := ""; ; {
rows, err := tx.Scan(supporterHistoryBucket, numberKey(owner)+":", cursor, 256)
if err != nil {
return err
}
if len(rows) == 0 {
return nil
}
for _, row := range rows {
cursor = row.Key
var v supporterUsage
if err := json.Unmarshal(row.Value, &v); err != nil {
return err
}
if !v.Received && v.RewardEligible {
available = true
return nil
}
}
}
})
return available, err
}
type supporterSelection struct {
Content uint64
Allowed bool
}
type supporterUsage struct {
ID, Owner, Slot, Costume, Design, BorrowType uint64
Borrower FriendProfile
AtMS int64
Received, RewardEligible bool
}
func supporterHistoryKey(owner, id uint64) string { return numberKey(owner) + ":" + numberKey(id) }
func supporterUseKey(borrower, lender uint64, day string, content uint64) string {
return numberKey(borrower) + ":" + day + ":" + numberKey(lender) + ":" + numberKey(content)
}
func supporterRelation(tx Tx, a, b uint64) (bool, error) {
var rel FriendRelation
_, err := load(tx, "friend.relations", friendKey(a, b), &rel)
return rel.Accepted, err
}
func supporterDeck(tx Tx, p FriendProfile, borrower uint64, day string, content uint64) ([]byte, error) {
friends, err := supporterRelation(tx, borrower, p.OwnerIndex)
if err != nil {
return nil, err
}
count := uint64(0)
if _, err = load(tx, "friend.supporter_uses", supporterUseKey(borrower, p.OwnerIndex, day, content), &count); err != nil {
return nil, err
}
out := wire.AppendVarint(nil, 1, p.OwnerIndex)
out = wire.AppendString(out, 2, p.Snapshot.UserID)
out = wire.AppendVarint(out, 3, p.Snapshot.TitleID)
out = wire.AppendVarint(out, 4, p.Snapshot.PortraitCostumeID)
out = wire.AppendString(out, 5, p.Snapshot.Greeting)
if friends {
out = wire.AppendVarint(out, 6, 1)
}
base, err := friendWire(tx, p, 0)
if err != nil {
return nil, err
}
guild, _, err := wire.Bytes(base, 7)
if err != nil {
return nil, err
}
out = wire.AppendBytes(out, 7, guild)
out = wire.AppendVarint(out, 8, p.Snapshot.PortraitDesignID)
for slot := range uint64(2) {
if data := p.SupporterDetails[slot]; len(data) > 0 {
row, found, err := wire.Bytes(data, 1)
if err != nil || !found {
return nil, ErrInvalid
}
out = wire.AppendBytes(out, 9, row)
}
}
return wire.AppendVarint(out, 10, count), nil
}
func supporterHistoryWire(v supporterUsage) []byte {
p := v.Borrower
out := wire.AppendVarint(nil, 1, v.ID)
out = wire.AppendVarint(out, 2, p.OwnerIndex)
out = wire.AppendString(out, 3, p.Snapshot.UserID)
out = wire.AppendVarint(out, 4, p.Snapshot.PortraitCostumeID)
out = wire.AppendVarint(out, 5, p.Snapshot.PortraitDesignID)
out = wire.AppendVarint(out, 6, p.Snapshot.TitleID)
out = wire.AppendVarint(out, 7, v.Owner)
out = wire.AppendVarint(out, 8, v.Slot)
out = wire.AppendVarint(out, 9, v.Costume)
out = wire.AppendVarint(out, 10, v.Design)
out = wire.AppendVarint(out, 11, v.BorrowType)
if v.Received || !v.RewardEligible {
out = wire.AppendVarint(out, 12, 1)
}
return wire.AppendVarint(out, 13, uint64(v.AtMS))
}
func (f *Friends) supporter(tx Tx, self FriendProfile, path string, p packet, now int64, session string, content uint64) ([]byte, error) {
day := socialDay(now)
if path == "/SupporterStatus" {
limit, err := p.integer(2)
if err != nil || limit == 0 || limit > 256 {
return nil, ErrInvalid
}
last, err := p.integer(3)
if err != nil {
return nil, err
}
var out []byte
var histories []supporterUsage
for cursor := ""; ; {
rows, err := tx.Scan(supporterHistoryBucket, numberKey(self.OwnerIndex)+":", cursor, 256)
if err != nil {
return nil, err
}
if len(rows) == 0 {
break
}
for _, row := range rows {
cursor = row.Key
var v supporterUsage
if err := json.Unmarshal(row.Value, &v); err != nil {
return nil, err
}
if last == 0 || v.ID < last {
histories = append(histories, v)
}
}
}
slices.SortFunc(histories, func(a, b supporterUsage) int {
if a.ID > b.ID {
return -1
}
if a.ID < b.ID {
return 1
}
return 0
})
if len(histories) > int(limit) {
histories = histories[:limit]
}
for _, row := range histories {
out = wire.AppendBytes(out, 1, supporterHistoryWire(row))
}
for _, base := range self.Snapshot.Supporters {
b := wire.AppendVarint(nil, 1, base.ID)
b = wire.AppendVarint(b, 2, base.Level)
b = wire.AppendVarint(b, 3, base.DesignID)
out = wire.AppendBytes(out, 2, b)
}
account, err := readAccount(tx, self.AccountID)
if err != nil {
return nil, err
}
if account.GuildID != 0 {
guild, err := readGuild(tx, account.GuildID)
if err != nil {
return nil, err
}
for slot := range uint64(2) {
v := guild.Supporters[accountPrefix(self.AccountID)+numberKey(slot)]
b := wire.AppendVarint(nil, 1, v.CostumeID)
b = wire.AppendVarint(b, 2, v.CostumeLevel)
b = wire.AppendVarint(b, 3, v.CostumeDesignID)
out = wire.AppendBytes(out, 3, b)
}
}
var claims uint64
if _, err := load(tx, supporterClaimsBucket, numberKey(self.OwnerIndex)+":"+day, &claims); err != nil {
return nil, err
}
return wire.AppendVarint(out, 4, claims), nil
}
if path == "/SupporterBattleInfo" {
mode, err := p.integer(2)
if err != nil {
return nil, err
}
allowed := (content == 0 || content == 1 || content == 5 || content == 6 || content == 1000) && (mode >= 1 && mode <= 5 || mode >= 9 && mode <= 15 || mode == 17)
selection := supporterSelection{Content: content, Allowed: allowed}
if err := save(tx, "friend.supporter_selection", accountPrefix(self.AccountID)+session, selection); err != nil {
return nil, err
}
if !allowed {
return nil, nil
}
var out []byte
count := uint64(0)
for cursor := ""; ; {
rows, err := tx.Scan("friend.directory", "", cursor, 256)
if err != nil {
return nil, err
}
if len(rows) == 0 {
break
}
for _, row := range rows {
cursor = row.Key
var v FriendProfile
if err := json.Unmarshal(row.Value, &v); err != nil {
return nil, err
}
if v.OwnerIndex == self.OwnerIndex || len(v.SupporterDetails) == 0 {
continue
}
friends, err := supporterRelation(tx, self.OwnerIndex, v.OwnerIndex)
if err != nil {
return nil, err
}
field := 1
if !friends {
if count >= f.rules.Recommended {
continue
}
field = 2
count++
}
deck, err := supporterDeck(tx, v, self.OwnerIndex, day, content)
if err != nil {
return nil, err
}
out = wire.AppendBytes(out, field, deck)
}
}
return out, nil
}
var selection supporterSelection
found, err := load(tx, "friend.supporter_selection", accountPrefix(self.AccountID)+session, &selection)
if err != nil {
return nil, err
}
if !found || !selection.Allowed || selection.Content != content {
return nil, friendError(437, 9003, "Supporter selection is unavailable for this content")
}
lender, err := p.integer(2)
if err != nil || lender == 0 || lender == self.OwnerIndex {
return nil, ErrInvalid
}
slot, err := p.integer(3)
if err != nil || slot > 1 {
return nil, ErrInvalid
}
var other FriendProfile
found, err = load(tx, "friend.directory", numberKey(lender), &other)
if err != nil {
return nil, err
}
if !found {
return nil, friendError(437, 9003, "Player not found")
}
row, found, err := wire.Bytes(other.SupporterDetails[slot], 1)
if err != nil || !found {
return nil, friendError(437, 9003, "Supporter slot is unavailable")
}
bundle, found, err := wire.Bytes(row, 6)
if err != nil || !found {
return nil, ErrInvalid
}
char, err := base64.StdEncoding.DecodeString(string(bundle))
if err != nil {
return nil, err
}
friends, err := supporterRelation(tx, self.OwnerIndex, lender)
if err != nil {
return nil, err
}
limit := f.supporters.DailyRecommendedUses
kind := uint64(0)
if friends {
limit = f.supporters.DailyUses
kind = 1
}
useKey := supporterUseKey(self.OwnerIndex, lender, day, content)
var count uint64
if _, err := load(tx, "friend.supporter_uses", useKey, &count); err != nil {
return nil, err
}
if count >= limit {
return nil, friendError(437, 9003, "Daily supporter uses exhausted")
}
if err := save(tx, "friend.supporter_uses", useKey, count+1); err != nil {
return nil, err
}
var id uint64
if _, err := load(tx, "friend.supporter_sequence", "id", &id); err != nil {
return nil, err
}
if id >= math.MaxInt64 {
return nil, ErrCapacity
}
id++
if err := save(tx, "friend.supporter_sequence", "id", id); err != nil {
return nil, err
}
costume, _, err := wire.Varint(row, 3)
if err != nil {
return nil, err
}
design := uint64(0)
if int(slot) < len(other.Snapshot.Supporters) {
design = other.Snapshot.Supporters[slot].DesignID
}
usage := supporterUsage{ID: id, Owner: lender, Slot: slot, Costume: costume, Design: design, BorrowType: kind, Borrower: self, AtMS: now}
accrualKey := numberKey(lender) + ":" + day
var accrued uint64
if _, err := load(tx, "friend.supporter_accruals", accrualKey, &accrued); err != nil {
return nil, err
}
if accrued < f.supporters.DailyRewardClaims {
usage.RewardEligible = true
if err := save(tx, "friend.supporter_accruals", accrualKey, accrued+1); err != nil {
return nil, err
}
}
// Rental history retains the public identity at use time, without a copy of the player's roster.
usage.Borrower.SupporterDetails = nil
usage.Borrower.Snapshot.Supporters = nil
if err := save(tx, supporterHistoryBucket, supporterHistoryKey(lender, id), usage); err != nil {
return nil, err
}
if err := addGameplayCount(tx, self.OwnerIndex, 1, 0); err != nil {
return nil, err
}
deck, err := supporterDeck(tx, other, self.OwnerIndex, day, content)
if err != nil {
return nil, err
}
out := wire.AppendBytes(nil, 1, deck)
var relation FriendRelation
if _, err := load(tx, "friend.relations", friendKey(self.OwnerIndex, lender), &relation); err != nil {
return nil, err
}
if !friends && relation.From == 0 {
out = wire.AppendVarint(out, 2, 1)
}
return wire.AppendBytes(out, 3, char), nil
}
+69 -12
View File
@@ -3,7 +3,9 @@ package social
import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/profile"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/protocol/wire"
"context"
"crypto/sha256"
@@ -13,11 +15,11 @@ import (
"time"
)
var friendCodes = map[string]int{"/FriendInfoList": 204, "/FriendSend": 205, "/FriendAccept": 206, "/FriendRefuse": 207, "/FriendRemove": 208, "/FriendSendList": 209, "/FriendReceiveList": 210, "/FriendRecommend": 211, "/FriendSearch": 212, "/FriendSendRemove": 213}
var friendCodes = map[string]int{"/FriendInfoList": 204, "/FriendSend": 205, "/FriendAccept": 206, "/FriendRefuse": 207, "/FriendRemove": 208, "/FriendSendList": 209, "/FriendReceiveList": 210, "/FriendRecommend": 211, "/FriendSearch": 212, "/FriendSendRemove": 213, "/LikeUser": 203, "/MyLikeInfo": 218, "/SupporterBattleInfo": 439, "/SupporterBorrow": 437, "/SupporterStatus": 438, "/MyRoomUserInfo": 228, "/MyRoomSearchFriend": 230, "/MyRoomSearchRecommend": 231, "/MyRoomSearchGuild": 424, "/MyRoomLike": 420, "/MyRoomShareOptionUpdate": 645, "/MyRoomSave": 229, "/MyRoomNameChange": 234, "/MyRoomPrimaryChange": 235, "/MyRoomMove": 419, "/MyRoomItemInfo": 232, "/MyRoomPresetInfo": 641, "/MyRoomPresetSave": 642, "/MyRoomPresetNameChange": 643, "/MyRoomPresetDelete": 644}
func OwnsFriend(path string) bool { _, found := friendCodes[path]; return found }
func FriendMutates(path string) bool {
return path == "/FriendSend" || path == "/FriendAccept" || path == "/FriendRefuse" || path == "/FriendRemove" || path == "/FriendSendRemove"
return roomMutates(path) || path == "/SupporterBattleInfo" || path == "/LikeUser" || path == "/SupporterBorrow" || path == "/FriendSend" || path == "/FriendAccept" || path == "/FriendRefuse" || path == "/FriendRemove" || path == "/FriendSendRemove"
}
type FriendProfile struct {
@@ -26,6 +28,9 @@ type FriendProfile struct {
Version uint64
LastLoginMS int64
Snapshot profile.Snapshot
RoomIDs []uint64
RoomItems []inventory.Item
RoomCostumes []roster.Costume
SupporterDetails map[uint64][]byte
}
@@ -40,16 +45,21 @@ type friendReceipt struct {
Response []byte
}
type Friends struct {
store Store
rules gamedata.FriendRules
now func() time.Time
store Store
rules gamedata.FriendRules
now func() time.Time
rooms *gamedata.RoomDesign
supporters gamedata.SupporterRules
}
func NewFriends(store Store, rules gamedata.FriendRules) (*Friends, error) {
func NewFriends(store Store, rules gamedata.FriendRules, supporters gamedata.SupporterRules, rooms *gamedata.RoomDesign, now func() time.Time) (*Friends, error) {
if store == nil || rules.Friends == 0 || rules.Sent == 0 || rules.Received == 0 || rules.Recommended == 0 || rules.ExpireDays == 0 {
return nil, ErrInvalid
}
return &Friends{store: store, rules: rules, now: time.Now}, nil
if now == nil {
now = time.Now
}
return &Friends{store: store, rules: rules, supporters: supporters, rooms: rooms, now: now}, nil
}
func (f *Friends) Publish(ctx context.Context, p FriendProfile) error {
@@ -68,6 +78,11 @@ func (f *Friends) Publish(ctx context.Context, p FriendProfile) error {
if found && old.Version >= p.Version {
return nil
}
if f.rooms != nil {
if err := f.ensureRooms(tx, p); err != nil {
return err
}
}
return save(tx, "friend.directory", numberKey(p.OwnerIndex), p)
})
}
@@ -81,7 +96,15 @@ func (f *Friends) Profile(ctx context.Context, owner uint64) (FriendProfile, err
if !found {
return ErrNotFound
}
return nil
if _, err = load(tx, "friend.like_counts", numberKey(owner), &out.Snapshot.LikeCount); err != nil {
return err
}
row, err := friendWire(tx, out, 0)
if err != nil {
return err
}
out.Snapshot.GuildBase, _, err = wire.Bytes(row, 7)
return err
})
return out, err
}
@@ -193,7 +216,7 @@ func friendError(code, kind int, message string) error {
return &command.GameError{PacketCode: code, ErrorType: kind, Message: message}
}
func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner uint64, path string, raw []byte) (int, []byte, error) {
func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner uint64, path string, raw []byte, contentType uint64) (int, []byte, error) {
code, known := friendCodes[path]
if !known {
return 0, nil, ErrInvalid
@@ -206,9 +229,12 @@ func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner
if err != nil || seq == 0 || seq > math.MaxInt32 {
return code, nil, ErrInvalid
}
target, err := p.integer(2)
if err != nil {
return code, nil, err
var target uint64
if !roomOwns(path) {
target, err = p.integer(2)
if err != nil {
return code, nil, err
}
}
if path == "/FriendInfoList" && target > 1 {
return code, nil, ErrInvalid
@@ -248,6 +274,37 @@ func (f *Friends) Execute(ctx context.Context, identity command.Identity, owner
}
}
now := f.now().UnixMilli()
if roomOwns(path) {
response, err = f.room(tx, self, path, p, now)
if err != nil {
return err
}
if FriendMutates(path) {
return save(tx, "friend.receipts", id, friendReceipt{Digest: digest, Code: code, Response: response})
}
return nil
}
if path == "/LikeUser" || path == "/MyLikeInfo" {
response, err = f.like(tx, owner, target, path, now)
if err != nil {
return err
}
if FriendMutates(path) {
return save(tx, "friend.receipts", id, friendReceipt{Digest: digest, Code: code, Response: response})
}
return nil
}
if path == "/SupporterBattleInfo" || path == "/SupporterBorrow" || path == "/SupporterStatus" {
response, err = f.supporter(tx, self, path, p, now, identity.SessionID, contentType)
if err != nil {
return err
}
if FriendMutates(path) {
return save(tx, "friend.receipts", id, friendReceipt{Digest: digest, Code: code, Response: response})
}
return nil
}
edges, err := friendEdges(tx, owner, now, f.rules.ExpireDays)
if err != nil {
return err
@@ -0,0 +1,48 @@
package social
import (
"context"
"math"
)
type GameplayCounts struct{ BorrowCount, RentalClaims, RoomLikes uint64 }
func addGameplayCount(tx Tx, owner uint64, borrow, claims uint64) error {
var count GameplayCounts
if _, err := load(tx, "friend.gameplay_counts", numberKey(owner), &count); err != nil {
return err
}
if borrow > math.MaxInt64-count.BorrowCount || claims > math.MaxInt64-count.RentalClaims {
return ErrCapacity
}
count.BorrowCount += borrow
count.RentalClaims += claims
return save(tx, "friend.gameplay_counts", numberKey(owner), count)
}
func (f *Friends) GameplayCounts(ctx context.Context, account string, owner uint64) (GameplayCounts, error) {
var count GameplayCounts
err := f.store.View(ctx, func(tx Tx) error {
var p FriendProfile
found, err := load(tx, "friend.directory", numberKey(owner), &p)
if err != nil {
return err
}
if !found {
return nil
}
if p.AccountID != account {
return ErrPermission
}
if _, err := load(tx, "friend.gameplay_counts", numberKey(owner), &count); err != nil {
return err
}
var likes roomLikes
if _, err := load(tx, "friend.room_like_counts", numberKey(owner), &likes); err != nil {
return err
}
count.RoomLikes = likes.Total
return nil
})
return count, err
}
+70
View File
@@ -0,0 +1,70 @@
package social
import (
"context"
"math"
"time"
"bd2server/internal/server/protocol/wire"
)
type dailyLike struct {
Day string
Target uint64
}
func socialDay(stamp int64) string { return time.UnixMilli(stamp).UTC().Format("2006-01-02") }
func (f *Friends) like(tx Tx, owner, target uint64, path string, now int64) ([]byte, error) {
var current dailyLike
if _, err := load(tx, "friend.daily_likes", numberKey(owner), &current); err != nil {
return nil, err
}
day := socialDay(now)
if path == "/MyLikeInfo" {
if current.Day == day {
return wire.AppendVarint(nil, 1, current.Target), nil
}
return nil, nil
}
if target == 0 || target == owner || target > math.MaxInt64 {
return nil, friendError(203, 9003, "Invalid like target")
}
var other FriendProfile
found, err := load(tx, "friend.directory", numberKey(target), &other)
if err != nil {
return nil, err
}
if !found {
return nil, friendError(203, 9003, "Player not found")
}
if current.Day == day {
return nil, friendError(203, 9003, "Daily like already used")
}
var count uint64
if _, err := load(tx, "friend.like_counts", numberKey(target), &count); err != nil {
return nil, err
}
if count >= math.MaxInt32 {
return nil, ErrCapacity
}
if err := save(tx, "friend.like_counts", numberKey(target), count+1); err != nil {
return nil, err
}
return nil, save(tx, "friend.daily_likes", numberKey(owner), dailyLike{Day: day, Target: target})
}
func (f *Friends) LikeCount(ctx context.Context, owner uint64) (uint64, error) {
var count uint64
err := f.store.View(ctx, func(tx Tx) error { _, err := load(tx, "friend.like_counts", numberKey(owner), &count); return err })
return count, err
}
func (f *Friends) IsFriend(ctx context.Context, owner, target uint64) (bool, error) {
var relation FriendRelation
err := f.store.View(ctx, func(tx Tx) error {
_, err := load(tx, "friend.relations", friendKey(owner, target), &relation)
return err
})
return relation.Accepted, err
}
+10 -1
View File
@@ -261,7 +261,12 @@ func (o *Owner) Prepare(ctx context.Context, op Operation) (Reservation, error)
}
r := Reservation{ID: op.ID, Kind: op.Kind, ActorAccount: op.Actor.AccountID, SubjectAccount: subject, Digest: digest, RequestDigest: op.RequestDigest, Status: Prepared, GuildID: op.GuildID, MembershipEpoch: a.Epoch, PreparedMS: op.AtMS, Raid: op.Raid}
var g Guild
if op.Kind == Acknowledge || op.Kind == RaidClaim {
if op.Kind == SupporterClaim {
r.GuildID = 0
if e := o.prepareSupporterClaim(tx, op, &r); e != nil {
return e
}
} else if op.Kind == Acknowledge || op.Kind == RaidClaim {
if op.Kind == RaidClaim {
r.GuildID = 0
for after := ""; ; {
@@ -611,6 +616,10 @@ func (o *Owner) Confirm(ctx context.Context, proof CommitProof) (Reservation, er
}
}
switch r.Kind {
case SupporterClaim:
if err := o.confirmSupporterClaim(tx, op); err != nil {
return err
}
case RaidClaim:
for _, key := range r.EntitlementIDs {
var ent Entitlement
@@ -23,6 +23,7 @@ import (
)
var packetCodes = map[string]int{
"/SupporterReward": 442,
// These current request callbacks ignore the success packet code; the client enum has no corresponding entries.
"/GuildRaidSeasonRanking": 0, "/GuildRaidPresetDelete": 0, "/GuildRaidPresetInfoChange": 0,
"/GuildRaidMainInfo": 291, "/GuildRaidBossBattleInfo": 293, "/GuildRaidBossQuickBattle": 294, "/GuildRaidMemberRanking": 309, "/GuildRaidSeasonReward": 310, "/GuildRaidDeckInfo": 312, "/GuildRaidDeckSave": 313, "/GuildRaidBossBattleEnter": 316, "/GuildRaidBossBattleHistory": 339, "/GuildRaidMemberPlayHistoryInfo": 375, "/GuildRaidPresetSlotAdd": 399, "/GuildRaidPresetInfo": 403, "/GuildRaidPresetSave": 404, "/GuildRaidPresetUse": 411, "/GuildRaidBossPracticeBattleEnter": 453,
@@ -40,7 +41,7 @@ func Mutates(path string) bool {
}
}
switch path {
case "/GuildInfo", "/GuildCreate", "/GuildLeave", "/GuildJoin", "/GuildAccept", "/GuildJoinRefuse", "/GuildMemberBan", "/GuildMemberRoleEdit", "/GuildInfoEdit", "/GuildJoinSendCancel", "/GuildDeleteCancel", "/GuildSupporterAdd", "/GuildSupporterDelete", "/GuildUpdateActionInfo", "/GuildNoticeUpdate", "/GuildNameChange":
case "/SupporterReward", "/GuildInfo", "/GuildCreate", "/GuildLeave", "/GuildJoin", "/GuildAccept", "/GuildJoinRefuse", "/GuildMemberBan", "/GuildMemberRoleEdit", "/GuildInfoEdit", "/GuildJoinSendCancel", "/GuildDeleteCancel", "/GuildSupporterAdd", "/GuildSupporterDelete", "/GuildUpdateActionInfo", "/GuildNoticeUpdate", "/GuildNameChange":
return true
}
return false
@@ -246,6 +247,13 @@ func (s *Service) Prepare(ctx context.Context, identity command.Identity, path s
}
}
switch path {
case "/SupporterReward":
op.Kind = SupporterClaim
op.GuildID = 0
op.UsageIDs, e = p.integers(2)
if e != nil {
return fail(e)
}
case "/GuildInfo":
target, e := p.integer(2)
if e != nil {
@@ -473,7 +481,7 @@ func (s *Service) Apply(ctx command.Context, plan *Plan) (int, []byte, error) {
}
}
if len(r.Grants) > 0 {
if r.Kind == RaidClaim {
if r.Kind == RaidClaim || r.Kind == SupporterClaim {
if s.config.RewardBundle == nil {
return plan.Code, nil, ErrInvalid
}
@@ -481,7 +489,11 @@ func (s *Service) Apply(ctx command.Context, plan *Plan) (int, []byte, error) {
if e != nil {
return plan.Code, nil, e
}
plan.Response = wire.AppendVarint(wire.AppendBytes(nil, 1, bundle), 2, 1)
if r.Kind == SupporterClaim {
plan.Response = wire.AppendBytes(plan.Response, 2, bundle)
} else {
plan.Response = wire.AppendVarint(wire.AppendBytes(nil, 1, bundle), 2, 1)
}
} else if e := s.config.Grant(ctx, r.ID, r.Grants); e != nil {
return plan.Code, nil, e
}
@@ -540,6 +552,13 @@ func (s *Service) Cancel(ctx context.Context, plan *Plan) error {
}
func (s *Service) mutationResponse(ctx context.Context, path string, r Reservation, p packet) ([]byte, error) {
if r.Kind == SupporterClaim {
var out []byte
for _, id := range r.UsageIDs {
out = wire.AppendVarint(out, 1, id)
}
return out, nil
}
if r.View == nil {
if r.Kind == Acknowledge {
return nil, nil
@@ -0,0 +1,248 @@
package social
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"slices"
"sort"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
type RoomEconomy interface {
Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
NativePurchaseCosts(command.Context, gamedata.Reward) ([]gamedata.Reward, error)
}
type RoomCommerce struct {
Design *gamedata.RoomCommerceDesign
Rooms *gamedata.RoomDesign
Economy RoomEconomy
}
type roomCommerceState struct {
Rooms []uint64
Bought map[uint64]uint64
}
type roomCommerceReceipt struct {
Digest string
Body []byte
}
func roomCommerceLoad(ctx command.Context) (roomCommerceState, error) {
s := roomCommerceState{Bought: map[uint64]uint64{}}
raw, found, err := ctx.State.LoadEntry("social", "room_commerce", "core")
if err != nil || !found {
return s, err
}
if err := json.Unmarshal(raw, &s); err != nil {
return s, err
}
if s.Bought == nil {
return s, ErrInvalid
}
return s, nil
}
func (s RoomCommerce) OwnedRooms(ctx command.Context) ([]uint64, error) {
state, err := roomCommerceLoad(ctx)
return slices.Clone(state.Rooms), err
}
func (s RoomCommerce) Handle(ctx command.Context, path string, raw []byte) (int, []byte, bool, error) {
codes := map[string]int{"/MyRoomShopInfo": 245, "/MyRoomShopBuy": 246, "/MyRoomShopMultiBuy": 646, "/MyRoomExpand": 418}
code, found := codes[path]
if !found {
return 0, nil, false, nil
}
fail := func(err error) (int, []byte, bool, error) {
return code, nil, true, friendError(code, 9003, err.Error())
}
if s.Design == nil || s.Rooms == nil || s.Economy == nil {
return fail(ErrInvalid)
}
p, err := parsePacket(raw)
if err != nil {
return fail(err)
}
seq, err := p.integer(1)
if err != nil || seq == 0 {
return fail(ErrInvalid)
}
state, err := roomCommerceLoad(ctx)
if err != nil {
return code, nil, true, err
}
if path == "/MyRoomShopInfo" {
keys := make([]uint64, 0, len(state.Bought))
for key := range state.Bought {
keys = append(keys, key)
}
slices.Sort(keys)
var out []byte
for _, key := range keys {
row := wire.AppendVarint(nil, 1, key)
row = wire.AppendVarint(row, 2, state.Bought[key])
out = wire.AppendBytes(out, 1, row)
}
return code, out, true, nil
}
key := ctx.SessionID + "/" + ctx.RequestID
if ctx.RequestID == "" {
key = fmt.Sprintf("%s/%s/%d", ctx.SessionID, path, seq)
}
digest := sha256.Sum256(append([]byte(path), raw...))
if saved, found, err := ctx.State.LoadEntry("social", "room_commerce_replies", key); err != nil {
return code, nil, true, err
} else if found {
var r roomCommerceReceipt
if err := json.Unmarshal(saved, &r); err != nil {
return code, nil, true, err
}
if r.Digest != hex.EncodeToString(digest[:]) {
return fail(ErrConflict)
}
return code, r.Body, true, nil
}
var costs, rewards []gamedata.Reward
var room uint64
if path == "/MyRoomExpand" {
room, err = p.integer(2)
if err != nil {
return fail(err)
}
cost, known := s.Design.Expansion[room]
owned := append(slices.Clone(s.Rooms.Defaults), state.Rooms...)
slices.Sort(owned)
if !known || slices.Contains(owned, room) || len(owned) == 0 || room != owned[len(owned)-1]+1 {
return fail(ErrIneligible)
}
if err := roomPayment(p, 3, []gamedata.Reward{cost}, 1, &costs); err != nil {
return fail(err)
}
state.Rooms = append(state.Rooms, room)
} else {
rows := []packet{p}
idField, countField, paymentField := 2, 3, 4
if path == "/MyRoomShopMultiBuy" {
rows = nil
idField, countField, paymentField = 1, 2, 3
if len(p[2]) == 0 || len(p[2]) > 256 {
return fail(ErrInvalid)
}
for _, f := range p[2] {
if f.Type != 2 {
return fail(ErrInvalid)
}
row, err := parsePacket(f.Value)
if err != nil {
return fail(err)
}
rows = append(rows, row)
}
}
seen := map[uint64]bool{}
for _, row := range rows {
id, err := row.integer(idField)
if err != nil {
return fail(err)
}
n, err := row.integer(countField)
if err != nil {
return fail(err)
}
product, known := s.Design.Products[id]
if !known || n == 0 || seen[id] || n > product.Limit || state.Bought[id] > product.Limit-n {
return fail(ErrCapacity)
}
seen[id] = true
if err := roomPayment(row, paymentField, product.Prices, n, &costs); err != nil {
return fail(err)
}
if product.Reward.Count > math.MaxInt32/n {
return fail(ErrCapacity)
}
reward := product.Reward
reward.Count *= n
rewards = append(rewards, reward)
state.Bought[id] += n
}
}
merged := map[[2]uint64]uint64{}
for _, cost := range costs {
merged[[2]uint64{cost.Type, cost.ID}] += cost.Count
}
costs = nil
for key, n := range merged {
resolved, err := s.Economy.NativePurchaseCosts(ctx, gamedata.Reward{Type: key[0], ID: key[1], Count: n})
if err != nil {
return fail(err)
}
costs = append(costs, resolved...)
}
sort.Slice(costs, func(i, j int) bool {
if costs[i].Type != costs[j].Type {
return costs[i].Type < costs[j].Type
}
return costs[i].ID < costs[j].ID
})
bundle, err := s.Economy.Apply(ctx, "room-commerce:"+key, costs, rewards)
if err != nil {
return fail(err)
}
out := wire.AppendBytes(nil, 1, bundle)
if room != 0 {
out = wire.AppendBytes(out, 2, wire.AppendVarint(nil, 1, room))
}
stateRaw, err := json.Marshal(state)
if err != nil {
return code, nil, true, err
}
if err := ctx.State.PutEntry("social", "room_commerce", "core", stateRaw); err != nil {
return code, nil, true, err
}
receipt, err := json.Marshal(roomCommerceReceipt{Digest: hex.EncodeToString(digest[:]), Body: out})
if err != nil {
return code, nil, true, err
}
return code, out, true, ctx.State.PutEntry("social", "room_commerce_replies", key, receipt)
}
func roomPayment(p packet, field int, prices []gamedata.Reward, count uint64, out *[]gamedata.Reward) error {
if len(p[field]) != 1 || p[field][0].Type != 2 {
return ErrInvalid
}
item, err := parsePacket(p[field][0].Value)
if err != nil {
return err
}
typ, err := item.integer(3)
if err != nil {
return err
}
id, err := item.integer(2)
if err != nil {
return err
}
n, err := item.integer(4)
if err != nil {
return err
}
for _, price := range prices {
if price.Count > math.MaxInt32/count {
return ErrCapacity
}
if price.Type == typ && price.ID == id && price.Count*count == n {
price.Count = n
*out = append(*out, price)
return nil
}
}
return ErrInvalid
}
@@ -0,0 +1,341 @@
package social
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"math"
"unicode/utf8"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
)
func (f *Friends) PrepareRoomText(ctx context.Context, identity command.Identity, path string, raw []byte, check func(string) error) error {
if path != "/MyRoomNameChange" && path != "/MyRoomSave" && path != "/MyRoomPresetSave" && path != "/MyRoomPresetNameChange" {
return nil
}
key, err := json.Marshal(identity)
if err != nil {
return err
}
receiptKey := sha256.Sum256(key)
var prior friendReceipt
found := false
if err := f.store.View(ctx, func(tx Tx) error {
var err error
found, err = load(tx, "friend.receipts", hex.EncodeToString(receiptKey[:]), &prior)
return err
}); err != nil {
return err
}
p, err := parsePacket(raw)
if err != nil {
return err
}
seq, err := p.integer(1)
if err != nil {
return err
}
_, digest := requestIdentity(identity, path, seq, raw)
if found {
if prior.Digest != digest {
return ErrConflict
}
return nil
}
var texts []string
switch path {
case "/MyRoomNameChange":
text, err := p.text(3)
if err != nil {
return err
}
texts = append(texts, text)
case "/MyRoomPresetSave", "/MyRoomPresetNameChange":
texts, err = f.presetText(p, path)
if err != nil {
return err
}
default:
for _, row := range p[2] {
if row.Type != 2 {
return ErrInvalid
}
p, err := parsePacket(row.Value)
if err != nil {
return err
}
text, err := p.text(2)
if err != nil {
return err
}
texts = append(texts, text)
}
}
for _, text := range texts {
if !validRoomName(text) {
return friendError(friendCodes[path], 9003, "Invalid room name")
}
if text != "" {
if err := check(text); err != nil {
return err
}
}
}
return nil
}
func validRoomName(name string) bool {
return utf8.ValidString(name) && utf8.RuneCountInString(name) <= 20 && !stringsContainControl(name)
}
func stringsContainControl(s string) bool {
for _, r := range s {
if r < 32 || r == 127 {
return true
}
}
return false
}
func (f *Friends) editRooms(state *personalRooms, self FriendProfile, path string, p packet) error {
if path == "/MyRoomShareOptionUpdate" {
scope, err := p.integer(2)
if err != nil || scope > 4 {
return ErrInvalid
}
state.Scope = scope
return nil
}
if path == "/MyRoomSave" {
if len(p[2]) == 0 || len(p[2]) > len(state.Rooms) {
return ErrInvalid
}
seen := map[uint64]bool{}
for _, field := range p[2] {
if field.Type != 2 {
return ErrInvalid
}
row, err := parsePacket(field.Value)
if err != nil {
return err
}
id, err := row.integer(1)
if err != nil || id == 0 || seen[id] {
return ErrInvalid
}
seen[id] = true
index := -1
for i, v := range state.Rooms {
if v.ID == id {
index = i
break
}
}
if index < 0 {
return ErrPermission
}
name, err := row.text(2)
if err != nil || !validRoomName(name) {
return ErrInvalid
}
hidden, err := row.integer(4)
if err != nil || hidden > 1 {
return ErrInvalid
}
room := personalRoom{ID: id, Name: name, Hidden: hidden == 1}
for _, position := range row[3] {
if position.Type != 2 {
return ErrInvalid
}
room.Positions = append(room.Positions, append([]byte(nil), position.Value...))
}
if err := f.validatePositions(room, self, f.rooms.Limits[id]); err != nil {
return err
}
state.Rooms[index] = room
}
return validateRoomInventory(*state, self)
}
id, err := p.integer(2)
if err != nil || id == 0 {
return ErrInvalid
}
index := -1
for i, room := range state.Rooms {
if room.ID == id {
index = i
break
}
}
if index < 0 {
return ErrPermission
}
switch path {
case "/MyRoomNameChange":
name, err := p.text(3)
if err != nil || !validRoomName(name) {
return ErrInvalid
}
state.Rooms[index].Name = name
case "/MyRoomPrimaryChange":
if state.Rooms[index].Hidden {
return ErrIneligible
}
state.Primary = id
case "/MyRoomMove":
target, err := p.integer(3)
if err != nil || target == 0 {
return ErrInvalid
}
other := -1
for i, v := range state.Rooms {
if v.ID == target {
other = i
break
}
}
if other < 0 {
return ErrPermission
}
state.Rooms[index], state.Rooms[other] = state.Rooms[other], state.Rooms[index]
state.Rooms[index].ID = id
state.Rooms[other].ID = target
if err := f.validatePositions(state.Rooms[index], self, f.rooms.Limits[id]); err != nil {
return err
}
if err := f.validatePositions(state.Rooms[other], self, f.rooms.Limits[target]); err != nil {
return err
}
default:
return ErrInvalid
}
return nil
}
func validateRoomInventory(state personalRooms, self FriendProfile) error {
used := map[uint64]uint64{}
for _, room := range state.Rooms {
for _, position := range room.Positions {
index, _, err := wire.Varint(position, 1)
if err != nil {
return err
}
typ, _, err := wire.Varint(position, 2)
if err != nil {
return err
}
used[index]++
if typ == 1 {
if used[index] > 1 {
return ErrPermission
}
continue
}
var count uint64
for _, item := range self.RoomItems {
if item.InvenIndex == index {
count = item.Count
break
}
}
if used[index] > count {
return ErrPermission
}
}
}
return nil
}
func (f *Friends) validatePositions(room personalRoom, self FriendProfile, limits gamedata.RoomLimits) error {
if len(room.Positions) > 256 {
return ErrCapacity
}
var objects, carpets, characters uint64
used := map[string]uint64{}
for _, raw := range room.Positions {
p, err := parsePacket(raw)
if err != nil {
return err
}
index, err := p.integer(1)
if err != nil || index == 0 {
return ErrInvalid
}
typ, err := p.integer(2)
if err != nil || typ > 2 {
return ErrInvalid
}
position, err := p.integer(3)
if err != nil || position > 3 {
return ErrInvalid
}
for _, field := range []int{4, 5, 6, 7, 8} {
n, err := p.integer(field)
if err != nil || n > math.MaxInt32 {
return ErrInvalid
}
}
wallHidden, err := p.integer(9)
if err != nil || wallHidden > 1 {
return ErrInvalid
}
key := fmt.Sprintf("%d:%d", typ, index)
used[key]++
if typ == 1 {
found := false
for _, costume := range self.RoomCostumes {
if costume.InvenIndex == index {
found = true
break
}
}
if !found || used[key] > 1 {
return ErrPermission
}
characters++
continue
}
var id, count uint64
for _, item := range self.RoomItems {
if item.InvenIndex == index && (typ == 0 && item.Type == 27 || typ == 2 && item.Type == 28) {
id = item.ID
count = item.Count
break
}
}
if id == 0 || used[key] > count {
return ErrPermission
}
if typ == 2 {
objects++
continue
}
item, found := f.rooms.Items[id]
if !found || item.ObjectType != 0 {
return ErrInvalid
}
if item.Location == 0 && position != 1 || item.Location == 1 && position != 2 && position != 3 {
return ErrInvalid
}
switch item.Kind {
case 0:
if used[key] > 2 {
return ErrInvalid
}
case 1:
objects++
case 2:
carpets++
default:
return ErrInvalid
}
}
if objects > limits.Objects || carpets > limits.Carpets || characters > limits.Characters {
return ErrCapacity
}
return nil
}
@@ -0,0 +1,120 @@
package social_test
import (
"context"
"fmt"
"testing"
"time"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/profile"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/protocol/wire"
)
func TestRoomPopularityResetsMonthlyPerViewerWithoutResettingTotal(t *testing.T) {
ctx := context.Background()
store := &memoryStore{rows: map[string]map[string][]byte{}}
now := time.Date(2026, 10, 31, 23, 59, 0, 0, time.UTC)
rooms := &gamedata.RoomDesign{Defaults: []uint64{1}, Limits: map[uint64]gamedata.RoomLimits{1: {Characters: 4}}, ListCount: 10}
friends, err := social.NewFriends(store, gamedata.FriendRules{Friends: 50, Sent: 50, Received: 50, Recommended: 10, ExpireDays: 7}, gamedata.SupporterRules{}, rooms, func() time.Time { return now })
if err != nil {
t.Fatal(err)
}
for index := uint64(1); index <= 3; index++ {
if err := friends.Publish(ctx, social.FriendProfile{AccountID: fmt.Sprint(index), OwnerIndex: index, Version: 1, Snapshot: profile.Snapshot{OwnerIndex: index, UserID: fmt.Sprint(index)}}); err != nil {
t.Fatal(err)
}
}
seq := uint64(0)
call := func(actor uint64, path string, fields []byte) ([]byte, error) {
seq++
_, body, err := friends.Execute(ctx, command.Identity{AccountID: fmt.Sprint(actor), SessionID: "room", RequestID: fmt.Sprint(seq)}, actor, path, append(wire.AppendVarint(nil, 1, seq), fields...), 0)
return body, err
}
like := func(actor, target uint64) ([]byte, error) {
return call(actor, "/MyRoomLike", wire.AppendVarint(nil, 2, target))
}
if _, err := like(1, 2); err != nil {
t.Fatal(err)
}
if _, err := like(1, 3); err != nil {
t.Fatal("monthly room allowance was incorrectly global", err)
}
if _, err := like(3, 2); err != nil {
t.Fatal(err)
}
if _, err := like(1, 2); err == nil {
t.Fatal("same viewer could increase popularity twice in a month")
}
popular, err := call(1, "/MyRoomSearchRecommend", wire.AppendVarint(nil, 2, 1))
if err != nil {
t.Fatal(err)
}
var order []uint64
if err := wire.Walk(popular, func(field wire.Field) error {
if field.Number == 1 {
owner, _, err := wire.Varint(field.Value, 1)
order = append(order, owner)
return err
}
return nil
}); err != nil {
t.Fatal(err)
}
if len(order) != 2 || order[0] != 2 || order[1] != 3 {
t.Fatalf("monthly popular order=%v want[2 3]", order)
}
// Current LocalText140304 says monthly popularity resets at09:00KST,
// and140200 says the same user's room may be liked again next month.
now = now.Add(2 * time.Minute)
before, _, err := friends.RoomProfile(ctx, 1, 2)
if err != nil {
t.Fatal(err)
}
last, _, err := wire.Varint(before, 10)
if err != nil || last == 0 {
t.Fatal("viewer history was lost during month rollover")
}
result, err := like(1, 2)
if err != nil {
t.Fatal(err)
}
monthly, _, err := wire.Varint(result, 1)
if err != nil {
t.Fatal(err)
}
total, _, err := wire.Varint(result, 2)
if err != nil {
t.Fatal(err)
}
if monthly != 1 || total != 3 {
t.Fatalf("new month popularity=%d/%d want1/3", monthly, total)
}
count, err := friends.GameplayCounts(ctx, "2", 2)
if err != nil || count.RoomLikes != 3 {
t.Fatalf("actual room achievement popularity=%+v error=%v", count, err)
}
if profileLikes, err := friends.LikeCount(ctx, 2); err != nil || profileLikes != 0 {
t.Fatalf("room popularity contaminated profile likes=%d error=%v", profileLikes, err)
}
if _, err := call(2, "/MyRoomShareOptionUpdate", wire.AppendVarint(nil, 2, 4)); err != nil {
t.Fatal(err)
}
if _, err := like(3, 2); err == nil {
t.Fatal("private room accepted a monthly popularity increase")
}
private, _, err := friends.RoomProfile(ctx, 1, 2)
if err != nil {
t.Fatal(err)
}
if err := wire.Walk(private, func(field wire.Field) error {
if field.Number == 8 {
t.Fatal("private profile projection exposed layout")
}
return nil
}); err != nil {
t.Fatal(err)
}
}
@@ -0,0 +1,301 @@
package social
import (
"bytes"
"bd2server/internal/server/protocol/wire"
)
type roomPreset struct {
Slot uint64
Name string
Items, Rooms [][]byte
}
func roomPresetWire(p roomPreset) []byte {
out := wire.AppendVarint(nil, 1, p.Slot)
out = wire.AppendString(out, 2, p.Name)
for _, item := range p.Items {
out = wire.AppendBytes(out, 3, item)
}
for _, room := range p.Rooms {
out = wire.AppendBytes(out, 4, room)
}
return out
}
func roomPresetKey(owner, kind, slot uint64) string {
return numberKey(owner) + ":" + numberKey(kind) + ":" + numberKey(slot)
}
func (f *Friends) roomPreset(tx Tx, self FriendProfile, path string, p packet) ([]byte, error) {
if path == "/MyRoomPresetInfo" {
var out []byte
for kind := uint64(1); kind <= 2; kind++ {
limit := f.rooms.MyPresets
if kind == 2 {
limit = f.rooms.UserPresets
}
for slot := uint64(1); slot <= limit; slot++ {
var preset roomPreset
found, err := load(tx, "friend.room_presets", roomPresetKey(self.OwnerIndex, kind, slot), &preset)
if err != nil {
return nil, err
}
if found {
out = wire.AppendBytes(out, int(kind), roomPresetWire(preset))
}
}
}
return out, nil
}
kind, err := p.integer(2)
if err != nil {
return nil, err
}
var slot uint64
if path != "/MyRoomPresetSave" {
slot, err = p.integer(3)
if err != nil {
return nil, err
}
}
var preset roomPreset
if path == "/MyRoomPresetSave" {
sourceOwner := kind
kind = 1
if sourceOwner != self.OwnerIndex {
kind = 2
}
if len(p[3]) != 1 || p[3][0].Type != 2 {
return nil, ErrInvalid
}
row, err := parsePacket(p[3][0].Value)
if err != nil {
return nil, err
}
slot, err = row.integer(1)
if err != nil {
return nil, err
}
preset.Slot = slot
preset.Name, err = row.text(2)
if err != nil || !validRoomName(preset.Name) {
return nil, ErrInvalid
}
var source FriendProfile
found, err := load(tx, "friend.directory", numberKey(sourceOwner), &source)
if err != nil {
return nil, err
}
if !found {
return nil, ErrNotFound
}
var state personalRooms
found, err = load(tx, "friend.rooms", numberKey(sourceOwner), &state)
if err != nil {
return nil, err
}
if !found {
return nil, ErrNotFound
}
visible, err := roomVisible(tx, self, source, state)
if err != nil {
return nil, err
}
if !visible {
return nil, ErrPermission
}
if err := f.validateRoomPreset(source, self.OwnerIndex == sourceOwner, state, row, &preset); err != nil {
return nil, err
}
}
if err != nil || kind < 1 || kind > 2 {
return nil, ErrInvalid
}
limit := f.rooms.MyPresets
if kind == 2 {
limit = f.rooms.UserPresets
}
if slot == 0 || slot > limit {
return nil, ErrInvalid
}
key := roomPresetKey(self.OwnerIndex, kind, slot)
if path == "/MyRoomPresetDelete" {
return nil, remove(tx, "friend.room_presets", key)
}
if path == "/MyRoomPresetNameChange" {
found, err := load(tx, "friend.room_presets", key, &preset)
if err != nil {
return nil, err
}
if !found {
return nil, ErrNotFound
}
preset.Name, err = p.text(4)
if err != nil || !validRoomName(preset.Name) {
return nil, ErrInvalid
}
}
return nil, save(tx, "friend.room_presets", key, preset)
}
func (f *Friends) validateRoomPreset(source FriendProfile, own bool, state personalRooms, row packet, result *roomPreset) error {
if len(row[4]) == 0 || len(row[4]) > len(f.rooms.Limits) || len(row[3]) > 256 {
return ErrInvalid
}
items := map[uint64]uint64{}
seen := map[uint64]bool{}
for _, field := range row[3] {
if field.Type != 2 {
return ErrInvalid
}
item, err := parsePacket(field.Value)
if err != nil {
return err
}
index, err := item.integer(1)
if err != nil {
return err
}
id, err := item.integer(2)
if err != nil {
return err
}
count, err := item.integer(4)
if err != nil || count == 0 || seen[index] {
return ErrInvalid
}
seen[index] = true
owned := false
for _, v := range source.RoomItems {
if v.Type == 27 && v.InvenIndex == index && v.ID == id && v.Count >= count {
owned = true
break
}
}
if !owned {
return ErrPermission
}
items[index] = count
out := wire.AppendVarint(nil, 1, index)
out = wire.AppendVarint(out, 2, id)
out = wire.AppendVarint(out, 4, count)
result.Items = append(result.Items, out)
}
roomIDs := map[uint64]bool{}
used := map[uint64]uint64{}
for _, field := range row[4] {
if field.Type != 2 {
return ErrInvalid
}
room, err := parsePacket(field.Value)
if err != nil {
return err
}
id, err := room.integer(1)
if err != nil || roomIDs[id] {
return ErrInvalid
}
roomIDs[id] = true
limits, found := f.rooms.Limits[id]
if !found {
return ErrInvalid
}
hidden, err := room.integer(4)
if err != nil || hidden > 1 {
return ErrInvalid
}
name, err := room.text(2)
if err != nil || !validRoomName(name) {
return ErrInvalid
}
v := personalRoom{ID: id, Name: name, Hidden: hidden == 1}
var original *personalRoom
for _, r := range state.Rooms {
if r.ID == id {
copy := r
original = &copy
break
}
}
if hidden == 0 && (original == nil || original.Hidden && !own) {
return ErrPermission
}
if hidden == 1 && len(room[3]) > 0 {
return ErrInvalid
}
for _, position := range room[3] {
if position.Type != 2 {
return ErrInvalid
}
p, err := parsePacket(position.Value)
if err != nil {
return err
}
typ, err := p.integer(2)
if err != nil || typ != 0 {
return ErrInvalid
}
index, err := p.integer(1)
if err != nil {
return err
}
used[index]++
if used[index] > items[index] {
return ErrPermission
}
if !own {
matched := false
for _, raw := range original.Positions {
if bytes.Equal(raw, position.Value) {
matched = true
break
}
}
if !matched {
return ErrPermission
}
}
v.Positions = append(v.Positions, append([]byte(nil), position.Value...))
}
if err := f.validatePositions(v, source, limits); err != nil {
return err
}
result.Rooms = append(result.Rooms, roomWire(v))
}
return nil
}
func (f *Friends) presetText(p packet, path string) ([]string, error) {
if path == "/MyRoomPresetNameChange" {
name, err := p.text(4)
return []string{name}, err
}
if len(p[3]) != 1 || p[3][0].Type != 2 {
return nil, ErrInvalid
}
row, err := parsePacket(p[3][0].Value)
if err != nil {
return nil, err
}
name, err := row.text(2)
if err != nil {
return nil, err
}
texts := []string{name}
for _, room := range row[4] {
if room.Type != 2 {
return nil, ErrInvalid
}
p, err := parsePacket(room.Value)
if err != nil {
return nil, err
}
name, err := p.text(2)
if err != nil {
return nil, err
}
texts = append(texts, name)
}
return texts, nil
}
@@ -0,0 +1,134 @@
package social
import (
"encoding/json"
"math/rand/v2"
"slices"
"time"
"bd2server/internal/server/protocol/wire"
)
func (f *Friends) searchRooms(tx Tx, self FriendProfile, path string, p packet, now int64) ([]byte, error) {
typ := uint64(0)
if path == "/MyRoomSearchRecommend" {
var err error
typ, err = p.integer(2)
if err != nil || typ > 1 {
return nil, ErrInvalid
}
}
selfAccount, err := readAccount(tx, self.AccountID)
if err != nil {
return nil, err
}
type candidate struct {
info []byte
owner, likes uint64
}
var candidates []candidate
month := time.UnixMilli(now).UTC().Format("2006-01")
for cursor := ""; ; {
rows, err := tx.Scan("friend.directory", "", cursor, 256)
if err != nil {
return nil, err
}
if len(rows) == 0 {
break
}
for _, row := range rows {
cursor = row.Key
var other FriendProfile
if err := json.Unmarshal(row.Value, &other); err != nil {
return nil, err
}
if other.OwnerIndex == self.OwnerIndex {
continue
}
if path == "/MyRoomSearchFriend" {
yes, err := supporterRelation(tx, self.OwnerIndex, other.OwnerIndex)
if err != nil {
return nil, err
}
if !yes {
continue
}
}
if path == "/MyRoomSearchGuild" {
account, err := readAccount(tx, other.AccountID)
if err != nil {
return nil, err
}
if selfAccount.GuildID == 0 || account.GuildID != selfAccount.GuildID {
continue
}
}
var state personalRooms
found, err := load(tx, "friend.rooms", numberKey(other.OwnerIndex), &state)
if err != nil {
return nil, err
}
if !found {
continue
}
info, err := f.roomUser(tx, self, other, state, true)
if err == ErrPermission {
continue
}
if err != nil {
return nil, err
}
var count roomLikes
if _, err := load(tx, "friend.room_like_counts", numberKey(other.OwnerIndex), &count); err != nil {
return nil, err
}
monthly := uint64(0)
if count.Month == month {
monthly = count.Monthly
}
if path == "/MyRoomSearchRecommend" && typ == 0 {
if count.Total == 0 {
continue
}
populated := false
for _, room := range state.Rooms {
if !room.Hidden && len(room.Positions) > 0 {
populated = true
break
}
}
if !populated {
continue
}
}
candidates = append(candidates, candidate{info: info, owner: other.OwnerIndex, likes: monthly})
}
}
if path == "/MyRoomSearchRecommend" && typ == 1 {
slices.SortFunc(candidates, func(a, b candidate) int {
if a.likes > b.likes {
return -1
}
if a.likes < b.likes {
return 1
}
if a.owner < b.owner {
return -1
}
if a.owner > b.owner {
return 1
}
return 0
})
} else if path == "/MyRoomSearchRecommend" {
rand.Shuffle(len(candidates), func(i, j int) { candidates[i], candidates[j] = candidates[j], candidates[i] })
}
if uint64(len(candidates)) > f.rooms.ListCount {
candidates = candidates[:f.rooms.ListCount]
}
var out []byte
for _, row := range candidates {
out = wire.AppendBytes(out, 1, row.info)
}
return out, nil
}
+317
View File
@@ -0,0 +1,317 @@
package social
import (
"context"
"math"
"slices"
"strings"
"time"
"bd2server/internal/server/domain/inventory"
"bd2server/internal/server/domain/roster"
"bd2server/internal/server/protocol/wire"
)
func (f *Friends) RoomProfile(ctx context.Context, viewer, target uint64) ([]byte, uint64, error) {
var out []byte
var total uint64
err := f.store.View(ctx, func(tx Tx) error {
var self, other FriendProfile
found, err := load(tx, "friend.directory", numberKey(viewer), &self)
if err != nil || !found {
return err
}
found, err = load(tx, "friend.directory", numberKey(target), &other)
if err != nil || !found {
return err
}
var state personalRooms
found, err = load(tx, "friend.rooms", numberKey(target), &state)
if err != nil || !found {
return err
}
var likes roomLikes
if _, err := load(tx, "friend.room_like_counts", numberKey(target), &likes); err != nil {
return err
}
total = likes.Total
out, err = f.roomUser(tx, self, other, state, false)
if err == ErrPermission {
out = wire.AppendVarint(nil, 1, target)
out = wire.AppendString(out, 2, other.Snapshot.UserID)
out = wire.AppendVarint(out, 12, state.Scope)
return nil
}
return err
})
return out, total, err
}
type personalRoom struct {
ID uint64
Name string
Hidden bool
Positions [][]byte
}
type personalRooms struct {
Primary, Scope uint64
Rooms []personalRoom
}
type roomLikes struct {
Month string
Monthly, Total uint64
}
func roomOwns(path string) bool { return strings.HasPrefix(path, "/MyRoom") }
func roomMutates(path string) bool {
switch path {
case "/MyRoomPresetSave", "/MyRoomPresetNameChange", "/MyRoomPresetDelete", "/MyRoomLike", "/MyRoomShareOptionUpdate", "/MyRoomSave", "/MyRoomNameChange", "/MyRoomPrimaryChange", "/MyRoomMove":
return true
}
return false
}
func (f *Friends) ensureRooms(tx Tx, p FriendProfile) error {
var state personalRooms
_, err := load(tx, "friend.rooms", numberKey(p.OwnerIndex), &state)
if err != nil {
return err
}
ids := append(append([]uint64(nil), f.rooms.Defaults...), p.RoomIDs...)
for _, id := range ids {
if _, found := f.rooms.Limits[id]; !found {
return ErrInvalid
}
found := false
for _, room := range state.Rooms {
if room.ID == id {
found = true
break
}
}
if !found {
state.Rooms = append(state.Rooms, personalRoom{ID: id})
}
}
if state.Primary == 0 {
slices.SortFunc(state.Rooms, func(a, b personalRoom) int { return int(a.ID) - int(b.ID) })
state.Primary = state.Rooms[0].ID
}
return save(tx, "friend.rooms", numberKey(p.OwnerIndex), state)
}
func roomVisible(tx Tx, viewer, owner FriendProfile, state personalRooms) (bool, error) {
if viewer.OwnerIndex == owner.OwnerIndex {
return true, nil
}
friend, err := supporterRelation(tx, viewer.OwnerIndex, owner.OwnerIndex)
if err != nil {
return false, err
}
a, err := readAccount(tx, viewer.AccountID)
if err != nil {
return false, err
}
b, err := readAccount(tx, owner.AccountID)
if err != nil {
return false, err
}
guild := a.GuildID != 0 && a.GuildID == b.GuildID
switch state.Scope {
case 0:
return true, nil
case 1:
return friend || guild, nil
case 2:
return friend, nil
case 3:
return guild, nil
case 4:
return false, nil
}
return false, ErrInvalid
}
func roomWire(v personalRoom) []byte {
out := wire.AppendVarint(nil, 1, v.ID)
out = wire.AppendString(out, 2, v.Name)
for _, position := range v.Positions {
out = wire.AppendBytes(out, 3, position)
}
if v.Hidden {
out = wire.AppendVarint(out, 4, 1)
}
return out
}
func (f *Friends) roomUser(tx Tx, viewer, owner FriendProfile, state personalRooms, all bool) ([]byte, error) {
visible, err := roomVisible(tx, viewer, owner, state)
if err != nil {
return nil, err
}
if !visible {
return nil, ErrPermission
}
out := wire.AppendVarint(nil, 1, owner.OwnerIndex)
out = wire.AppendString(out, 2, owner.Snapshot.UserID)
out = wire.AppendVarint(out, 3, owner.Snapshot.PortraitCostumeID)
out = wire.AppendVarint(out, 4, state.Primary)
for _, item := range owner.RoomItems {
switch item.Type {
case 27:
out = wire.AppendBytes(out, 5, inventory.ItemWire(item))
case 28:
v := wire.AppendVarint(nil, 1, item.InvenIndex)
v = wire.AppendVarint(v, 2, item.ID)
out = wire.AppendBytes(out, 7, v)
}
}
for _, costume := range owner.RoomCostumes {
out = wire.AppendBytes(out, 6, roster.CostumeWire(costume))
}
primaryVisible := false
for _, room := range state.Rooms {
if room.Hidden && viewer.OwnerIndex != owner.OwnerIndex {
continue
}
if room.ID == state.Primary {
primaryVisible = true
}
if all || viewer.OwnerIndex == owner.OwnerIndex || room.ID == state.Primary {
out = wire.AppendBytes(out, 8, roomWire(room))
}
}
if !primaryVisible && viewer.OwnerIndex != owner.OwnerIndex {
return nil, ErrPermission
}
var likes roomLikes
if _, err := load(tx, "friend.room_like_counts", numberKey(owner.OwnerIndex), &likes); err != nil {
return nil, err
}
out = wire.AppendVarint(out, 9, likes.Total)
var stamp int64
if _, err := load(tx, "friend.room_likes", friendKeyDirectional(viewer.OwnerIndex, owner.OwnerIndex), &stamp); err != nil {
return nil, err
}
out = wire.AppendVarint(out, 10, uint64(stamp))
out = wire.AppendVarint(out, 11, owner.Snapshot.PortraitDesignID)
return wire.AppendVarint(out, 12, state.Scope), nil
}
func friendKeyDirectional(a, b uint64) string { return numberKey(a) + ":" + numberKey(b) }
func (f *Friends) room(tx Tx, self FriendProfile, path string, p packet, now int64) ([]byte, error) {
if f.rooms == nil {
return nil, ErrInvalid
}
var state personalRooms
found, err := load(tx, "friend.rooms", numberKey(self.OwnerIndex), &state)
if err != nil {
return nil, err
}
if !found {
return nil, ErrNotFound
}
fail := func(message string) ([]byte, error) { return nil, friendError(friendCodes[path], 9003, message) }
if strings.HasPrefix(path, "/MyRoomPreset") {
out, err := f.roomPreset(tx, self, path, p)
if err != nil {
return fail(err.Error())
}
return out, nil
}
if path == "/MyRoomUserInfo" || path == "/MyRoomLike" {
target, err := p.integer(2)
if err != nil || target == 0 {
return fail("Invalid room owner")
}
var other FriendProfile
found, err := load(tx, "friend.directory", numberKey(target), &other)
if err != nil {
return nil, err
}
if !found {
return fail("Player not found")
}
var rooms personalRooms
found, err = load(tx, "friend.rooms", numberKey(target), &rooms)
if err != nil {
return nil, err
}
if !found {
return fail("Player has no rooms")
}
visible, err := roomVisible(tx, self, other, rooms)
if err != nil {
return nil, err
}
if !visible {
return fail("Room is private")
}
if path == "/MyRoomUserInfo" {
all, err := p.integer(3)
if err != nil || all > 1 {
return nil, ErrInvalid
}
out, err := f.roomUser(tx, self, other, rooms, true)
if err != nil {
return fail("Room is unavailable")
}
return wire.AppendBytes(nil, 1, out), nil
}
if target == self.OwnerIndex {
return fail("Cannot like your own room")
}
if _, err := f.roomUser(tx, self, other, rooms, false); err != nil {
return fail("Room is unavailable")
}
month := time.UnixMilli(now).UTC().Format("2006-01")
var stamp int64
key := friendKeyDirectional(self.OwnerIndex, target)
if _, err := load(tx, "friend.room_likes", key, &stamp); err != nil {
return nil, err
}
if stamp != 0 && time.UnixMilli(stamp).UTC().Format("2006-01") == month {
return fail("Room already liked this month")
}
var count roomLikes
if _, err := load(tx, "friend.room_like_counts", numberKey(target), &count); err != nil {
return nil, err
}
if count.Total >= math.MaxInt32 {
return nil, ErrCapacity
}
if count.Month != month {
count.Month = month
count.Monthly = 0
}
count.Total++
count.Monthly++
if err := save(tx, "friend.room_like_counts", numberKey(target), count); err != nil {
return nil, err
}
if err := save(tx, "friend.room_likes", key, now); err != nil {
return nil, err
}
out := wire.AppendVarint(nil, 1, count.Monthly)
out = wire.AppendVarint(out, 2, count.Total)
return wire.AppendVarint(out, 3, uint64(now)), nil
}
if path == "/MyRoomSearchFriend" || path == "/MyRoomSearchGuild" || path == "/MyRoomSearchRecommend" {
return f.searchRooms(tx, self, path, p, now)
}
if path == "/MyRoomItemInfo" {
var out []byte
for _, item := range self.RoomItems {
if item.Type == 28 {
v := wire.AppendVarint(nil, 1, item.InvenIndex)
v = wire.AppendVarint(v, 2, item.ID)
out = wire.AppendBytes(out, 1, v)
}
}
return out, nil
}
if err := f.editRooms(&state, self, path, p); err != nil {
return fail(err.Error())
}
return nil, save(tx, "friend.rooms", numberKey(self.OwnerIndex), state)
}
@@ -0,0 +1,74 @@
package social
import (
"bd2server/internal/server/design/gamedata"
)
func (o *Owner) prepareSupporterClaim(tx Tx, op Operation, reservation *Reservation) error {
if op.Day == "" || len(op.UsageIDs) == 0 || uint64(len(op.UsageIDs)) > o.design.Supporters.DailyRewardClaims {
return ErrInvalid
}
var published FriendProfile
found, err := load(tx, "friend.directory", numberKey(op.Actor.OwnerIndex), &published)
if err != nil {
return err
}
if !found || published.AccountID != op.Actor.AccountID {
return ErrPermission
}
var claimed uint64
key := numberKey(op.Actor.OwnerIndex) + ":" + op.Day
if _, err := load(tx, supporterClaimsBucket, key, &claimed); err != nil {
return err
}
if claimed+uint64(len(op.UsageIDs)) > o.design.Supporters.DailyRewardClaims {
return ErrCapacity
}
seen := map[uint64]bool{}
for _, id := range op.UsageIDs {
if id == 0 || seen[id] {
return ErrInvalid
}
seen[id] = true
key := supporterHistoryKey(op.Actor.OwnerIndex, id)
var usage supporterUsage
found, err := load(tx, supporterHistoryBucket, key, &usage)
if err != nil {
return err
}
if !found || usage.Owner != op.Actor.OwnerIndex || usage.Received || !usage.RewardEligible {
return ErrIneligible
}
reservation.UsageIDs = append(reservation.UsageIDs, id)
}
reward := o.design.Supporters.Reward
reservation.Grants = []gamedata.Reward{{Type: reward.Type, ID: reward.ID, Count: reward.Count * uint64(len(op.UsageIDs))}}
return nil
}
func (o *Owner) confirmSupporterClaim(tx Tx, op Operation) error {
for _, id := range op.UsageIDs {
key := supporterHistoryKey(op.Actor.OwnerIndex, id)
var usage supporterUsage
found, err := load(tx, supporterHistoryBucket, key, &usage)
if err != nil {
return err
}
if !found || usage.Received || !usage.RewardEligible {
return ErrConflict
}
usage.Received = true
if err := save(tx, supporterHistoryBucket, key, usage); err != nil {
return err
}
}
key := numberKey(op.Actor.OwnerIndex) + ":" + op.Day
var claimed uint64
if _, err := load(tx, supporterClaimsBucket, key, &claimed); err != nil {
return err
}
if err := addGameplayCount(tx, op.Actor.OwnerIndex, 0, uint64(len(op.UsageIDs))); err != nil {
return err
}
return save(tx, supporterClaimsBucket, key, claimed+uint64(len(op.UsageIDs)))
}
@@ -0,0 +1,29 @@
package social
import (
"bd2server/internal/server/protocol/wire"
"context"
)
func (s *Service) RankingSnapshot(ctx context.Context, limit int) (uint64, [][]byte, [][]byte, error) {
season, err := s.raidSeason(s.config.Now().UnixMilli())
if err != nil {
return 0, nil, nil, err
}
rows, err := s.config.Owner.Standings(ctx, season.ID)
if err != nil {
return 0, nil, nil, err
}
var out, history [][]byte
for _, row := range rows {
if row.Rank > 0 && row.Rank <= uint64(limit) {
out = append(out, guildRank(row))
}
}
for _, entry := range s.config.RaidSeasons {
if entry.StartsMS <= s.config.Now().UnixMilli() {
history = append(history, wire.AppendVarint(nil, 1, entry.ID))
}
}
return season.ID, out, history, nil
}
@@ -74,6 +74,7 @@ const (
SupporterRemove Kind = "supporter_remove"
Attendance Kind = "attendance"
RaidClaim Kind = "raid_claim"
SupporterClaim Kind = "supporter_claim"
)
type Status string
@@ -150,6 +151,7 @@ type Operation struct {
UseSupporter bool
RequestDigest string
Text string
UsageIDs []uint64
ActionTypes []uint64
Supporter SupporterSlot
}
@@ -164,6 +166,7 @@ type Reservation struct {
Charges []gamedata.Reward
Grants []gamedata.Reward
RequestDigest string
UsageIDs []uint64
EntitlementIDs []string
Application bool
PreparedMS int64
@@ -4,15 +4,16 @@ import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/progression/achievements"
"encoding/json"
"fmt"
"sort"
"strings"
)
// achievements.GameplayAchievementProvider exposes only authoritative owned instances and
// persisted quest/object state. It does not manufacture past acquisition counts.
// persisted quest/object state. Retained history establishes lower bounds.
func (s *Service) GameplayAchievementProvider(ctx command.Context, design *gamedata.AchievementCounterDesign, grades gamedata.GameplayAchievementGrades) *achievements.OwnedGameplayAchievementProvider {
p := &achievements.OwnedGameplayAchievementProvider{Design: design, CharacterGrades: grades.Characters, EquipmentGrades: grades.Equipment}
p := &achievements.OwnedGameplayAchievementProvider{Design: design, CharacterGrades: grades.Characters, EquipmentGrades: grades.Equipment, CostumeGrades: grades.Costumes, CharacterGrowth: grades.CharacterGrowth, EquipmentPrivate: grades.EquipmentPrivate, CostumeMaximum: grades.CostumeMaximum}
observedPeriods := map[[2]int]gamedata.FieldRewardObject{}
p.TransientVersion = func() string {
var signature strings.Builder
@@ -53,7 +54,14 @@ func (s *Service) GameplayAchievementProvider(ctx command.Context, design *gamed
return nil, nil
}
for _, c := range design.Conditions {
if c.Type < 14 || c.Type > 16 {
difficulty := int(c.Type) - 14
if c.Type == 72 {
difficulty = 3
}
if c.Type == 73 {
difficulty = 4
}
if (c.Type < 14 || c.Type > 16) && c.Type != 72 && c.Type != 73 {
continue
}
key := [2]uint64{c.Type, c.SubType}
@@ -67,39 +75,64 @@ func (s *Service) GameplayAchievementProvider(ctx command.Context, design *gamed
}
complete := true
for _, qid := range pack.MainQuestIDs {
if !s.state.QuestCleared(qid, pack.ID, int(c.Type-14)) {
if !s.state.QuestCleared(qid, pack.ID, difficulty) {
complete = false
break
}
}
if complete {
conditions = append(conditions, achievements.GameplayAchievementCondition{Type: c.Type, SubType: c.SubType, Value: 1})
conditions = append(conditions, achievements.GameplayAchievementCondition{Type: c.Type, SubType: c.SubType, Value: 1, LowerBound: true})
}
}
return conditions, nil
}
var worldConditions []achievements.GameplayAchievementCondition
var researchObjects map[string]gamedata.FieldResearchObject
var previousSignature string
var previousObjects map[string]gamedata.FieldRewardObject
p.FieldObjects = func(ctx command.Context) (map[string]gamedata.FieldRewardObject, error) {
observedPeriods = map[[2]int]gamedata.FieldRewardObject{}
objects := map[string]gamedata.FieldRewardObject{}
openedPeriods, err := s.state.OpenedFieldRewardPeriods(ctx)
if err != nil {
return nil, err
}
// Opened IDs are persisted independently of quest difficulty. Only loaded
// packs with real opened entries require their reward design to be resolved.
research, err := s.state.AllResearchObjects(ctx)
if err != nil {
return nil, err
}
var waypointCount uint64
if s.decks != nil {
waypointCount = s.decks.ActivatedWaypointCount()
}
cleared := s.state.AllClearedQuests()
raw, err := json.Marshal([]any{openedPeriods, research, cleared, waypointCount, p.TransientVersion()})
if err != nil {
return nil, err
}
if signature := string(raw); signature == previousSignature && previousObjects != nil {
return previousObjects, nil
}
observedPeriods = map[[2]int]gamedata.FieldRewardObject{}
objects := map[string]gamedata.FieldRewardObject{}
values := map[[2]uint64]uint64{}
add := func(kind, sub, count uint64) { values[[2]uint64{kind, sub}] += count }
add(32, 0, waypointCount)
for _, q := range cleared {
if s.storyCatalog != nil && q.Difficulty == 0 && s.storyCatalog.Packs[q.PackID].Quests[q.QuestID].Type == 2 {
add(18, 0, 1)
}
}
packs := map[int]bool{}
for id := range s.packs {
for id := range openedPeriods {
packs[id] = true
}
for id := range s.fieldPacks {
for id := range research {
packs[id] = true
}
projectedResearch := map[string]gamedata.FieldResearchObject{}
collections := map[int]bool{}
for pack := range packs {
periods := openedPeriods[pack]
if len(periods) == 0 {
continue
}
d, err := s.fieldObjectDesign(ctx, pack)
d, err := s.achievementFieldDesign(ctx, pack)
if err != nil {
return nil, err
}
@@ -109,6 +142,14 @@ func (s *Service) GameplayAchievementProvider(ctx command.Context, design *gamed
return nil, fmt.Errorf("achievement: opened field design absent")
}
observedPeriods[[2]int{pack, obj.ResetType}] = obj
switch obj.Type {
case 1:
add(28, 0, 1)
case 2:
add(31, 0, 1)
case 5:
add(30, 0, 1)
}
period, err := s.fieldObjectPeriodFor(pack, obj)
if err != nil {
continue
@@ -117,8 +158,86 @@ func (s *Service) GameplayAchievementProvider(ctx command.Context, design *gamed
objects[fmt.Sprintf("field:%d:%d:%s", pack, id, period)] = obj
}
}
rd, err := s.researchDesign(pack)
if err != nil {
return nil, err
}
for id := range research[pack] {
obj, found := rd.Objects[id]
if !found {
return nil, fmt.Errorf("achievement: researched field design absent")
}
projectedResearch[fmt.Sprintf("research:%d:%d", pack, id)] = obj
add(29, 0, 1)
if obj.CollectionID > 0 {
collections[obj.CollectionID] = true
}
}
mapComplete := map[int]bool{}
mapHasRewards := map[int]bool{}
check := func(mapID int, completed bool) {
if !mapHasRewards[mapID] {
mapComplete[mapID] = true
}
mapHasRewards[mapID] = true
mapComplete[mapID] = mapComplete[mapID] && completed
}
for id, obj := range d.Objects {
if matchesFieldCount(obj, 2) {
check(obj.MapID, periods[id] == "once")
}
}
for id, obj := range rd.Objects {
if obj.Reward.Type == 0 && obj.CollectionID == 0 {
continue
}
for _, mapID := range obj.Maps {
check(mapID, research[pack][id])
}
}
packComplete := len(mapHasRewards) > 0
for mapID := range mapHasRewards {
if mapComplete[mapID] {
add(33, uint64(mapID), 1)
} else {
packComplete = false
}
}
if packComplete {
add(34, uint64(pack), 1)
}
}
add(5, 0, uint64(len(collections)))
projectedConditions := make([]achievements.GameplayAchievementCondition, 0, len(values))
for key, value := range values {
projectedConditions = append(projectedConditions, achievements.GameplayAchievementCondition{Type: key[0], SubType: key[1], Value: value, LowerBound: true})
}
worldConditions, researchObjects, previousObjects = projectedConditions, projectedResearch, objects
// Period discovery changes the transient signature on the first projection.
raw, _ = json.Marshal([]any{openedPeriods, research, cleared, waypointCount, p.TransientVersion()})
previousSignature = string(raw)
return objects, nil
}
p.Project = func(_ command.Context, snapshot *achievements.GameplayAchievementSnapshot) error {
snapshot.Conditions = append(snapshot.Conditions, worldConditions...)
snapshot.ResearchObjects = researchObjects
return nil
}
return p
}
func (s *Service) achievementFieldDesign(ctx command.Context, pack int) (gamedata.FieldObjectDesign, error) {
if design, found := s.fieldObjects[pack]; found {
return design, nil
}
if s.storyCatalog != nil {
if _, known := s.storyCatalog.Packs[pack]; known && s.fieldObjectLoader != nil {
design, err := s.fieldObjectLoader(pack)
if err == nil {
s.fieldObjects[pack] = design
}
return design, err
}
}
return s.fieldObjectDesign(ctx, pack)
}
@@ -0,0 +1,114 @@
//go:build integration
package world
import (
"testing"
"time"
"bd2server/internal/server/design/gamedata"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
)
// GameData 20261008155037 pack5 object5120 is the searchable HiddenBox in
// map51, group12: weekly reset and one182-unit crafting-material draw.
// FieldPacket.WeeklyResetFieldRewardObjects restores this group at reset;
// resetting does not grant anything until the player collects it again.
func TestHiddenInvestigationRewardBecomesCollectibleOnceAtWeeklyReset(t *testing.T) {
ctx, service, source := fieldQuestIntegration(t, 5)
schedule, err := gamedata.LoadFieldResetSchedule(source.Root(), source.Version())
if err != nil {
t.Fatal(err)
}
if err := service.AttachFieldObjectRuntime(source, schedule); err != nil {
t.Fatal(err)
}
service.packs = map[int]map[int]gamedata.QuestDesign{5: service.storyCatalog.Packs[5].Quests}
service.wallet, err = assets.OpenWallet(ctx, stateio.RootStore{}, assets.Currency{})
if err != nil {
t.Fatal(err)
}
service.inventory, err = assets.OpenInventory(ctx, stateio.RootStore{}, nil)
if err != nil {
t.Fatal(err)
}
stacks, err := gamedata.LoadItemStackDesign(source.Root(), source.Version())
if err != nil {
t.Fatal(err)
}
if err := service.inventory.AttachItemStacks(stacks); err != nil {
t.Fatal(err)
}
if err := service.state.SaveUserPosition(ctx, wire.AppendString(wire.AppendVarint(nil, 2, 5), 3, `{"MapId":51}`)); err != nil {
t.Fatal(err)
}
reset := time.Date(2026, time.October, 12, 0, 0, 0, 0, time.UTC)
now := reset.Add(-time.Millisecond)
service.monsterNow = func() time.Time { return now }
seq := uint64(0)
handle := func(path string, fields []byte) []byte {
t.Helper()
seq++
_, response, handled, err := service.Handle(ctx, path, append(wire.AppendVarint(nil, 1, seq), fields...))
if err != nil || !handled {
t.Fatalf("%s: handled=%v err=%v", path, handled, err)
}
return response
}
materials := func() uint64 {
var total uint64
for _, item := range service.inventory.All(ctx) {
if item.Type == 8 && (item.ID == 301 || item.ID == 401 || item.ID == 204) {
total += item.Count
}
}
return total
}
assertCollected := func(want bool) {
t.Helper()
response := handle("/FieldObjectPreview", wire.AppendVarint(nil, 2, 5))
found := false
if err := wire.Walk(response, func(f wire.Field) error {
if f.Number == 1 && f.Type == 2 {
id, _, err := wire.Varint(f.Value, 1)
if err != nil {
return err
}
found = found || id == 5120
}
return nil
}); err != nil {
t.Fatal(err)
}
if found != want {
t.Fatalf("preview reported collected=%v want%v at%v", found, want, now)
}
}
collect := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 2, 5), 3, 12), 4, 5120)
assertCollected(false)
handle("/FieldObjectReward", collect)
assertCollected(true)
if total := materials(); total != 182 {
t.Fatalf("first collection granted%d materials, want182", total)
}
handle("/FieldObjectReward", collect)
if total := materials(); total != 182 {
t.Fatalf("same-period collection duplicated materials:%d", total)
}
now = reset
assertCollected(false)
if total := materials(); total != 182 {
t.Fatalf("weekly reset granted uncollected materials:%d", total)
}
handle("/FieldObjectReward", collect)
assertCollected(true)
if total := materials(); total != 364 {
t.Fatalf("next-period collection granted%d materials, want364", total)
}
handle("/FieldObjectReward", collect)
if total := materials(); total != 364 {
t.Fatalf("next-period retry duplicated materials:%d", total)
}
}
@@ -127,6 +127,46 @@ func TestForestMonsterVictorySurvivesDifficultyChangeUntilWeeklyReset(t *testing
if err != nil || count != want {
t.Fatalf("forest defeat count=%d want=%d err=%v", count, want, err)
}
// FieldObjectSceneData1 places101-105 in forest map2 and111-115 in
// cave map3. Native PackMapRewardInfo derives each map's remaining
// monsters from ActiveFlag and RespawnTime, excluding story encounters.
rows, err := service.packMonsterRows(ctx, 1)
if err != nil {
t.Fatal(err)
}
var forestRows, caveRows, forestDefeated, caveDefeated uint64
for _, row := range rows {
id, _, err := wire.Varint(row, 1)
if err != nil {
t.Fatal(err)
}
active, _, err := wire.Varint(row, 6)
if err != nil {
t.Fatal(err)
}
respawn, _, err := wire.Varint(row, 3)
if err != nil {
t.Fatal(err)
}
defeated := active == 0 || respawn > uint64(now.UnixMilli())
switch {
case id >= 101 && id <= 105:
forestRows++
if defeated {
forestDefeated++
}
case id >= 111 && id <= 115:
caveRows++
if defeated {
caveDefeated++
}
default:
t.Fatalf("story or unplaced monster polluted map detail:%d", id)
}
}
if forestRows != 5 || caveRows != 5 || forestDefeated != want || caveDefeated != 0 {
t.Fatalf("forest completed%d/5 cave completed%d/5, rows%d,%d wantforest%d cave0", forestDefeated, caveDefeated, forestRows, caveRows, want)
}
}
assertCount(0)
start(1)
@@ -294,6 +294,27 @@ func (s *Store) QuestCleared(questID, packID int, level ...int) bool {
return found
}
func (s *Store) AllClearedQuests() []QuestProgress {
out := make([]QuestProgress, 0, len(s.cleared))
for key := range s.cleared {
pack, difficulty, quest, ok := parseQuestKey(key)
if ok {
out = append(out, QuestProgress{PackID: pack, Difficulty: difficulty, QuestID: quest})
}
}
sort.Slice(out, func(i, j int) bool {
a, b := out[i], out[j]
if a.PackID != b.PackID {
return a.PackID < b.PackID
}
if a.Difficulty != b.Difficulty {
return a.Difficulty < b.Difficulty
}
return a.QuestID < b.QuestID
})
return out
}
// ClearedQuests returns sorted quest IDs for one pack. The detached slice is
// safe for response construction without holding the store lock.
func (s *Store) ClearedQuests(packID int, level ...int) []int {
@@ -35,6 +35,31 @@ func (s *Store) ResearchObjects(ctx command.Context, pack int) ([]int, error) {
sort.Ints(ids)
return ids, nil
}
func (s *Store) AllResearchObjects(ctx command.Context) (map[int]map[int]bool, error) {
store, err := s.fieldRewardEntries()
if err != nil {
return nil, err
}
entries, err := store.ListEntries(ctx.State, "progress", "field_research")
if err != nil {
return nil, err
}
out := map[int]map[int]bool{}
for key, raw := range entries {
packKey, objectKey, found := strings.Cut(key, ":")
pack, packErr := strconv.Atoi(packKey)
id, idErr := strconv.Atoi(objectKey)
if !found || packErr != nil || idErr != nil || pack <= 0 || id <= 0 || key != fieldRewardKey(pack, id) || string(raw) != "once" {
return nil, fmt.Errorf("progress: invalid research identity")
}
if out[pack] == nil {
out[pack] = map[int]bool{}
}
out[pack][id] = true
}
return out, nil
}
func (s *Store) ResearchObjectReply(ctx command.Context, pack, id int) ([]byte, bool, error) {
store, err := s.fieldRewardEntries()
@@ -59,6 +59,13 @@ func (s *Service) packInfoFor(ctx command.Context, packID int) ([]byte, error) {
return nil, err
}
out = append(out, buffs...)
research, err := s.state.ResearchObjects(ctx, packID)
if err != nil {
return nil, err
}
for _, id := range research {
out = wire.AppendVarint(out, 11, uint64(id))
}
if s.huntingGround == nil {
return out, nil
}
@@ -159,6 +159,17 @@ func TestForestSideQuestCompletionSurvivesPackEntry(t *testing.T) {
if err != nil || id != uint64(step.next) || levelErr != nil || level != 0 {
t.Fatalf("forest continuation must remain normal side quest %d: id=%d level=%d", step.next, id, level)
}
// QuestPacket plays the completion cinema before the next objective;
// LoginUI acknowledges that presentation at its native end callback.
presentation, err := service.StoryCheckpoint(ctx, StoryCheckpointRequest{Operation: "read"})
if err != nil {
t.Fatal(err)
}
if presentation.Checkpoint != nil {
if _, err := service.StoryCheckpoint(ctx, StoryCheckpointRequest{Operation: "complete", StoryCheckpoint: StoryCheckpoint{ID: presentation.Checkpoint.ID}}); err != nil {
t.Fatal(err)
}
}
})
run(func(ctx command.Context, service *Service) {
rows := service.activeSideQuestWires(1)
@@ -109,8 +109,18 @@ func (s *Service) StoryCheckpoint(ctx command.Context, request StoryCheckpointRe
func (s *Service) validateStoryCheckpoint(ctx command.Context, checkpoint StoryCheckpoint) error {
pack, exists := s.storyCatalog.Packs[checkpoint.PackID]
if !exists || !s.packUnlocked(ctx, checkpoint.PackID) || checkpoint.Difficulty != s.questDifficultyFor(checkpoint.PackID, checkpoint.QuestID) || !slices.Contains(pack.MapIDs, checkpoint.MapID) {
return ErrInvalidRequest
if !exists || !s.packUnlocked(ctx, checkpoint.PackID) || checkpoint.Difficulty != s.questDifficultyFor(checkpoint.PackID, checkpoint.QuestID) {
return fmt.Errorf("%w: checkpoint pack or difficulty unavailable", ErrInvalidRequest)
}
if s.packDetailDesign == nil {
return fmt.Errorf("world: checkpoint map design unavailable")
}
maps, err := s.packDetailDesign(checkpoint.PackID)
if err != nil {
return err
}
if !slices.Contains(maps.MapIDs, checkpoint.MapID) {
return fmt.Errorf("%w: checkpoint map outside pack", ErrInvalidRequest)
}
quest, exists := pack.Quests[checkpoint.QuestID]
if !exists {
@@ -0,0 +1,138 @@
package auth
import (
"bd2server/internal/server/domain/identity"
"bd2server/internal/server/gateway/authconfig"
identitystore "bd2server/internal/server/storage/identity"
"context"
"database/sql"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strconv"
"testing"
"time"
)
func TestSessionProfileUsesAuthenticatedAccount(t *testing.T) {
identityPath := filepath.Join(t.TempDir(), "identity.db")
store, err := identitystore.Open(identityPath, make([]byte, 32))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := store.Close(); err != nil {
t.Error(err)
}
})
service, err := New(authconfig.Runtime{
Config: authconfig.Config{Mode: "oauth", Providers: map[string]authconfig.ProviderConfig{"discord": {ClientID: "test-client"}}},
AccessTTL: time.Hour, RefreshTTL: 24 * time.Hour, DeviceTTL: time.Minute,
}, store)
if err != nil {
t.Fatal(err)
}
login := func(subject string) identity.TokenSet {
t.Helper()
device, err := service.identity.CreateDevice("discord", "127.0.0.1")
if err != nil {
t.Fatal(err)
}
authorization, err := service.identity.Start("discord", device.ID, device.StartTicket)
if err != nil {
t.Fatal(err)
}
if err := service.identity.CompleteDevice(authorization.ID, "discord", identity.ProviderIdentity{Issuer: "https://discord.com", Subject: subject}); err != nil {
t.Fatal(err)
}
result, err := service.identity.Poll(device.ID, device.Secret)
if err != nil {
t.Fatal(err)
}
return result.Tokens
}
a, b := login("111111"), login("222222")
profileFor := func(token string) identity.GameProfile {
t.Helper()
account, err := service.ValidateAccess(token)
if err != nil {
t.Fatal(err)
}
profile, err := store.GameIdentity(context.Background(), account)
if err != nil {
t.Fatal(err)
}
return identity.GameProfile{AccountID: account, UID: strconv.FormatInt(profile.OwnerIndex, 10)}
}
aProfile, bProfile := profileFor(a.AccessToken), profileFor(b.AccessToken)
if aProfile.AccountID == bProfile.AccountID || aProfile.UID == bProfile.UID {
t.Fatal("device registrations did not create distinct game identities")
}
// Imported profiles can retain a display name in user_id; the client UID
// shown by UserInfoPanel.UpdateUID is the numeric owner_index.
db, err := sql.Open("sqlite", identityPath)
if err != nil {
t.Fatal(err)
}
nickname := "Guest_" + aProfile.UID
if _, err := db.Exec(`UPDATE game_profiles SET user_id=? WHERE account_id=?`, nickname, aProfile.AccountID); err != nil {
_ = db.Close()
t.Fatal(err)
}
if err := db.Close(); err != nil {
t.Fatal(err)
}
retained, err := store.GameIdentity(context.Background(), aProfile.AccountID)
if err != nil || retained.UserID != nickname || strconv.FormatInt(retained.OwnerIndex, 10) != aProfile.UID {
t.Fatalf("persisted nickname and UID fixture = %+v: %v", retained, err)
}
handler := service.Handler()
request := func(method, path, authorization string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest(method, path, nil)
if authorization != "" {
r.Header.Set("Authorization", authorization)
}
w := httptest.NewRecorder()
handler.ServeHTTP(w, r)
return w
}
for _, authorization := range []string{"", "Bearer ", "Device secret", "Bearer invalid"} {
if w := request(http.MethodGet, "/auth/session/profile", authorization); w.Code != http.StatusUnauthorized {
t.Fatalf("unauthorized profile status = %d", w.Code)
}
}
assertProfile := func(path, token string, want identity.GameProfile) {
t.Helper()
w := request(http.MethodGet, path, "Bearer "+token)
if w.Code != http.StatusOK {
t.Fatalf("profile status = %d: %s", w.Code, w.Body.String())
}
var fields map[string]string
if err := json.Unmarshal(w.Body.Bytes(), &fields); err != nil {
t.Fatal(err)
}
if len(fields) != 2 || fields["account_id"] != want.AccountID || fields["uid"] != want.UID {
t.Fatalf("profile = %v, want account %s UID %s", fields, want.AccountID, want.UID)
}
if w.Header().Get("Cache-Control") != "no-store" {
t.Fatal("profile response can be cached")
}
}
assertProfile("/auth/session/profile", a.AccessToken, aProfile)
assertProfile("/auth/session/profile", b.AccessToken, bProfile)
query := url.Values{"account_id": {bProfile.AccountID}, "uid": {bProfile.UID}}
assertProfile("/auth/session/profile?"+query.Encode(), a.AccessToken, aProfile)
if w := request(http.MethodPost, "/auth/session/revoke", "Bearer "+a.AccessToken); w.Code != http.StatusNoContent {
t.Fatalf("revoke status = %d: %s", w.Code, w.Body.String())
}
if w := request(http.MethodGet, "/auth/session/profile", "Bearer "+a.AccessToken); w.Code != http.StatusUnauthorized {
t.Fatalf("revoked profile status = %d", w.Code)
}
if _, err := service.identity.Refresh(a.RefreshToken, "binding-revoked-family"); err == nil {
t.Fatal("binding token revocation left its refresh token usable")
}
assertProfile("/auth/session/profile", b.AccessToken, bProfile)
}
@@ -62,6 +62,7 @@ func (s *Service) Handler() http.Handler {
mux.HandleFunc("POST /auth/device/{id}/poll", s.poll)
mux.HandleFunc("POST /auth/session/refresh", s.refresh)
mux.HandleFunc("POST /auth/session/revoke", s.revoke)
mux.HandleFunc("GET /auth/session/profile", s.profile)
return securityHeaders(mux)
}
func securityHeaders(next http.Handler) http.Handler {
@@ -287,6 +288,20 @@ func (s *Service) revoke(w http.ResponseWriter, r *http.Request) {
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Service) profile(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") || strings.TrimPrefix(auth, "Bearer ") == "" {
http.Error(w, "access token required", http.StatusUnauthorized)
return
}
profile, err := s.identity.SessionProfile(r.Context(), strings.TrimPrefix(auth, "Bearer "))
if err != nil {
writeFailure(w, err, "profile unavailable")
return
}
writeJSON(w, http.StatusOK, profile)
}
func (s *Service) ValidateAccess(token string) (string, error) {
return s.identity.ValidateAccess(token)
}
@@ -36,8 +36,6 @@ var emptyResponses = map[string]int{
"/GuildInitInfo": 332,
"/IdCardPresetInfo": 450,
"/LifeUserInfo": 594,
"/MyLikeInfo": 218,
"/MyRoomItemInfo": 232,
"/PersonalInfo": 199,
"/QuestMaxClearInfo": 137,
"/SpineInteractionAchievementInfo": 532,
@@ -14,8 +14,6 @@ var standaloneDefaults = map[string]int{
"/PvpBattleDeckInfo": 87,
"/PvpBattleHistory": 97,
"/PvpBattleOnceRewardInfo": 277,
"/SupporterStatus": 438,
"/SupporterBattleInfo": 439,
}
// commandSuccess contains idempotent local mutations whose response type is
@@ -312,6 +312,20 @@ type GameProfile struct {
UserID string
}
func (s *Store) PublicGameProfile(ctx context.Context, accountID string) (identity.GameProfile, error) {
var profile identity.GameProfile
var ownerIndex int64
err := s.db.QueryRowContext(ctx, `SELECT account_id,owner_index FROM game_profiles WHERE account_id=?`, accountID).Scan(&profile.AccountID, &ownerIndex)
if err != nil {
return identity.GameProfile{}, err
}
if profile.AccountID == "" || ownerIndex <= 0 {
return identity.GameProfile{}, errors.New("auth: public game identity invalid")
}
profile.UID = strconv.FormatInt(ownerIndex, 10)
return profile, nil
}
func allocateGameProfile(tx *sql.Tx, accountID string) (GameProfile, error) {
var maximum int64
if err := tx.QueryRow(`SELECT COALESCE(MAX(owner_index),0) FROM game_profiles`).Scan(&maximum); err != nil {
+11
View File
@@ -0,0 +1,11 @@
<Project DefaultTargets="Build">
<ItemGroup>
<ClientPlugin Include="LocalIdentity/LocalIdentity.csproj;LoginUI/LoginUI.csproj;CashShop/CashShop.csproj;FChat/FChat.csproj" />
</ItemGroup>
<Target Name="Restore">
<MSBuild Projects="@(ClientPlugin)" Targets="Restore" BuildInParallel="true" />
</Target>
<Target Name="Build">
<MSBuild Projects="@(ClientPlugin)" Targets="Build" BuildInParallel="true" />
</Target>
</Project>
+15 -5
View File
@@ -33,18 +33,28 @@
"fchat.error.not_found": "API endpoint or model not found.",
"fchat.error.rate_limit": "API quota or rate limit reached.",
"fchat.error.unavailable": "Translation API is temporarily unavailable.",
"fchat.error.rejected": "Translation API rejected the request (HTTP %s).",
"fchat.error.rejected": "Translation API rejected the request (HTTP {0}).",
"fchat.error.connection": "Translation request timed out or could not connect.",
"fchat.test.connected": "Connected: %s",
"fchat.test.connected": "Connected: {0}",
"fchat.test.canceled": "Test canceled.",
"fchat.test.connection_failed": "Translation connection failed; check your settings.",
"fchat.test.sample": "Hello, nice to meet you.",
"fchat.policy.rejected": "This text was rejected. Please edit it and try again.",
"fchat.policy.unavailable": "Text review is temporarily unavailable. Please try again later.",
"fchat.error.secret_large": "Saved API key is too large.",
"fchat.error.secret_unsupported": "Secure API key storage is unavailable.",
"fchat.error.secret_failed": "Secure API key storage failed (OSStatus %s).",
"fchat.error.secret_failed": "Secure API key storage failed (OSStatus {0}).",
"fchat.error.secret_protect": "Windows could not protect the API key.",
"fchat.error.secret_unprotect": "Windows could not decrypt the API key.",
"fchat.error.secret_empty": "The credential store returned an empty value."
"fchat.error.secret_empty": "The credential store returned an empty value.",
"fchat.panel.own_messages": "Translate my own messages",
"fchat.panel.target_label": "Target language",
"fchat.panel.target_hint": "Empty = game UI language",
"fchat.panel.blacklist_label": "Language blacklist",
"fchat.panel.blacklist_hint": "e.g. English, Japanese",
"fchat.panel.loading": "Loading native settings controls…",
"fchat.panel.controls_failed": "Could not load settings controls. Close and reopen this panel.",
"fchat.help.target": "Describe the target language in natural language, for example “Simplified Chinese”, “British English” or “Japanese”. Leave this field empty to use your current game UI language. The AI interprets your description when translating.",
"fchat.help.blacklist": "Enter language names or descriptions in natural language, separated by commas, for example “English, Japanese”. Leave empty to allow all languages. The AI must identify the actual language of each message. This cannot be reliably determined locally, so message content may still be sent to your configured AI API even when translation is skipped. Language identification may consume additional tokens and incur charges. Set your API budget accordingly.",
"fchat.error.target_invalid": "Target language must be a single line of at most 200 characters.",
"fchat.error.blacklist_invalid": "Language blacklist must be a single line of at most 2,000 characters."
}
+15 -5
View File
@@ -33,18 +33,28 @@
"fchat.error.not_found": "APIの接続先またはモデルが見つかりません。",
"fchat.error.rate_limit": "APIの利用枠またはリクエスト頻度の上限に達しました。",
"fchat.error.unavailable": "翻訳APIは一時的に利用できません。",
"fchat.error.rejected": "翻訳APIがリクエストを拒否しました(HTTP %s)。",
"fchat.error.rejected": "翻訳APIがリクエストを拒否しました(HTTP {0})。",
"fchat.error.connection": "翻訳リクエストがタイムアウトしたか、接続できませんでした。",
"fchat.test.connected": "接続成功:%s",
"fchat.test.connected": "接続成功:{0}",
"fchat.test.canceled": "テストをキャンセルしました。",
"fchat.test.connection_failed": "翻訳サービスへの接続に失敗しました。設定を確認してください。",
"fchat.test.sample": "こんにちは。お会いできてうれしいです。",
"fchat.policy.rejected": "この文章は却下されました。修正してから再試行してください。",
"fchat.policy.unavailable": "文章の審査は一時的に利用できません。後で再試行してください。",
"fchat.error.secret_large": "保存されたAPIキーが長すぎます。",
"fchat.error.secret_unsupported": "APIキーの安全な保存機能を利用できません。",
"fchat.error.secret_failed": "APIキーの安全な保存に失敗しました(OSStatus %s)。",
"fchat.error.secret_failed": "APIキーの安全な保存に失敗しました(OSStatus {0})。",
"fchat.error.secret_protect": "WindowsでAPIキーを暗号化できませんでした。",
"fchat.error.secret_unprotect": "WindowsでAPIキーを復号できませんでした。",
"fchat.error.secret_empty": "キーの保存機能が空の値を返しました。"
"fchat.error.secret_empty": "キーの保存機能が空の値を返しました。",
"fchat.panel.own_messages": "自分のメッセージも翻訳する",
"fchat.panel.target_label": "翻訳先の言語",
"fchat.panel.target_hint": "空欄の場合はゲームの表示言語",
"fchat.panel.blacklist_label": "翻訳しない言語",
"fchat.panel.blacklist_hint": "例:英語, 日本語",
"fchat.panel.loading": "ゲーム標準の設定項目を読み込み中…",
"fchat.panel.controls_failed": "設定項目を読み込めませんでした。閉じてから開き直してください。",
"fchat.help.target": "「簡体字中国語」「イギリス英語」「日本語」など、翻訳先の言語を自然な言葉で指定してください。空欄の場合は現在のゲームの表示言語を使います。AI が入力した説明を解釈して翻訳します。",
"fchat.help.blacklist": "翻訳しない言語の名前や説明を自然な言葉で入力し、複数ある場合は「英語, 日本語」のようにカンマで区切ってください。空欄の場合はすべての言語を許可します。各メッセージの実際の言語を AI が識別する必要があります。端末だけでは確実に判定できないため、翻訳を省略する場合もメッセージが設定した AI API に送信されることがあります。言語の識別で追加のトークンや料金が発生する場合があります。API の予算を適切に設定してください。",
"fchat.error.target_invalid": "翻訳先の言語は 200 文字以内の 1 行で入力してください。",
"fchat.error.blacklist_invalid": "翻訳しない言語は 2000 文字以内の 1 行で入力してください。"
}
+15 -5
View File
@@ -33,18 +33,28 @@
"fchat.error.not_found": "API 주소 또는 모델을 찾을 수 없습니다.",
"fchat.error.rate_limit": "API 사용량 또는 요청 빈도 제한에 도달했습니다.",
"fchat.error.unavailable": "번역 API를 일시적으로 사용할 수 없습니다.",
"fchat.error.rejected": "번역 API가 요청을 거부했습니다(HTTP %s).",
"fchat.error.rejected": "번역 API가 요청을 거부했습니다(HTTP {0}).",
"fchat.error.connection": "번역 요청 시간이 초과되었거나 연결하지 못했습니다.",
"fchat.test.connected": "연결 성공: %s",
"fchat.test.connected": "연결 성공: {0}",
"fchat.test.canceled": "테스트가 취소되었습니다.",
"fchat.test.connection_failed": "번역 서비스 연결에 실패했습니다. 설정을 확인하세요.",
"fchat.test.sample": "안녕하세요. 만나서 반갑습니다.",
"fchat.policy.rejected": "이 텍스트가 거부되었습니다. 수정한 후 다시 시도하세요.",
"fchat.policy.unavailable": "텍스트 검토를 일시적으로 사용할 수 없습니다. 나중에 다시 시도하세요.",
"fchat.error.secret_large": "저장된 API 키가 너무 깁니다.",
"fchat.error.secret_unsupported": "안전한 API 키 저장소를 사용할 수 없습니다.",
"fchat.error.secret_failed": "안전한 API 키 저장에 실패했습니다(OSStatus %s).",
"fchat.error.secret_failed": "안전한 API 키 저장에 실패했습니다(OSStatus {0}).",
"fchat.error.secret_protect": "Windows에서 API 키를 암호화하지 못했습니다.",
"fchat.error.secret_unprotect": "Windows에서 API 키를 복호화하지 못했습니다.",
"fchat.error.secret_empty": "키 저장소가 빈 값을 반환했습니다."
"fchat.error.secret_empty": "키 저장소가 빈 값을 반환했습니다.",
"fchat.panel.own_messages": "내가 보낸 메시지도 번역",
"fchat.panel.target_label": "번역 대상 언어",
"fchat.panel.target_hint": "비워 두면 현재 게임 표시 언어 사용",
"fchat.panel.blacklist_label": "번역 제외 언어",
"fchat.panel.blacklist_hint": "예: 영어, 일본어",
"fchat.panel.loading": "게임 기본 설정 컨트롤을 불러오는 중…",
"fchat.panel.controls_failed": "설정 컨트롤을 불러오지 못했습니다. 창을 닫고 다시 열어 주세요.",
"fchat.help.target": "“간체 중국어”, “영국 영어”, “일본어”처럼 번역할 대상 언어를 자연어로 입력하세요. 비워 두면 현재 게임 표시 언어를 사용합니다. AI가 입력한 설명을 해석하여 번역합니다.",
"fchat.help.blacklist": "번역하지 않을 언어의 이름이나 설명을 자연어로 입력하세요. 여러 언어는 “영어, 일본어”처럼 쉼표로 구분하세요. 비워 두면 모든 언어를 허용합니다. AI가 각 메시지의 실제 언어를 식별해야 합니다. 기기에서만 이를 정확하게 판단할 수 없으므로 번역을 건너뛰더라도 메시지 내용이 설정한 AI API로 전송될 수 있습니다. 언어 식별에 추가 토큰이 소모되고 요금이 발생할 수 있으니 API 예산을 적절히 설정하세요.",
"fchat.error.target_invalid": "번역 대상 언어는 200자 이내의 한 줄로 입력하세요.",
"fchat.error.blacklist_invalid": "번역 제외 언어는 2000자 이내의 한 줄로 입력하세요."
}
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff. Show more